# ---- __init__.py ----
# SPDX-License-Identifier: Apache-2.0
"""Token-budget continuous-batching scheduler.

Two surfaces:

  - :class:`Scheduler` — single-FIFO continuous batcher for the active
    resident.
  - :class:`MultiGroupQueue` — the graceful cross-resident park queue
    with swap-cost-aware selection, drained by the run loop's stable-VA
    residency advance.
"""

from arbi_serve.scheduler.multi_group import GroupKey, MultiGroupQueue
from arbi_serve.scheduler.scheduler import Scheduler

__all__ = ["GroupKey", "MultiGroupQueue", "Scheduler"]
# ---- _request_state_reach.py ----
# SPDX-License-Identifier: Apache-2.0
"""Per-request state mapping reach, including the admitted draft lookahead."""

from __future__ import annotations

from arbi_serve.engine.request import Request, folded_output, speculative_lookahead_reserve


def _max_reachable_context(req: Request) -> int | None:
    """The furthest context ``req`` can ever reach: prompt + output budget + speculative lookahead.

    ``None`` when the request carries no ``max_tokens`` — it then runs until
    a stop matches or the engine's max context does, so the pool resolves the
    target against its own reservation. A duplex-lane request is ``None`` for
    the same reason from the other side: its context also grows by the tokens
    the lane injects (``pending_context_token_ids``), which no admission-time
    sum can bound. This is the growth target for a state pool that backs its
    stores on demand: growing to the request's CURRENT length instead would
    re-map on every token.

    INVARIANT UNDER A RE-PREFILL FOLD, which is what lets a bound be
    measured against it: the fold moves tokens from the output budget into
    the prompt, growing the first term and shrinking the second by the same
    count, so a request that is preempted (or recovered) repeatedly cannot
    inflate its own reach by being re-read.
    """
    max_tokens = getattr(req.sampling, "max_tokens", None)
    if max_tokens is None or getattr(req, "is_duplex_frame", False):
        return None
    remaining = int(max_tokens) - len(folded_output(req))
    lookahead = speculative_lookahead_reserve(
        req.sampling, architecture_reserve=getattr(req, "speculative_context_reserve", 0)
    )
    return len(req.prompt_token_ids) + max(0, remaining) + (lookahead if remaining > 0 else 0)
# ---- activation_budget.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Admission-time accounting for one step's forward-activation bytes.

Admission commits KV PAGES per row and refuses a row it cannot page
(``Scheduler._can_allocate_reserved``). It commits nothing for the bytes that
row's tokens will allocate in the forward, so a slate whose pages fit but whose
GEMM / gather working set does not is admitted anyway and the forward OOMs —
after the Phase-2 freeze, with KV already locked, i.e. as a client-visible 500.
The serving floor
(:func:`~arbi_serve.engine.inprocess_capture.serving_floor_for_grow`) reserves
free VRAM for that working set, but a reserve is only a promise about a state
nothing prevents; this module is the matching enforcement, so the state the
floor fears is unreachable rather than merely unlikely.

The model
--------
One step's forward activation bytes, as a function of the three quantities
admission already has in hand while it builds the slate::

    demand = per_prefill_token x prefill_tokens
           + per_row           x rows
           + per_gather_kv_token x gather_kv_tokens
           + per_query_token   x query_tokens

``prefill_tokens`` and ``rows`` are the axes the boot activation profile
measures directly (:mod:`arbi_serve.runtime.activation_profile` runs a pure
decode shape at ``max_batch`` rows and a pure prefill shape at
``max_batched_tokens``), so the two slopes are a two-point calibration on
measured data rather than an analytic model of the layer stack.

``query_tokens`` is the DECODE-ROW query width past one token each. Every
profiled shape above runs its decode rows at exactly one token, but a served
MTP verify step runs ``K + 1`` flat tokens per opted row
(:func:`~arbi_serve.spec_decode.mtp_verify_plan.build_verify_plan`). On a
capture hit those bytes are the graph pool's and are budgeted there; on a MISS
the step falls to a full eager per-layer forward at that width
(``EagerModelRunner``'s ``eager_verify_offladder`` rung) whose activations land
in ``scratch.forward_arena``. The axis is therefore reachable, unbudgeted
without this term, and measured by its own profiled shape
(:data:`~arbi_serve.runtime.activation_profile.SHAPE_VERIFY_FORWARD`) rather
than derived from the decode shape. The PAGE side of the same step already
reserves it — :meth:`~arbi_serve.scheduler.scheduler_allocation.
_AllocationMixin._decode_page_commit` commits the ``1 + K`` extension's
pages — so this is the byte half of a reservation the scheduler already makes.

``gather_kv_tokens`` is the axis the profile CANNOT see. The tkv Turbo prefill paged
prefill takes a padded short-circuit whenever the step carries exactly one
prefill row and that row's accumulated KV is at or below
``PREFILL_PAGED_GATHER_MAX_TOKENS``; the short-circuit materializes the whole
accumulated context per (chunk, layer). The profile's prefill probe is a FRESH
sequence, so it measures that term at chunk width and never at the context
width a long chat reaches. It is the one term that scales with something other
than the step's own token count — and therefore the only one that can carry a
slate past what the floor reserved.

Charging the gather
-------------------
The short-circuit is mutually exclusive with co-scheduling: it needs ``B == 1``,
so a step carrying two prefill rows takes the zero-copy varlen route and stages
nothing context-scaled. A slate is therefore charged the LARGEST single prefill
row's gather, never a sum — an upper bound that only falls as more prefill rows
join the step.

Enforcement contract
--------------------
The budget is the bytes the serving floor actually left for the step, so the
reserve and the gate are one quantity rather than two that can drift. Both are
calibrated on the same profile, so every slate whose cost the profile SAW fits
the budget and the gate does not fire — the whole of ordinary decode, mixed and
chunk-prefill traffic. What can exceed it is the term the profile did not see:
one prefill row's context-scaled gather. Whether the gate fires at all on a
given boot is therefore an observable property of that boot's numbers, not an
assumption — :mod:`arbi_serve.engine.activation_admission` computes the widest
admissible slate against the reserve at arm time and says which way it came out.

A PREFILL row is narrowed rather than refused: :meth:`StepActivationModel.
max_prefill_tokens` inverts the model in its token argument, so the scheduler
caps the chunk at what the budget covers and the row still advances every step.
A row that cannot fit the budget even at its minimum width is admitted anyway
with a bounded warning — one row is the minimum unit of progress, and starving
it silently is worse than running it. So admission bounds CO-RESIDENT demand
exactly, narrows the one term it can narrow, and names a row that exceeds the
budget on its own.

Pure arithmetic — no CUDA, no engine state, no allocation.
"""

from __future__ import annotations

from dataclasses import dataclass

#: KV-token ceiling on tkv's Turbo prefill B==1 padded gather short-circuit. At or below
#: it the loader materializes the accumulated context; above it it takes the
#: zero-copy varlen path and stages only tile-scale scratch. This mirrored a
#: ceiling turbo-attn's paged loader used to export; turbo-attn has since
#: REMOVED it rather than renamed it, so the probe in
#: :func:`resolve_prefill_gather_max_kv_tokens` finds nothing and this value
#: stands. The probe is kept so a reintroduced ceiling is picked up rather
#: than silently disagreed with.
PREFILL_PAGED_GATHER_MAX_TOKENS = 32768


def resolve_prefill_gather_max_kv_tokens() -> int:
    """tkv's live gather ceiling, falling back to the mirrored constant.

    Reading tkv's own value keeps the budget correct across a tkv bump that
    moves the ceiling — including the direction that matters most, a tkv that
    caps the gather at one chunk, which collapses the context-scaled term and
    lets the floor follow the real peak down without a second hand-tuned
    number here.
    """
    try:
        from tkv.runtime.attend import turbo_prefill_paged_loader as _loader  # noqa: PLC0415
    except Exception:  # noqa: BLE001 — no tkv (bf16 / MLA build): mirror stands.
        return PREFILL_PAGED_GATHER_MAX_TOKENS
    _tkv_max = getattr(_loader, "PREFILL_PAGED_GATHER_MAX_TOKENS", None)
    if _tkv_max is None:
        # The loader is present and the ceiling is GONE. That is not a missing
        # value to fall back on — it is the statement that no context-scaled
        # ceiling exists any more, because the padded gather is bounded at the
        # current chunk (``S_kv <= total_q``) and everything past it takes the
        # zero-copy path. Charging the retired ceiling would price a term the
        # kernel no longer allocates, and admission would defer rows to reserve
        # for it. What the padded route still materializes is one chunk, and
        # the serving floor already prices exactly that as its
        # ``tkv-prefill-staging`` term (``Sg = min(max_context,
        # max_batched_tokens)``) — so charging it again here would double-book
        # the same bytes. Zero is the whole remaining gather demand, not an
        # absence of information.
        return 0
    try:
        v = int(_tkv_max)
    except (TypeError, ValueError):
        return PREFILL_PAGED_GATHER_MAX_TOKENS
    return v if v > 0 else PREFILL_PAGED_GATHER_MAX_TOKENS


@dataclass(frozen=True, slots=True)
class StepActivationModel:
    """Calibrated per-step activation cost and the budget admission enforces.

    Every field is bytes except ``gather_max_kv_tokens`` (KV tokens) — the
    ceiling past which tkv stops materializing the gather, so charging beyond
    it would price a state the kernel cannot enter.

    ``budget_bytes`` is ``None`` when no budget is armed — no reading was taken,
    the gate is inert, and every slate is admissible. An integer is a READING,
    and ``0`` is a reading like any other: the card saying a step may spend
    nothing. Those are opposite instructions to admission, so they cannot share
    a value. A single sentinel for both makes the inert branch the one an
    exhausted card always reaches, which turns the gate off at the moment it is
    the only thing left.
    """

    const_bytes: int
    per_prefill_token_bytes: int
    per_row_bytes: int
    per_gather_kv_token_bytes: int
    gather_max_kv_tokens: int
    budget_bytes: int | None
    #: Bytes each EXTRA query token on a decode row costs, beyond the one the
    #: row's ``per_row_bytes`` already carries. Nonzero only when the boot
    #: profile measured :data:`~arbi_serve.runtime.activation_profile.
    #: SHAPE_VERIFY_FORWARD`; zero leaves the model exactly what it was.
    per_query_token_bytes: int = 0

    def gather_charge_tokens(self, row_kv_tokens: int) -> int:
        """KV tokens the gather can materialize for a row of this length."""
        if self.per_gather_kv_token_bytes <= 0:
            return 0
        return min(max(0, int(row_kv_tokens)), int(self.gather_max_kv_tokens))

    def demand_bytes(
        self,
        *,
        prefill_tokens: int,
        rows: int,
        gather_kv_tokens: int,
        query_tokens: int = 0,
    ) -> int:
        """Modelled forward-activation bytes for a slate of this shape.

        ``query_tokens`` is the slate's EXTRA decode-row query tokens — the
        drafts an MTP row's verify step carries beside its committed tail, i.e.
        ``K`` per opted row, not ``K + 1``. The tail token is the one every
        decode row already pays through ``per_row_bytes``, so charging ``K + 1``
        here would price it twice.
        """
        return (
            self.const_bytes
            + self.per_prefill_token_bytes * max(0, int(prefill_tokens))
            + self.per_row_bytes * max(0, int(rows))
            + self.per_gather_kv_token_bytes * max(0, int(gather_kv_tokens))
            + self.per_query_token_bytes * max(0, int(query_tokens))
        )

    def admits(
        self,
        *,
        prefill_tokens: int,
        rows: int,
        gather_kv_tokens: int,
        query_tokens: int = 0,
    ) -> bool:
        """Whether a slate of this shape fits the budget the floor reserved."""
        if self.budget_bytes is None:
            return True
        return (
            self.demand_bytes(
                prefill_tokens=prefill_tokens,
                rows=rows,
                gather_kv_tokens=gather_kv_tokens,
                query_tokens=query_tokens,
            )
            <= self.budget_bytes
        )

    def max_prefill_tokens(
        self,
        *,
        rows: int,
        gather_kv_tokens: int,
        other_prefill_tokens: int = 0,
        query_tokens: int = 0,
    ) -> int | None:
        """Prefill tokens one more row may take and keep the slate in budget.

        ``None`` means "unbounded by this model" — no budget armed, or a token
        slope of zero, either of which makes a token cap meaningless. A budget
        of zero is NOT unbounded: it caps the row at zero tokens, and the
        scheduler's empty-slate floor then advances it one token at a time,
        which is the narrowest progress admission can make.

        This is the inverse of :meth:`demand_bytes` in its one continuous
        argument, and it is what lets a long prompt stay servable on a card
        whose free VRAM is below a full-width chunk. Refusing such a row would
        starve it and admitting it whole would OOM the forward; narrowing the
        chunk does neither — the row advances every step, just by fewer tokens.
        """
        if self.budget_bytes is None or self.per_prefill_token_bytes <= 0:
            return None
        room = (
            self.budget_bytes
            - self.const_bytes
            - self.per_row_bytes * max(0, int(rows))
            - self.per_gather_kv_token_bytes * max(0, int(gather_kv_tokens))
            - self.per_query_token_bytes * max(0, int(query_tokens))
        )
        if room <= 0:
            return 0
        return max(0, room // self.per_prefill_token_bytes - max(0, int(other_prefill_tokens)))

    def worst_admissible_bytes(
        self,
        *,
        max_batched_tokens: int,
        max_batch: int,
        max_context: int,
        max_query_tokens: int = 0,
    ) -> int:
        """Demand of the widest slate the admission limits allow.

        The number the budget must be at or above for the gate to be
        TTFT-neutral: every slate admission can build costs at most this.

        ``max_query_tokens`` is ``max_batch * mtp_k`` — every row opted into
        speculation at the deepest draft the boot resolved. It is a separate
        argument rather than a product taken here because the model does not
        know ``mtp_k``: the draft depth is the engine's, and a widest-slate
        number that guessed it would report a bound admission does not enforce.
        """
        return self.demand_bytes(
            prefill_tokens=max_batched_tokens,
            rows=max_batch,
            gather_kv_tokens=self.gather_charge_tokens(max_context),
            query_tokens=max_query_tokens,
        )


@dataclass(frozen=True, slots=True)
class ShapeObservation:
    """One profiled shape, as the calibration reads it.

    ``gather_kv_tokens`` is the accumulated KV the probe's own attention
    gathered — nonzero only for the single-row prefill probe, since the padded
    gather needs ``B == 1`` and the multi-row decode / mixed probes take the
    zero-copy route.

    ``query_tokens`` is the EXTRA query tokens the probe's rows carried beyond
    one each — nonzero only for the verify-width probe, whose rows each run
    ``K + 1`` tokens through the model. It is what separates a shape that
    calibrates the query axis from one that calibrates the prefill-token axis:
    the two are different forwards at the same token count (a decode-class
    batch with a wide ``max_query_len`` against a prefill batch), and fitting
    one slope over both would price neither.
    """

    tokens: int
    rows: int
    gather_kv_tokens: int
    peak_bytes: int
    query_tokens: int = 0


def calibrate(
    *,
    observations: list[ShapeObservation],
    gather_bytes_per_kv_token: int,
    gather_max_kv_tokens: int,
    budget_bytes: int | None,
) -> StepActivationModel | None:
    """Fit the token and row slopes to the profiled shapes.

    The boot profile measures the two axes admission controls at their
    extremes: a pure-decode shape (many rows, one token each) and a pure-prefill
    shape (one row, ``max_batched_tokens`` tokens). The token slope is the rise
    between them once each shape's own gather is netted out; the row slope is
    what the decode shape costs beyond its handful of tokens.

    A CONSTANT is then lifted until the model reproduces every profiled shape at
    or above its measurement. That is what keeps a linear fit honest against a
    peak that is not linear: the mixed shape sits above the line through the two
    extremes (it runs a prefill chunk and a decode batch in one forward), and a
    model that under-predicts a shape the engine demonstrably runs would hand
    admission a budget the forward exceeds.

    Every coefficient is clamped at zero, so a profile with a missing or
    zero-recorded shape (an OOM'd probe records 0 bytes by design) yields a
    smaller model rather than a negative slope that would make wider slates
    look cheaper. Returns ``None`` when fewer than two distinct token widths
    were profiled — there is then no slope to fit, and an unarmed gate is the
    correct outcome.

    THE QUERY SLOPE IS FIT LAST, AND ONLY AGAINST ITS OWN RESIDUAL. An
    observation with ``query_tokens > 0`` is a decode-class batch whose rows
    each carry ``K + 1`` tokens; it is held out of the three fits above and then
    charged only what the finished model does not already predict for the same
    rows at one token each. Two reasons it cannot be one of the token-slope
    points. Its tokens are not prefill tokens — admission calls
    :meth:`~StepActivationModel.demand_bytes` for a pure-MTP decode slate with
    ``prefill_tokens=0``, so a slope fit through it would price bytes no term
    ever charges. And folding it into the constant instead would charge its
    whole excess to every slate, including the ``mtp_k == 0`` traffic that never
    runs the shape, which narrows prefill chunks for a step that cannot occur.
    Clamped at zero like every other coefficient: a verify probe that came in at
    or below what the row slope already predicts leaves the model exactly what
    it was, which is the honest reading of "this axis costs nothing extra here".
    """
    g = max(0, int(gather_bytes_per_kv_token))
    gather_max = max(0, int(gather_max_kv_tokens))
    obs = [o for o in observations if int(o.peak_bytes) > 0 and int(o.tokens) > 0]
    base_obs = [o for o in obs if int(o.query_tokens) <= 0]
    query_obs = [o for o in obs if int(o.query_tokens) > 0]
    if len(base_obs) < 2:
        return None
    # Net of the gather each probe paid, so the slopes price the forward and
    # the gather term is not counted twice.
    net = [
        (int(o.tokens), int(o.rows), int(o.peak_bytes) - g * int(o.gather_kv_tokens))
        for o in base_obs
    ]
    widest = max(net, key=lambda e: e[0])
    narrowest = min(net, key=lambda e: e[0])
    if widest[0] == narrowest[0]:
        return None
    per_token = max(0, (widest[2] - narrowest[2]) // (widest[0] - narrowest[0]))
    rows_n = max(1, narrowest[1])
    per_row = max(0, (narrowest[2] - per_token * narrowest[0]) // rows_n)
    const = 0
    for tokens, rows, peak in net:
        const = max(const, peak - per_token * tokens - per_row * rows)
    # The residual the finished base model leaves on each verify probe, spread
    # over the extra query tokens that probe actually ran. Rounded UP so the
    # slope reproduces the measurement rather than landing a byte under it.
    per_query = 0
    for o in query_obs:
        qt = int(o.query_tokens)
        residual = (
            int(o.peak_bytes) - g * int(o.gather_kv_tokens) - const - per_row * max(0, int(o.rows))
        )
        if residual > 0:
            per_query = max(per_query, -(-residual // qt))
    return StepActivationModel(
        const_bytes=int(const),
        per_prefill_token_bytes=per_token,
        per_row_bytes=per_row,
        per_gather_kv_token_bytes=g,
        gather_max_kv_tokens=gather_max,
        budget_bytes=None if budget_bytes is None else max(0, int(budget_bytes)),
        per_query_token_bytes=int(per_query),
    )
# ---- admission_burst.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""An explicit, bounded admission barrier for equal-arrival experiments.

Requests use their ordinary X-Request-ID. The operator names their complete
order before sending them. Intake, cancellation and resource ownership stay
on the ordinary path; only composing the first scheduler slate waits.
"""

from __future__ import annotations

import asyncio
import copy
import math
import time
import uuid
from collections import Counter


class AdmissionBurstConflict(RuntimeError):
    """A barrier cannot start against live work or another armed barrier."""


class AdmissionBurstNotFound(LookupError):
    """The requested receipt is neither active nor the last completed one."""


class _AdmissionBurstMixin:
    _admission_burst = None
    _admission_burst_receipt = None


class AdmissionBurst:
    def __init__(self, scheduler, request_ids, timeout_s, wake):
        self.scheduler = scheduler
        self.request_ids = list(request_ids)
        self.expected = set(request_ids)
        self.id = uuid.uuid4().hex
        self.started = time.monotonic()
        self.state = "armed"
        self.reason = None
        self.wake = wake
        self._result = None
        self._timer = asyncio.get_running_loop().call_later(timeout_s, self.finish, "expired")

    def snapshot(self):
        if self._result is not None:
            return copy.deepcopy(self._result)
        queued = [req.client_request_id for req in self.scheduler.waiting]
        return {
            "id": self.id,
            "state": self.state,
            "valid": self.state == "complete",
            "request_ids": list(self.request_ids),
            "received_ids": [rid for rid in self.request_ids if rid in queued],
            "released_ids": queued if self.state != "armed" else [],
            "elapsed_s": time.monotonic() - self.started,
            "reason": self.reason,
        }

    def finish(self, state, reason=None):
        if self.state != "armed":
            return
        self.state, self.reason = state, reason
        self._timer.cancel()
        self._result = self.snapshot()
        self.scheduler._admission_burst = None
        self.scheduler._admission_burst_receipt = self._result
        self.wake()

    def allow(self, scheduler):
        """Release one complete ordered burst; reject contaminated evidence."""
        queued = list(scheduler.waiting)
        ids = [req.client_request_id for req in queued]
        counts = Counter(ids)
        if any(rid not in self.expected for rid in ids):
            self.finish("invalid", "unrelated request arrived during the barrier")
            return True
        if any(n > 1 for n in counts.values()):
            self.finish("invalid", "duplicate X-Request-ID in the waiting queue")
            return True
        if not self.expected.issubset(counts):
            return False
        by_id = dict(zip(ids, queued, strict=True))
        scheduler.waiting.clear()
        scheduler.waiting.extend(by_id[rid] for rid in self.request_ids)
        # The partial-prefill-first index is kept in arrival order; give it
        # the declared order too, or it would release partials by arrival.
        partial = getattr(scheduler, "_partial_waiting", None)
        if partial:
            scheduler._partial_waiting = {
                r.request_id: r for r in scheduler.waiting if r.request_id in partial
            }
        self.finish("complete")
        return True


def _scheduler(eng):
    from arbi_serve.engine.proc.admin_registry import AdminMethodUnsupportedError

    scheduler = getattr(eng, "scheduler", None)
    if not isinstance(scheduler, _AdmissionBurstMixin):
        raise AdminMethodUnsupportedError("admission barriers require one local scheduler")
    return scheduler


def arm(eng, request_ids: list, timeout_s: float = 10.0):
    """Arm an idle scheduler for exactly these caller-visible request ids."""
    scheduler = _scheduler(eng)
    if scheduler._admission_burst is not None:
        raise AdmissionBurstConflict("an admission barrier is already armed")
    if eng.requests or scheduler.waiting or scheduler.running:
        raise AdmissionBurstConflict("admission barriers require an idle engine")
    if (
        not request_ids
        or len(request_ids) > scheduler.batch_cfg.max_batch
        or any(not isinstance(rid, str) or not rid or len(rid) > 128 for rid in request_ids)
        or len(set(request_ids)) != len(request_ids)
    ):
        raise ValueError("request_ids must be unique nonempty strings within max_batch")
    if not math.isfinite(timeout_s) or not 0 < timeout_s <= 30:
        raise ValueError("timeout_s must be finite and in (0, 30]")
    burst = AdmissionBurst(scheduler, request_ids, timeout_s, eng._wakeup.set)
    scheduler._admission_burst = burst
    return burst.snapshot()


def status(eng, id: str):
    """Return the active barrier or the latest completed receipt by id."""
    scheduler = _scheduler(eng)
    active = scheduler._admission_burst
    if active is not None and active.id == id:
        return active.snapshot()
    last = scheduler._admission_burst_receipt
    if last is not None and last["id"] == id:
        return copy.deepcopy(last)
    raise AdmissionBurstNotFound(id)


def cancel(eng, id: str):
    """Release partial arrivals immediately, keeping an invalid receipt."""
    scheduler = _scheduler(eng)
    active = scheduler._admission_burst
    if active is not None and active.id == id:
        active.finish("cancelled")
    return status(eng, id)
# ---- attn_dp_group.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Per-attention-DP-rank admission: one scheduler per request shard.

At ``attn_dp_size > 1`` an attention-DP set owns whole REQUESTS — their
tokens and their whole KV — so admission is a PER-SET decision. One
scheduler over one page table cannot make it: the sets' pools fill
independently, and a slate every set forwards would put the same requests
(and the same KV) on every set, which is the replication the axis exists
to remove.

So rank 0 runs ``attn_dp_size`` schedulers, one per set, each over its own
page table, and this group is the single object the engine holds in
``eng.scheduler``. Each member is an ORDINARY
:class:`~arbi_serve.scheduler.scheduler.Scheduler` with no attention-DP
awareness at all: per-set page accounting, preemption and backpressure
fall out of the fact that a member can only see its own table.

Rank 0 backs member 0 with the REAL pool (its own set's KV) and every
other member with an :class:`~arbi_serve.cache.attn_dp_shadow_pool.AttnDpShadowPagedPool`
— see that class for why a page-count mirror is sufficient and what would
break if the ids had to match.

OWNERSHIP IS PERMANENT. :meth:`add` stamps ``Request.attn_dp_rank`` once
and every later call routes on it; a request's pages live in exactly one
set's pool, so re-homing it would strand them. Placement
(:func:`pick_set`) is a rank-0-local decision and never crosses the wire —
the per-member slates it produces do.

THE STEP BUDGET IS SHARED, NOT REPLICATED. Every rank's FFN runs over the
GATHERED rows of all ``attn_dp_size`` sets, so the whole step's token
count — not one set's — is what the activation arena and
``max_batched_tokens`` bound. Rows are split statically: each member gets
``1 / attn_dp_size`` of ``max_batch``, which is what the per-set decode
graphs capture. Tokens are handed out per tick (:meth:`schedule_per_dp`),
max-min fair over what each set can use: a set that needs less than an
even share keeps what it needs and the rest goes to the sets that need
more. So a lone prompt prefills at the whole step's width instead of at
its set's share, while two sets that both prefill still split the step
evenly — their attention runs side by side, and the tick waits for the
slower one.
"""

from __future__ import annotations

import dataclasses
import functools
from typing import TYPE_CHECKING

from arbi_serve.engine.request import RequestState
from arbi_serve.scheduler.scheduler_selection import UNCAPPED

if TYPE_CHECKING:
    from collections.abc import Callable, Iterator

    from arbi_serve.config import BatchConfig
    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.scheduler import Scheduler


def split_batch_config(batch_cfg: BatchConfig, attn_dp_size: int) -> BatchConfig:
    """One attention-DP member's batch config: its share of the rows.

    ``max_batch`` bounds the GATHERED step (see the module docstring), so
    each member may hold at most its share of the rows, floored at 1 — a
    member that could admit no row would be a set that never serves.
    ``max_batched_tokens`` stays whole: the group caps each member per tick
    (:meth:`AttnDpSchedulerGroup.schedule_per_dp`) so the sets' sum never
    exceeds it.
    """
    n = int(attn_dp_size)
    if n <= 1:
        return batch_cfg
    return dataclasses.replace(batch_cfg, max_batch=max(1, int(batch_cfg.max_batch) // n))


def per_set_max_batch(max_batch: int) -> int:
    """The rows ONE attention-DP set's slate can hold: its member's ``max_batch``.

    What :func:`split_batch_config` gives each member, at the installed
    topology (``max_batch`` itself at ``attn_dp_size == 1``). The decode
    capture ladder stops here under attention DP: a graph records one set's
    rows, and its FFN runs over ``attn_dp_size`` times as many.
    """
    from arbi_serve.distributed.parallel_state import get_attention_dp_size

    n = int(get_attention_dp_size())
    return int(max_batch) if n <= 1 else max(1, int(max_batch) // n)


def step_demand(member: Scheduler) -> int:
    """Step tokens ``member`` could put on this tick's slate: an upper bound.

    Each running decode row's allowance (what :meth:`Scheduler.schedule`
    debits for it), plus each prefilling or waiting request's next chunk.
    An overestimate only hands this set a larger share than it fills.
    """
    chunk = int(member.batch_cfg.chunk_prefill)
    total = 0
    for req in member.running:
        if req.state is RequestState.DECODING:
            total += member._decode_row_step_tokens(req)
        else:
            total += min(chunk, req.num_remaining_prompt)
    for queue in (member.waiting, member._deferred_admits):
        for req in queue:
            total += min(chunk, max(1, req.num_remaining_prompt))
    return total


def fair_shares(total: int, demands: list[int]) -> list[int]:
    """Max-min fair split of ``total`` over ``demands`` (water-filling).

    A set asking for no more than an even share of what is left gets what
    it asks; the rest is split among the others the same way. Every set's
    share is at most its demand except the largest's, which takes whatever
    remains, so the shares sum to ``total``.
    """
    n = len(demands)
    shares = [0] * n
    left = int(total)
    order = sorted(range(n), key=lambda d: (demands[d], d))
    for k, d in enumerate(order):
        even = left // (n - k)
        shares[d] = left if k == n - 1 else min(int(demands[d]), even)
        left -= shares[d]
    return shares


def request_tokens(req: Request) -> int:
    """KV tokens ``req`` holds once its prompt is in: prompt, injected context, output.

    The whole prompt counts from admission, not just the consumed part: a
    waiting prompt is attention work its set has already been handed.
    """
    return len(req.prompt_token_ids) + int(req.context_consumed) + len(req.output_token_ids)


def set_load(member: Scheduler) -> tuple[int, int]:
    """``(tokens, requests)`` one set holds: waiting, running and deferred admits."""
    tokens = 0
    count = 0
    for queue in (member.waiting, member.running, member._deferred_admits):
        for held in queue:
            tokens += request_tokens(held)
            count += 1
    return tokens, count


def cached_prefix_tokens(member: Scheduler, req: Request) -> int:
    """Prompt tokens ``member``'s prefix tree already holds for ``req``.

    A read-only walk (no LRU touch, no refs), in ``req``'s cache namespace;
    ``0`` on a flat table or for a request that opted out of the cache.
    """
    peek = getattr(member.page_table, "peek_hot", None)
    if peek is None or not getattr(req.sampling, "cache_enabled", True):
        return 0
    _node, pages = peek(req.cache_token_ids(), member._tenant_id_for(req))
    return int(pages) * int(member.page_table.block_size)


def pick_set(members: list[Scheduler], credit: list[int] | None = None) -> int:
    """The attention-DP set a new request joins.

    Every set's tick waits for the slowest set's attention, and a set's
    attention time grows with the KV it reads (each decode row's context)
    and the prompt tokens it still has to prefill — not with how many
    requests it holds. So a set's load is the KV tokens it holds or has been
    handed (:func:`set_load`), and the request goes to the set where that is
    lowest (the request's own tokens add the same to every set). A request
    count would put a long prompt beside another long prompt whenever the
    short requests happened to fall on the other set.

    Rows still bound a set: a set whose resident requests already fill its
    share of ``max_batch`` cannot run one more this tick, however few tokens
    it holds, so such a set loses to any set with a free row.

    ``credit[d]`` is the tokens set ``d`` would not have to compute for the
    request (a prefix it already caches); it is subtracted from that set's
    load. Ties go to fewer requests, then to the lowest index, so placement
    is a deterministic function of arrival order.
    """
    best = 0
    best_key: tuple[int, int, int] | None = None
    for idx, member in enumerate(members):
        tokens, count = set_load(member)
        full = int(count >= int(member.batch_cfg.max_batch))
        key = (full, tokens - (credit[idx] if credit else 0), count)
        if best_key is None or key < best_key:
            best, best_key = idx, key
    return best


class _ChainView:
    """Read-only concatenation of the members' ``waiting`` / ``running``.

    Admission and the health surfaces read these as a sequence
    (``len`` / iteration / truthiness) and never mutate them, so a view
    beats rebuilding a list on every arriving request.
    """

    __slots__ = ("_parts",)

    def __init__(self, parts) -> None:
        self._parts = parts

    def __len__(self) -> int:
        return sum(len(p) for p in self._parts)

    def __iter__(self) -> Iterator:
        for part in self._parts:
            yield from part

    def __bool__(self) -> bool:
        return any(self._parts)


class _ShardedPageTableView:
    """The members' page tables as one read-only accounting surface.

    :func:`arbi_serve.engine.admission.check_admission` measures KV
    occupancy against ONE rank's ``pool.num_pages``, so the availability
    it must see is the FULLEST set's — the set a new request could land
    on. ``min`` is therefore the aggregate, not ``sum``: summing would
    report ``attn_dp_size`` pools' worth of headroom against one pool's
    denominator and never watermark at all.
    """

    def __init__(self, group: AttnDpSchedulerGroup) -> None:
        self._group = group

    @property
    def block_size(self) -> int:
        """Page size in tokens; identical on every member."""
        return self._group.members[0].page_table.block_size

    def available_pages(self) -> int:
        """Free pages in the fullest attention-DP set."""
        return min(m.page_table.available_pages() for m in self._group.members)

    def free_pages(self) -> int:
        """Free pool pages in the fullest attention-DP set."""
        return min(m.page_table.free_pages() for m in self._group.members)

    def length(self, request_id: int) -> int:
        """Resident token count of one request, from its owner's table."""
        return self._group.table_for(request_id).length(request_id)


class AttnDpSchedulerGroup:
    """``attn_dp_size`` schedulers presented to the engine as one.

    Exposes the exact surface the engine, the admission gate and the SPMD
    driver call on a :class:`~arbi_serve.scheduler.scheduler.Scheduler`.
    Anything not listed here is deliberately absent rather than forwarded
    to member 0: a call that silently hit one set's queues while the
    others held requests would be wrong in a way no test would show.
    """

    def __init__(self, members: list[Scheduler]) -> None:
        if len(members) < 2:
            raise ValueError(
                f"AttnDpSchedulerGroup: needs one member per attention-DP "
                f"rank (got {len(members)}); attn_dp_size == 1 must use the "
                f"plain Scheduler so the default topology keeps its exact "
                f"pre-existing path."
            )
        self.members = list(members)
        self.page_table = _ShardedPageTableView(self)
        #: request id -> owning attention-DP rank. Authoritative for every
        #: route: a finished request is dropped from it only after its
        #: owner has released it.
        self._owner: dict[int, int] = {}

    # ── geometry ─────────────────────────────────────────────────────

    @property
    def attn_dp_size(self) -> int:
        """Number of attention-DP sets this group schedules for."""
        return len(self.members)

    def member_for(self, req: Request) -> Scheduler:
        """The scheduler that owns ``req``."""
        return self.members[int(req.attn_dp_rank)]

    def table_for(self, request_id: int):
        """The page table holding ``request_id``'s pages."""
        return self.members[self._owner.get(int(request_id), 0)].page_table

    def _pick_owner(self, req: Request) -> int:
        """The set ``req`` joins; see :func:`pick_set`."""
        return pick_set(self.members, [cached_prefix_tokens(m, req) for m in self.members])

    # ── engine surface ───────────────────────────────────────────────

    @property
    def waiting(self) -> _ChainView:
        """Every member's waiting queue, concatenated."""
        return _ChainView([m.waiting for m in self.members])

    @property
    def running(self) -> _ChainView:
        """Every member's running set, concatenated."""
        return _ChainView([m.running for m in self.members])

    @property
    def batch_cfg(self):
        """One member's split step budget (identical across members)."""
        return self.members[0].batch_cfg

    @property
    def _savepoint_chunk_size(self) -> int:
        """Savepoint chunk size; identical across members."""
        return self.members[0]._savepoint_chunk_size

    @property
    def _n_waiting_interactive(self) -> int:
        """O(1) admission counter, summed over the members."""
        return sum(m._n_waiting_interactive for m in self.members)

    @property
    def _n_running_interactive(self) -> int:
        """O(1) admission counter, summed over the members."""
        return sum(m._n_running_interactive for m in self.members)

    @property
    def _n_running_batch(self) -> int:
        """O(1) admission counter, summed over the members."""
        return sum(m._n_running_batch for m in self.members)

    @property
    def _n_deferred_interactive(self) -> int:
        """O(1) admission counter, summed over the members."""
        return sum(m._n_deferred_interactive for m in self.members)

    @property
    def _deferred_admits(self) -> _ChainView:
        """Every member's deferred-admit holding pen, concatenated."""
        return _ChainView([m._deferred_admits for m in self.members])

    @property
    def _offload_recurrent(self) -> bool:
        """Whether hybrid recurrent-state offload is on (same on every member)."""
        return self.members[0]._offload_recurrent

    @_offload_recurrent.setter
    def _offload_recurrent(self, value: bool) -> None:
        for member in self.members:
            member._offload_recurrent = bool(value)

    def _has_recurrent_state(self) -> bool:
        """Whether the model carries recurrent state (same on every member)."""
        return self.members[0]._has_recurrent_state()

    def add(self, req: Request) -> None:
        """Assign ``req`` to an attention-DP set and admit it there."""
        owner = self._pick_owner(req)
        req.attn_dp_rank = owner
        self._owner[int(req.request_id)] = owner
        self.members[owner].add(req)

    def remove(self, req: Request) -> None:
        """Cancel / time out ``req`` on its owning member."""
        self.member_for(req).remove(req)
        self._owner.pop(int(req.request_id), None)

    def release_device_state(self, req: Request) -> None:
        """Release ``req``'s pages and recurrent row on its owning member."""
        self.member_for(req).release_device_state(req)

    def finished(self, req: Request) -> None:
        """Retire ``req`` on its owning member."""
        self.member_for(req).finished(req)
        self._owner.pop(int(req.request_id), None)

    def schedule_per_dp(self, *, _now: float | None = None) -> list[list[tuple[Request, int]]]:
        """One slate per attention-DP set, in set order.

        The SPMD driver's entry point: each set forwards ITS list and
        nothing else, so this is the per-rank ``StepPlan`` source.

        The sets share one ``max_batched_tokens`` (module docstring): each
        is capped at its max-min fair share (:func:`fair_shares`) of the
        step, sized by the tokens it could use (:func:`step_demand`). The
        caps sum to the budget, so the sets' total never exceeds it, and a
        set's running decode rows always fit inside its own share unless the
        rows alone overrun the step. Members are scheduled in index order on
        rank 0, so the split is a deterministic function of arrival order.
        """
        total = int(self.members[0].batch_cfg.max_batched_tokens)
        caps = fair_shares(total, [step_demand(m) for m in self.members])
        slates: list[list[tuple[Request, int]]] = []
        for member, cap in zip(self.members, caps, strict=True):
            member.step_token_cap = cap
            try:
                slates.append(member.schedule(_now=_now))
            finally:
                member.step_token_cap = UNCAPPED
        return slates

    def schedule(self, *, _now: float | None = None) -> list[tuple[Request, int]]:
        """Every set's slate concatenated.

        Present so a non-SPMD caller sees one scheduler; the SPMD loop
        calls :meth:`schedule_per_dp` because it needs the split.
        """
        out: list[tuple[Request, int]] = []
        for slate in self.schedule_per_dp(_now=_now):
            out.extend(slate)
        return out

    def commit(self, slate: list[tuple[Request, int]], sampled_tokens: list[int | None]) -> None:
        """Advance state + append tokens, each row on its owning member."""
        self.commit_state(slate)
        self.commit_output(slate, sampled_tokens)

    def commit_state(self, slate: list[tuple[Request, int]]) -> list[tuple[int, object]]:
        """Advance the prefill/decode state machine per owning member.

        Returns each member's deferred consolidation work, for
        :meth:`_run_pp_consolidate`.
        """
        return [
            (owner, self.members[owner].commit_state(rows)) for owner, rows in self._split(slate)
        ]

    def _run_pp_consolidate(self, due: list[tuple[int, object]] | None) -> None:
        """Run each member's consolidation from :meth:`commit_state`."""
        for owner, member_due in due or ():
            self.members[owner]._run_pp_consolidate(member_due)

    def commit_output(
        self, slate: list[tuple[Request, int]], sampled_tokens: list[int | None]
    ) -> None:
        """Append each row's sampled token via its owning member."""
        by_owner: dict[int, tuple[list, list]] = {}
        for (req, n_tok), token in zip(slate, sampled_tokens, strict=True):
            rows, toks = by_owner.setdefault(int(req.attn_dp_rank), ([], []))
            rows.append((req, n_tok))
            toks.append(token)
        for owner, (rows, toks) in by_owner.items():
            self.members[owner].commit_output(rows, toks)

    def drain_dropped_suspended(self) -> list[Request]:
        """Every member's dropped suspended jobs."""
        out: list[Request] = []
        for member in self.members:
            out.extend(member.drain_dropped_suspended())
        return out

    def duplex_tick_due(self, now: float) -> bool:
        """Whether any member has a duplex tick due."""
        return any(m.duplex_tick_due(now) for m in self.members)

    def set_forward_in_flight_fn(self, fn: Callable[[], bool]) -> None:
        """Wire the engine's forward-in-flight predicate into every member."""
        for member in self.members:
            member.set_forward_in_flight_fn(fn)

    def set_spmd_deferred_release(self, fn: Callable[..., None] | None) -> None:
        """Install the SPMD deferred-release hook on every member.

        Each member's hook names that member as ``owner``: the drain frees
        a request from the page table of the set that holds its pages,
        which for every set but rank 0's own is not ``eng.page_table``.
        """
        for member in self.members:
            member.set_spmd_deferred_release(
                None if fn is None else functools.partial(fn, owner=member)
            )

    def enable_spmd_preempt_log(self, enabled: bool = True) -> None:
        """Arm the SPMD preempt log on every member.

        Each member keeps its OWN log, so the rank-0 delta builder drains
        exactly that set's preemptions when it builds that set's delta.
        """
        for member in self.members:
            member.enable_spmd_preempt_log(enabled)

    def shutdown(self) -> None:
        """Gut every member's heavy references (idempotent)."""
        for member in self.members:
            member.shutdown()
        self._owner.clear()

    # ── internals ────────────────────────────────────────────────────

    def _split(self, slate: list[tuple[Request, int]]) -> list[tuple[int, list]]:
        """Group a mixed slate by owning attention-DP rank, order preserved."""
        by_owner: dict[int, list] = {}
        for row in slate:
            by_owner.setdefault(int(row[0].attn_dp_rank), []).append(row)
        return list(by_owner.items())
# ---- attn_dp_savepoint_admission.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Admission against one attention-DP set's savepoints, on rank 0.

Each member scheduler of :class:`~arbi_serve.scheduler.attn_dp_group.
AttnDpSchedulerGroup` gets one :class:`SetSavepointSnapshotter`. It answers
the snapshotter's admission questions (``resolve_resume`` /
``resolve_match`` / ``queue_resume``) off that set's
:class:`~arbi_serve.cache.attn_dp_savepoints.SetSavepointIndex`, so the
reconciliation the hybrid path already trusts — cap the radix match at the
savepoint's coverage, drop a savepoint the match falls short of, re-prefill
a match no savepoint covers — runs unchanged; only where the bytes live
differs. It also plans the tick's stages (:meth:`plan_stages`), which ride
the set's delta.

WHICH BOUNDARIES ARE WRITTEN. Two, both page-aligned and both inside the
step that passes them:

* the prompt's end: the deepest boundary strictly before the prompt's
  last token on both the page and the recurrent kernel's fold grid, on the step that completes the prompt — what the
  conversation's next turn resumes from (the same rule as
  :func:`~arbi_serve.cache.recurrent_savepoint.savepoint_fold_split`);
* a shared context's end: where this request's radix walk stopped short of
  any savepoint, i.e. a prefix another request left in the tree. The next
  sibling of that prefix resumes there.

A preempted request's re-bind never resumes from a set savepoint (it
re-prefills): the re-bind's match is decided inside a preemption whose
PreemptRow would have to carry the slot as well, for a path that is rare
under attention DP's per-set budgets.
"""

from __future__ import annotations

import math
from dataclasses import dataclass
from typing import TYPE_CHECKING

from arbi_serve.scheduler.prefill_cache_limit import resume_match_limit
from arbi_serve.scheduler.savepoint_admission import SavepointSnapshotter

if TYPE_CHECKING:
    from arbi_serve.cache.attn_dp_savepoints import SetSavepointIndex
    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.scheduler import Scheduler


@dataclass(frozen=True)
class SetSavepointEntry:
    """A held set savepoint: what ``resolve_match`` caps and checks against."""

    num_tokens_covered: int
    slot: int


class SetSavepointSnapshotter(SavepointSnapshotter):
    """The snapshotter of one attention-DP member scheduler (see module docstring)."""

    def __init__(self, sched: Scheduler, index: SetSavepointIndex) -> None:
        super().__init__(sched)
        self.index = index
        #: rid -> slot of an admission's resume not yet carried by a delta.
        self._restores: dict[int, int] = {}
        #: rid -> the shared context's end this request owes a write at.
        self._forks: dict[int, int] = {}

    # ── admission ────────────────────────────────────────────────────

    def resolve_resume(self, req: Request, tenant_id: str, cache_enabled: bool):
        rid = int(req.request_id)
        self._forks.pop(rid, None)
        tokens = req.cache_token_ids()
        if not cache_enabled or len(tokens) < 2:
            return None, None
        limit = resume_match_limit(req, len(tokens) - 1)
        hit = self.index.best(tenant_id, tokens, limit)
        usable = hit[0] if hit is not None else 0
        peek = getattr(self._sched.page_table, "peek_hot", None)
        if peek is not None:
            _node, pages = peek(tokens, tenant_id)
            page = self.index.page
            reach = min(int(pages) * page, (limit // page) * page)
            if reach > usable:
                self._forks[rid] = reach
        if hit is None:
            return None, None
        return hit, SetSavepointEntry(num_tokens_covered=hit[0], slot=hit[1])

    def resolve_match(
        self,
        req: Request,
        tenant_id: str,
        cache_enabled: bool,
        savepoint_resume_key,
        savepoint_entry,
        *,
        retain_enabled: bool | None = None,
        readmit: bool = False,
        page_budget_cap: int | None = None,
    ):
        if readmit:
            savepoint_resume_key, savepoint_entry = None, None
        return super().resolve_match(
            req,
            tenant_id,
            cache_enabled,
            savepoint_resume_key,
            savepoint_entry,
            retain_enabled=retain_enabled,
            readmit=readmit,
            page_budget_cap=page_budget_cap,
        )

    def queue_resume(self, req: Request, tenant_id: str, savepoint_entry, match_len: int) -> None:
        del tenant_id
        if int(savepoint_entry.num_tokens_covered) != int(req.prompt_consumed):
            raise RuntimeError(
                f"attention-DP set savepoint: request {req.request_id} credited "
                f"prompt_consumed={req.prompt_consumed} (match {match_len}) but slot "
                f"{savepoint_entry.slot} covers {savepoint_entry.num_tokens_covered} tokens"
            )
        rid = int(req.request_id)
        old = self._restores.pop(rid, None)
        if old is not None:
            self.index.unpin(old)
        self.index.pin(savepoint_entry.slot)
        self._restores[rid] = int(savepoint_entry.slot)

    def take_restore(self, rid: int) -> int:
        """The slot ``rid``'s admission resumes from, once, as its AdmitRow is built."""
        slot = self._restores.pop(int(rid), None)
        if slot is None:
            return -1
        self.index.unpin(slot)
        return slot

    def forget_request(self, req_id: int) -> None:
        self._forks.pop(int(req_id), None)
        slot = self._restores.pop(int(req_id), None)
        if slot is not None:
            self.index.unpin(slot)
        super().forget_request(req_id)

    # ── the tick's stages ────────────────────────────────────────────

    def plan_stages(self, slate: list[tuple[Request, int]]) -> list[tuple[int, int, int]]:
        """``(request_id, boundary, slot)`` the set's forward stages this tick.

        Called once per tick, as the set's delta is built, over the final
        slate (``prompt_consumed`` is still the step's start). A stage left
        pending by a tick that never committed is dropped first.
        """
        self.index.drop_pending()
        page = self.index.page
        # A boundary the forward can stage must be a page multiple (the index
        # keys on pages) AND on the recurrent kernel's fold grid (the emit
        # addresses a chunk; ``publish_step_plans`` refuses an offset off it,
        # and the slot is then never filled on any rank). Chunk cuts are kept
        # on that grid by the scheduler, so a boundary on both grids is
        # reachable from every step start.
        step = math.lcm(page, max(1, int(getattr(self._sched, "_savepoint_fold_grid", 0) or 1)))
        table = self._sched.page_table
        tenant_fn = getattr(table, "tenant_id_for", None)
        retain_fn = getattr(table, "retain_enabled_for", None)
        out: list[tuple[int, int, int]] = []
        for req, n in slate:
            if not req.is_prefill or n <= 0:
                continue
            rid = int(req.request_id)
            pc_before = int(req.prompt_consumed)
            pc_after = pc_before + int(n)
            prompt_len = len(req.prompt_token_ids)
            wants = []
            fork = self._forks.get(rid)
            if fork is not None:
                fork = (fork // step) * step
            if fork is not None and fork < pc_before:
                self._forks.pop(rid, None)
                fork = None
            if fork is not None and fork <= pc_after:
                self._forks.pop(rid, None)
                wants.append(fork)
            if pc_after >= prompt_len:
                end = ((prompt_len - 1) // step) * step
                if end >= pc_before and end not in wants:
                    wants.append(end)
            wants = [b for b in wants if b > 0]
            if not wants:
                continue
            if retain_fn is not None and not retain_fn(rid):
                continue
            tokens = req.cache_token_ids()
            tenant = str(tenant_fn(rid)) if tenant_fn is not None else ""
            for boundary in wants:
                key = self.index.key(tenant, tokens, boundary)
                if self.index.holds(key):
                    continue
                slot = self.index.claim(key)
                if slot is not None:
                    out.append((rid, int(boundary), int(slot)))
        return out


def install_member(sched: Scheduler, index: SetSavepointIndex | None) -> None:
    """Answer ``sched``'s prefix questions for a pool whose rows hold state.

    ``index`` is the set's savepoint index, or ``None`` when this boot keeps
    no set savepoints, in which case no member may credit a match at all. A
    peer's mirror pool holds no state of its own, so its own answer (from
    the pool) would be "nothing to restore" and every hit would be credited.
    """
    sched._has_recurrent_state_cached = True
    sched._prefix_cache_serves = index is not None
    if index is not None:
        from arbi_serve.cache.recurrent_savepoint import recurrent_fold_grid

        # A stage/set store replaces the legacy store after construction.
        # Its prefill cuts still need the same kernel reduction grid.
        sched._savepoint_fold_grid = recurrent_fold_grid(sched.pool, index.page)
        sched._prefix_retention_serves = True
        sched._savepoint_snapshotter = SetSavepointSnapshotter(sched, index)
# ---- coadmit_pacing.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""``ARBI_PP_COADMIT_PREFILL_EVERY_N``: how often a solo prefill gets a tick.

A tick emits at most one decode step per row and costs whatever prefill chunk
it also carries, so a decode co-admitted with a prefill runs at one step per
CHUNK whatever either costs. ``ARBI_PP_PREFILL_SOLO_BESIDE_DECODE`` moves the
chunk to the rank the decode is not on, which is what lets the two run at the
same time; this is the other half, and without it the move buys nothing —
the tick is still one chunk wide, because the dispatch that hands the chunk
over is a rendezvous with the rank still working through the last one.
Offering the chunk on one tick in N gives the decode N-1 ticks that cost it
nothing.

WHY THIS IS NOT A CONSTANT, AND WHY IT IS DERIVED HERE RATHER THAN TYPED.
N is the ratio of the peer's per-chunk wall time to this rank's
per-decode-step wall time, so it belongs to a ``(model, box, flag-stack)``
triple exactly as ``ARBI_PP_STAGE_SPLIT`` does. Too small leaves the decode
paced by the chunk; too large idles the peer between chunks and the prefill
pays. A number that has to be measured first is a lever that is off wherever
nobody measured it — so both terms are read off THIS engine's own tick clock
instead, and the operator types a number only to override what it found.

BOTH TERMS ARE THE SAME CLOCK, WHICH IS WHAT MAKES THE RATIO SOUND. The
scheduler opens every tick at a ``time.monotonic()`` reading it already takes
for the duplex deadline, so the interval between two consecutive opens is one
tick's whole wall cost — the forward, the sampler and the host work included —
with no clock this module adds. Classifying those intervals by what the tick
carried gives the two terms directly:

* an interval whose tick put a SOLO-PREFILL chunk on the slate is a chunk's
  wall cost, because the chunk is what that tick spent its time on;
* an interval whose tick carried a decode row and NO solo chunk is this
  rank's per-decode-step wall cost.

Both classes are present before anything is derived: a co-admitted decode runs
alone until its prefill peer arrives, and while N is still 1 every tick carries
a chunk. The ratio is therefore measurable on the way in, and it stays
measurable after a value is adopted, because a paced tick's own interval is
still classified by what it carried rather than by N.

LATCHED ONCE, ON PURPOSE. The value is adopted the first time both sample sets
are full enough and is not revised after. A pacing decision changes which ticks
carry a chunk, and re-deriving from intervals the last decision shaped is a
loop whose fixed point is not the ratio. The engine logs what it adopted and
from what, so an operator who wants a different point on the trade pins a
number; nothing here second-guesses a pinned one.

REFUSES BY NAME RATHER THAN GUESSING. Below the sample floor, or when the
measured chunk is no longer than a decode step, the pacer stays at N=1 —
today's behaviour exactly — and records why on the flag's own counter. A boot
that could not measure and a boot that measured "no pacing wanted" must not
read alike.
"""

from __future__ import annotations

import logging
import statistics

from arbi_serve.engine.request import RequestState
from arbi_serve.flag_truth import FiringWindow, path_counter

__all__ = ["DERIVE", "CoadmitPacer"]

_LOG = logging.getLogger("arbi_serve.scheduler")

#: ``ARBI_PP_COADMIT_PREFILL_EVERY_N`` spelling for "measure it here". Any
#: value >= 1 is an operator pin and is used verbatim.
DERIVE = 0

#: Chunks the pacer held out of a tick. ``counted`` because the total is the
#: only thing that separates "the paced path ran" from "it ran a lot": the
#: contract asks the first, an operator reading the ratio back wants the
#: second. Refusals carry every way the gate declines, so a zero here is never
#: ambiguous between an unarmed stack and a stack that could not measure.
_COADMIT_PACED = path_counter("pp_coadmit_prefill_every_n", FiringWindow.SERVE, counted=True)


class CoadmitPacer:
    """The pacing decision for one engine, plus the measurement behind it.

    Owns the tick counter the gate reads, so the scheduler keeps no second
    copy of it. Constructed inert: with no solo-prefilling row in the system
    nothing here is reached, and every engine that is not a PP2 boot with the
    handoff armed pays one ``getattr`` miss per prefilling row per tick.
    """

    #: Solo-prefill chunk intervals needed before a ratio is taken. Small
    #: because the term is a whole prefill chunk — the noisiest thing in the
    #: numerator is the first one, which also carries the plan build.
    MIN_CHUNK_SAMPLES = 4

    #: Decode-only intervals needed. Larger than the chunk floor because they
    #: are cheap to come by (a co-admitted decode runs alone until its peer
    #: arrives) and because the denominator's spread moves with drafter
    #: acceptance, which is a property of the text.
    MIN_DECODE_SAMPLES = 8

    #: Ring depth per class. A median over the recent window rather than over
    #: the whole run, so a long warm-up cannot outvote the steady state.
    WINDOW = 64

    #: Ceiling on a derived value. A ratio past this is not a pacing decision,
    #: it is a measurement that went wrong — a stalled peer, a decode row that
    #: left, a tick that blocked on something neither term describes — and
    #: adopting it would park the prefill behind a decode that may itself end.
    #: An operator who really wants it pins it.
    MAX_DERIVED = 64

    def __init__(self, configured: int = DERIVE) -> None:
        self._configured = int(configured)
        self._derived: int | None = None
        self._tick_opened: float | None = None
        self._chunk_s: list[float] = []
        self._decode_s: list[float] = []
        self._tick_had_decode = False
        #: Ticks since a solo-prefilling row was last put on a slate. The gate
        #: reads it; ``note_solo_chunk_slated`` zeroes it.
        self.ticks_since_solo_chunk = 0

    # ── the decision ────────────────────────────────────────────────

    def every_n(self) -> int:
        """Ticks per offered chunk: the pin, the derived value, or 1."""
        if self._configured >= 1:
            return self._configured
        if self._derived is None:
            self._try_derive()
        return self._derived or 1

    def paced_out(self, req, running) -> bool:
        """True iff ``req``'s next prefill chunk is held out of THIS tick.

        Paces a row that is BOTH solo-prefilling and co-admitted with a live
        decode, and nothing else. Pacing a prefill with no decode beside it
        would be pure loss — there is nothing on the other rank for the spare
        ticks to serve — and the solo check comes first because it is the one
        every non-PP engine answers, at the cost of one ``getattr`` miss.
        """
        if not getattr(req, "_pp_prefill_solo", False):
            return False
        every = self.every_n()
        if every <= 1:
            _COADMIT_PACED.refuse(self._unpaced_reason())
            return False
        if self.ticks_since_solo_chunk >= every:
            return False
        if not any(
            r.state == RequestState.DECODING and r.request_id != req.request_id for r in running
        ):
            _COADMIT_PACED.refuse("no co-admitted decode beside the solo prefill")
            return False
        _COADMIT_PACED.fired += 1
        return True

    def _unpaced_reason(self) -> str:
        if self._configured >= 1:
            return "pinned at every_n=1: every tick carries a chunk"
        if self._derived is not None:
            return "derived every_n=1: a chunk costs no more than a decode step"
        return (
            f"deriving: have {len(self._chunk_s)}/{self.MIN_CHUNK_SAMPLES} chunk ticks and "
            f"{len(self._decode_s)}/{self.MIN_DECODE_SAMPLES} decode-only ticks"
        )

    # ── the measurement ─────────────────────────────────────────────

    @property
    def _measuring(self) -> bool:
        """Whether a sample is still worth taking: deriving, not yet latched.

        False for an operator pin and False after adoption, so the clock
        arithmetic and the slate scan below cost a boolean read on every
        engine that is not mid-derivation — including every engine that never
        arms the flag at all.
        """
        return self._configured < 1 and self._derived is None

    def open_tick(self, now: float) -> None:
        """Close the previous tick's interval and open this one.

        ``now`` is the scheduler's own ``time.monotonic()`` reading for this
        tick, passed in rather than taken here so the two cannot diverge and
        so a test injecting a clock reaches this too. Called before the tick
        counter advances, because the previous tick carried a solo chunk
        exactly when that counter is still at zero.
        """
        if self._measuring:
            prev, self._tick_opened = self._tick_opened, now
            if prev is not None and now > prev:
                self._note_interval(now - prev, carried_chunk=self.ticks_since_solo_chunk == 0)
            self._tick_had_decode = False
        self.ticks_since_solo_chunk += 1

    def break_interval(self) -> None:
        """Drop the open interval: what ran in it is not one of the terms.

        The duplex lane is the caller. A due duplex deadline takes the whole
        tick and returns before the ordinary slate is built, so the wall time
        between the two ordinary ticks either side of it is a decode step or
        a chunk PLUS a media frame — and charged to whichever of the two the
        earlier tick happened to carry. Dropping it is the honest reading:
        the pair of samples that would have straddled the frame is one the
        ratio never had.
        """
        self._tick_opened = None

    def note_slate(self, slate) -> None:
        """Record what the tick just built will spend its time on.

        Only whether a decode row is on it: the chunk half is already known
        from the tick counter. A slate is at most ``max_batch`` rows, and this
        stops looking at the first decode row.
        """
        if not self._measuring:
            return
        for req, _ in slate:
            if req.state == RequestState.DECODING:
                self._tick_had_decode = True
                return

    def note_solo_chunk_slated(self) -> None:
        """A solo-prefilling row took a chunk on this tick."""
        self.ticks_since_solo_chunk = 0

    def _note_interval(self, seconds: float, *, carried_chunk: bool) -> None:
        if carried_chunk:
            samples = self._chunk_s
        elif self._tick_had_decode:
            samples = self._decode_s
        else:
            # Neither term. An idle tick, or one that carried only a
            # cooperative prefill, describes nothing in the ratio.
            return
        samples.append(seconds)
        if len(samples) > self.WINDOW:
            del samples[0]

    def _try_derive(self) -> None:
        if (
            len(self._chunk_s) < self.MIN_CHUNK_SAMPLES
            or len(self._decode_s) < self.MIN_DECODE_SAMPLES
        ):
            return
        chunk = statistics.median(self._chunk_s)
        step = statistics.median(self._decode_s)
        if step <= 0.0:
            self._derived = 1
            return
        self._derived = max(1, min(self.MAX_DERIVED, round(chunk / step)))
        _LOG.info(
            "pp coadmit pacing: every_n=%d derived from a %.1f ms peer chunk over a "
            "%.1f ms decode step (%d/%d samples); pin ARBI_PP_COADMIT_PREFILL_EVERY_N "
            "to override",
            self._derived,
            chunk * 1e3,
            step * 1e3,
            len(self._chunk_s),
            len(self._decode_s),
        )
# ---- compression_admission.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Make admission policy compression-aware.

The KV pool's page CAPACITY already scales with the codec: num_pages =
kv_bytes // (backend.bytes_per_token * page_size), and a compressed codec's
per-token cost is a fraction of bf16's, so the same VRAM holds proportionally
more pages — the active backend's ``bytes_per_token`` is what states the
factor and the pool's realized page total is what it bought. The
scheduler's admission GATE (FlatPageTable.can_allocate) correctly consumes
that larger free list.

But the admission POLICY caps — ``cfg.batch.max_batch`` (default 32) and
``cfg.batch.max_batched_tokens`` — are static constants that do
NOT scale with the codec. So the recovered capacity sits idle: the engine
admits the same 32 sequences whether KV is bf16 or compressed.

This derives a compression-aware ``max_batch`` from the realized page capacity
and a target context, so the policy fills the capacity the codec bought."""

from __future__ import annotations


def pages_per_seq(context_tokens: int, page_size: int) -> int:
    """Pages one sequence of ``context_tokens`` needs (the can_allocate
    arithmetic: ceil(k / page_size); see cache/pagetable.py:169-173)."""
    return (int(context_tokens) + int(page_size) - 1) // int(page_size)


def recommend_max_batch(
    num_pages: int, page_size: int, target_context: int, *, hard_cap: int | None = None
) -> int:
    """Concurrent sequences of ``target_context`` tokens the pool can hold.

    ``num_pages`` reflects the active backend's compressed per-token cost
    (per-layer under smart-mix), so this rises with the compression ratio
    — unlike a static ``max_batch``. ``hard_cap`` clamps to an operator
    ceiling (e.g. a scheduler/runtime limit)."""
    pps = pages_per_seq(target_context, page_size)
    n = int(num_pages) // max(pps, 1)
    if hard_cap is not None:
        n = min(n, int(hard_cap))
    return max(n, 0)
# ---- flex_drain.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The gentle drain of paused flex prefill while interactive traffic is present.

An interactive request owns the step's prefill compute: no flex prefill runs and no flex is admitted while
one is present (``Scheduler.schedule``). With interactive traffic that never lets up, that would hold the
flex rows already admitted and paused mid-prefill out for as long as the traffic lasts. The drain lets them
complete over time, one at a time, in the steps where it costs interactive little:

* no interactive request is already prefilling (a QUEUED interactive request does not block it: the paused
  flex row may jump ahead of it, and the interactive request is admitted behind it in the same step, with its
  slot reserved);
* no flex request is decoding: no other flex request is going.

Then the oldest paused flex prefill advances by one chunk (capped like every flex prefill, so an interactive
arrival waits at most one small chunk). Once it is decoding it rides along with the interactive rows, and the
next paused flex prefill starts only after it is done. An interactive request that starts prefilling pauses
the drain again. Only requests already admitted are drained: new flex is not admitted while interactive is
present. Under per-task queues (``Scheduler.set_task_policies``) there is no drain: their picker owns the order.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from arbi_serve.engine.request import RequestState

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.scheduler import Scheduler


def plan_flex_drain(sched: Scheduler, interactive_present: bool) -> Request | None:
    """The one running flex row, mid-prefill, allowed to advance this step; ``None`` when none is.

    O(1) unless a flex row is running, then one walk of ``running``.
    """
    if not interactive_present:
        return None
    if getattr(sched, "_task_queues", None) is not None:
        # Per-task queues own admission order and exclusive steps (``task_queues``); a flex row sharing the step
        # with an interactive one would break an exclusive cohort. ``partial_prefill_first`` stands down the same way.
        return None
    n_interactive = getattr(sched, "_n_running_interactive", None)
    if not isinstance(n_interactive, int):
        n_interactive = sum(1 for r in sched.running if not r.is_flex)
    if len(sched.running) <= n_interactive:
        return None  # no flex row running
    first: Request | None = None
    for r in sched.running:
        if not r.is_flex:
            if r.state == RequestState.PREFILLING:
                return None  # an interactive prefill is going
        elif r.state == RequestState.DECODING:
            return None  # another flex request is going
        elif first is None and r.state == RequestState.PREFILLING:
            first = r
    return first


def flex_prefill_yields(sched: Scheduler, req: Request, drain_row: Request | None) -> bool:
    """Whether a running flex row sits this step out because interactive work is present.

    Interactive work owns the step's PREFILL compute: a flex prefill chunk is skipped (the row keeps its
    pages and resumes once interactive clears), except for the one row the drain lets through, or a
    background cohort that must drain for a higher-priority bulk task. A flex DECODE row is one cheap
    token, so it rides along in the same forward and never yields here.
    """
    return (
        req.state != RequestState.DECODING
        and req is not drain_row
        and not sched.must_drain_background(req)
    )


__all__ = ["flex_prefill_yields", "plan_flex_drain"]
# ---- media_continuation.py ----
# SPDX-License-Identifier: Apache-2.0
"""Reuse an unchanged admission slate while a media-only forward is suspended.

Media generators yield without advancing request prompt/KV state. Replanning
those same rows at every model layer does no admission work. Queue mutations
invalidate the slate before the next stage, including new interactive arrivals.
"""

from __future__ import annotations

from arbi_serve.engine.request import RequestState
from arbi_serve.scheduler.media_quota import MediaQuotaAdmission
from arbi_serve.scheduler.scheduler import Scheduler
from arbi_serve.tenant.context import UNLIMITED


class MediaContinuationScheduler(Scheduler):
    """A narrow fast path for the one-device, media-only FORWARD engine."""

    def __init__(self, *args, media_engine, **kwargs):
        super().__init__(*args, **kwargs)
        self._media_engine = media_engine
        self._media_quota = MediaQuotaAdmission(self._quota_filter)
        self._continuation_key = None
        self._continuation_slate = None

    def set_task_policies(self, policies):
        super().set_task_policies(policies)
        if self._task_queues is not None:
            self._task_queues.admission_ready = self._media_quota.ready

    def _running_add(self, req):
        # Selection preview and this commitment run synchronously on the same
        # engine thread. No other quota reservation can intervene between them.
        if self._task_queues is not None and not self._media_quota.reserve(req):
            raise RuntimeError("media quota changed after readiness selection")
        super()._running_add(req)

    def _apply_tenant_quota(self, slate):
        # A partial model stage emits no new prompt/completion tokens. Its
        # request already reserved quota on first admission, before running.
        if self._task_queues is None:
            return super()._apply_tenant_quota(slate)
        return slate

    def _media_key(self):
        eng = self._media_engine
        queues = self._task_queues
        if (
            queues is None
            or not getattr(eng.model, "media_only_forward", False)
            or not getattr(eng.model, "deferred_media", False)
            or eng.duplex_lane is not None
            or self.parking_enabled
            or self._deferred_admits
        ):
            return None
        # Config groups are frozen dataclasses; hot changes replace them.
        return (
            id(eng.model),
            id(self.batch_cfg),
            id(self.cache_cfg),
            id(queues),
            queues.revision,
            id(self.activation_model),
        )

    def schedule(self, *, _now=None):
        key = self._media_key()
        if key is not None and key == self._continuation_key:
            return self._continuation_slate
        self._continuation_key = None
        self._continuation_slate = None
        self._media_quota.begin_step()
        slate = super().schedule(_now=_now)
        queues = self._task_queues
        if (
            key is not None
            and slate
            and len(slate) == len(self.running)
            and not any(p.max_wait_ms for p in queues.policies.values())
            and all(
                req.state == RequestState.PREFILLING
                and req.multimodal
                and getattr(req, "_media_embeds", None) is None
                and not req.sampling.cache_enabled
                and not req.is_duplex_frame
                and (self._media_quota.reserved(req) or req.tenant.quota_budget == UNLIMITED)
                for req, _ in slate
            )
            # With no batching timers, a missing candidate means every
            # waiting head is blocked by inflight/exclusive-task policy.
            # Only a queue mutation can make one eligible again.
            and queues.pick(interactive_only=False, slate_has_work=True) is None
            and not self._media_quota.deferred_this_step
        ):
            self._continuation_key = self._media_key()
            self._continuation_slate = slate
        return slate
# ---- media_quota.py ----
# SPDX-License-Identifier: Apache-2.0
"""Reserve quota once for a whole deferred media request, before it owns a task slot."""

from __future__ import annotations


class MediaQuotaAdmission:
    def __init__(self, quota_filter):
        self.filter = quota_filter
        self.deferred_this_step = False
        self._reported = set()

    def begin_step(self):
        self.deferred_this_step = False
        self._reported.clear()

    @staticmethod
    def _unrestricted(tenant):
        budget = tenant.quota_budget
        return (
            budget.tokens_per_second is None
            and budget.max_concurrent_requests is None
            and budget.max_prompt_tokens is None
        )

    @staticmethod
    def _cost(req):
        # Preserve the existing scheduler quota unit (the Request prompt),
        # reserving it once even if a smaller prefill chunk was scheduled.
        # Pooling task_tokens metadata has never defined scheduler quota cost.
        tokens = len(req.prompt_token_ids)
        return dict(prompt_tokens=tokens, cost_tokens=float(tokens), request_id=req.request_id)

    def reserved(self, req):
        return getattr(req, "_media_quota_reserved", None) is self.filter.tracker

    def ready(self, req):
        if self.reserved(req):
            return True
        tenant = self.filter._tenant_for(req)
        if self._unrestricted(tenant):
            return True
        decision = self.filter.tracker.preview_admit(tenant, **self._cost(req))
        if not decision.admitted:
            self.deferred_this_step = True
            if req.request_id not in self._reported:
                self._reported.add(req.request_id)
                self.filter.note_deferred(tenant, decision)
        return decision.admitted

    def reserve(self, req):
        if self.reserved(req):
            return True
        tenant = self.filter._tenant_for(req)
        if tenant.tenant_id in ("", "anon") and self._unrestricted(tenant):
            return True
        decision = self.filter.tracker.try_admit(tenant, **self._cost(req))
        if decision.admitted:
            req._media_quota_reserved = self.filter.tracker
        else:
            self.filter.note_deferred(tenant, decision)
        return decision.admitted
# ---- mtp_bucketing.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Admission-time MTP K-bucketing policy.

The verify pass requires a SINGLE uniform K every step (cudagraph capture
invariant — baked-in ``cu_seqlens_q`` / ``tokens_per_seq``). Rather than
coerce all rows down to ``min(K)`` (which would throw away every K=7
row's draft chain that step), the scheduler picks ONE K per step and
drops rows at other K values from the slate; the dropped rows stay in
``Scheduler.running`` and run next step.

``MtpBucketer`` owns the per-K consecutive-skip bookkeeping
(``skip_counts``) so the starvation guard
(``BatchConfig.mtp_admission_starvation_steps``) can force a K-bucket
pick after the bucket has been skipped that many steps in a row.

It also applies the speculation load valve, which decides whether a step
drafts at all. The valve's tri-state and the measurement behind ``auto``
live in :mod:`arbi_serve.scheduler.spec_valve`; this module owns only the
mutation (transiently zeroing ``sampling.mtp_k``) and its observability.
"""

from __future__ import annotations

import logging
import time
from typing import TYPE_CHECKING

from arbi_serve.flag_truth import path_counter
from arbi_serve.runtime_flags import runtime_flags
from arbi_serve.scheduler.spec_request_gate import REQUEST_GATE_ROWS, declines
from arbi_serve.scheduler.spec_row_estimate import ROW_ESTIMATE, enabled, estimate_of
from arbi_serve.scheduler.spec_valve import (
    DECIDE_MARGIN,
    MODE_AUTO,
    MODE_OFF,
    MODE_ON,
    SOURCE_ARCH_FALLBACK,
    SOURCE_MEASURED,
    SpecValveController,
    ValveSetting,
    arch_fallback_batch,
    parse_valve_flag,
)
from arbi_serve.scheduler.spec_valve_mode import dense_prior_refuted
from arbi_serve.spec_decode.controller import StepCostBook, StepMeter
from arbi_serve.spec_decode.depth_control import CONTROLLER_STEPS
from arbi_serve.spec_shadow import shadow_available

if TYPE_CHECKING:
    from arbi_serve.config import BatchConfig
    from arbi_serve.engine.request import Request

#: Flag-truth counter for ``ARBI_MTP_SPEC_DISABLE_BATCH``, fired at its
#: READ site — the resolved valve governs the step's spec-disable
#: decision. Fires in ``on`` (with a positive batch) and in ``auto``,
#: which are the modes that can bite; ``off`` refuses.
#:
#: The FIRE is deliberately NOT latched: this flag is live-flippable via
#: ``/v1/admin/config_override``, so a latch would freeze the counter at
#: the first state it saw and lie about a mid-serve flip. A plain int
#: increment per admission step is free (this is the same shape as
#: ``spmd_step``, which fires on the hottest loop in the engine).
#: The REFUSE is latched, because a dict write per admission step is not.
_MTP_SPEC_DISABLE = path_counter("mtp_spec_disable_threshold_read")

#: Flag-truth counter for the load valve ACTUALLY BITING: fired once per
#: admission step on which the gate zeroed the opted rows' ``mtp_k``.
#:
#: Separate from ``_MTP_SPEC_DISABLE`` by contract. That counter fires when
#: the threshold is READ, which happens every admission step whatever the
#: batch is — it answers "is the flag set", never "is speculation running".
#: Silently dropping speculation under load is the state an operator has to
#: be able to see, so it gets its own counter, incremented at the mutation.
_MTP_SPEC_DISABLED_BY_LOAD = path_counter("mtp_spec_disabled_by_load")

#: A temperature-0 row was weighed by the valve (``ARBI_MTP_VALVE_GREEDY``): fired once per admission step that
#: carries one. Without the flag greedy rows are outside the valve and this stays at zero.
_MTP_VALVE_GREEDY_ROWS = path_counter("mtp_valve_greedy_rows")

#: The serving model's default for ``ARBI_MTP_VALVE_GREEDY`` (stamped at boot by a model whose drafter loses on open
#: text); the flag, when set, wins.
_GREEDY_DEFAULT = False


def set_valve_greedy_default(on: bool) -> None:
    """Stamp the serving model's default for weighing temperature-0 rows in the valve."""
    global _GREEDY_DEFAULT
    _GREEDY_DEFAULT = bool(on)


def valve_weighs_greedy() -> bool:
    """Whether greedy rows enter the valve: the flag if set, else the model's stamped default."""
    mode = runtime_flags().mtp_valve_greedy
    if mode in ("on", "off"):
        return mode == "on"
    return _GREEDY_DEFAULT


#: Floor between two spec-disable transition log lines, seconds. The gate can
#: flip on consecutive steps when the decode batch oscillates across the
#: threshold; the counters stay exact per step while the log stays readable.
_TRANSITION_LOG_MIN_INTERVAL_S = 5.0

logger = logging.getLogger(__name__)

_spec_disable_off_latched = False

#: Boot-stamped architecture FALLBACK for the load valve. Process-wide
#: because the flag is. It is a guess from the served verifier's FFN
#: topology, never a measurement: it supplies ``auto``'s starting arm
#: before anything has been measured, and the batch a bare ``on`` pins.
#: :class:`~arbi_serve.scheduler.spec_valve.SpecValveController` replaces
#: it with a live comparison as soon as it holds both arms at a width.
_ARCH_DEFAULT: int = 0
_ARCH_DEFAULT_REASON: str = "no spec-decode verifier resolved"

#: ``(flags snapshot, raw flag string, resolved setting)``. The flag is fresh-read per
#: admission step so it hot-swaps live; memoizing on the raw string keeps
#: that read to one string compare on the hot path.
_SETTING_CACHE: tuple[object, str, ValveSetting] | None = None


def resolve_spec_disable_arch_default(layer_specs) -> tuple[int, str]:
    """The valve's architecture fallback for a verifier with these specs.

    Thin alias for :func:`~arbi_serve.scheduler.spec_valve.arch_fallback_batch`
    so the scheduler-side name stays where its callers expect it.
    """
    return arch_fallback_batch(layer_specs)


def set_spec_disable_arch_default(threshold: int, reason: str) -> None:
    """Stamp the boot-resolved architecture fallback for the load valve."""
    global _ARCH_DEFAULT, _ARCH_DEFAULT_REASON, _SETTING_CACHE
    _ARCH_DEFAULT = max(0, int(threshold))
    _ARCH_DEFAULT_REASON = str(reason)
    # The fallback is an input to the parse (a bare ``on`` resolves to it),
    # so a re-stamp must invalidate the memoized setting.
    _SETTING_CACHE = None


def spec_disable_arch_default() -> tuple[int, str]:
    """The boot-stamped architecture fallback and the reason behind it."""
    return _ARCH_DEFAULT, _ARCH_DEFAULT_REASON


def _resolve_setting() -> ValveSetting:
    """Fresh-read ``mtp_spec_disable_batch`` and resolve its tri-state.

    Live via ``/v1/admin/config_override``; see
    :func:`~arbi_serve.scheduler.spec_valve.parse_valve_flag` for the
    accepted values.
    """
    global _SETTING_CACHE, _spec_disable_off_latched

    flags, cached = runtime_flags(), _SETTING_CACHE
    if cached is not None and cached[0] is flags:
        setting = cached[2]  # the same snapshot: production reads one per boot or override
    else:
        raw = str(flags.mtp_spec_disable_batch or "")
        if cached is not None and cached[1] == raw:
            setting = cached[2]
        else:
            setting = parse_valve_flag(
                raw, arch_batch=_ARCH_DEFAULT, arch_reason=_ARCH_DEFAULT_REASON
            )
        _SETTING_CACHE = (flags, raw, setting)
    if setting.mode == MODE_OFF or (setting.mode == MODE_ON and setting.pinned <= 0):
        # Latched: the valve cannot bite in this mode and this resolver runs
        # per admission step. An unlatched refuse() would put a dict write on
        # an inner loop — the one thing a counter may never do.
        if not _spec_disable_off_latched:
            _spec_disable_off_latched = True
            _MTP_SPEC_DISABLE.refuse("valve_off_never_disable")
    else:
        # The valve governs this step's decision. NOT latched — the flag is
        # live-flippable, so a latch would freeze the counter at the first
        # observed state and lie about the flip.
        _MTP_SPEC_DISABLE.fired = 1
    return setting


def _prior_detail() -> str:
    """The dense-prior gate's surfaced detail, rebuilt only when the topology reason changes."""
    global _PRIOR_DETAIL
    if _PRIOR_DETAIL[0] is not _ARCH_DEFAULT_REASON:
        _PRIOR_DETAIL = (
            _ARCH_DEFAULT_REASON,
            f"not measuring: every row clears the measured step cost ({_ARCH_DEFAULT_REASON})",
        )
    return _PRIOR_DETAIL[1]


_PRIOR_DETAIL: tuple[object, str] = (None, "")

#: The restore set outside :meth:`MtpBucketer._apply_spec_disable_by_load` (never written).
_NONE_RESTORED: dict = {}


def _already_stood_down(req: Request) -> bool:
    """Whether ``req`` still carries exactly what :meth:`MtpBucketer._stand_down` leaves on a row."""
    return (
        not req.mtp_next_drafts
        and req.mtp_next_drafts_dev is None
        and req.mtp_next_draft_probs is None
        and req.mtp_next_draft_conf is None
        and req.mtp_drafter_context_stale is True
        and getattr(estimate_of(req), "stood_down", True)
    )


class MtpBucketer:
    """Single-K-per-step slate filter for MTP-opted decode rows."""

    def __init__(self, batch_cfg: BatchConfig) -> None:
        self._batch_cfg = batch_cfg
        # Admission-time MTP K-bucketing bookkeeping.
        #
        # ``skip_counts`` tracks consecutive skips per K so the
        # starvation guard can force a K-bucket pick after the bucket
        # has been skipped ``mtp_admission_starvation_steps`` times in a
        # row. Empty dict ⇒ no MTP-opted rows seen yet.
        self.skip_counts: dict[int, int] = {}
        # Load-adaptive spec-disable restore set. When the gate fires it
        # zeroes ``sampling.mtp_k`` on the opted rows for ONE step so they
        # decode via the rank-symmetric MTP-off path; this maps each such
        # request (by id) to ``(request, original_k)`` so the NEXT call
        # restores it — robust even if the row leaves the slate meanwhile.
        # See ``_apply_spec_disable_by_load``.
        self._spec_disabled: dict[int, tuple[Request, int]] = {}
        #: Last step's stand-down set while a call restores it (``_apply_spec_disable_by_load``).
        self._restored: dict[int, tuple[Request, int]] = _NONE_RESTORED
        # ── Load-valve observability ───────────────────────────────────
        # An operator who enabled spec-decode must be able to see that the
        # engine stopped speculating. These are the only record of it: the
        # gate's effect is otherwise indistinguishable from a drafter that
        # simply proposes nothing.
        #
        # ``spec_disabled_now`` is the live state (read by the admin
        # ``server_info`` surface); ``spec_disabled_steps`` is a monotonic
        # count of admission steps the gate actually bit on (bridged to
        # ``arbi_serve_mtp_spec_disabled_steps_total`` by the heartbeat);
        # ``spec_disable_threshold`` / ``spec_disable_batch`` carry the
        # numbers from the latest decision so the surfaced state names WHY.
        self.spec_disabled_now: bool = False
        self.spec_disabled_steps: int = 0
        self.spec_disable_threshold: int = 0
        self.spec_disable_batch: int = 0
        # The tri-state the operator set, and where the threshold above came
        # from. Reported alongside the number so ``auto`` resolving to 2 and
        # an operator pinning 2 are distinguishable, which a bare integer
        # cannot express.
        self.spec_disable_mode: str = MODE_AUTO
        self.spec_disable_source: str = ""
        self.spec_disable_detail: str = ""
        self._transitions_since_log: int = 0
        self._last_transition_log_s: float = 0.0
        # ``auto``'s measurement. Constructed unconditionally: it holds no
        # device state and costs nothing until an ``auto`` step drives it,
        # and the flag is live-flippable INTO auto mid-serve. Seeded from the
        # process-wide architecture fallback here AND re-seeded by
        # ``set_valve_bootstrap`` from the boot path, because the scheduler
        # and the MTP driver are built in either order.
        self._valve = SpecValveController(
            bootstrap_batch=_ARCH_DEFAULT, bootstrap_detail=_ARCH_DEFAULT_REASON
        )
        self._boot_price = None
        self._step_timer = None
        # The speculation controller's cost source: every decode step, timed passively, whichever arm
        # and whichever sampling it ran (``spec_decode/controller.StepMeter``).
        self._depth_costs = StepCostBook()
        self._meter = StepMeter(self._depth_costs)
        self._depth_policy = None

    def step_cost_table(self, width: int):  # noqa: ANN201
        """Measured step costs by submitted depth at decode ``width``, or ``None`` until there are enough."""
        return self._depth_costs.table(width)

    def step_cost_ms(self, rows: int, tokens: int) -> float | None:
        return self._depth_costs.step_ms(rows, tokens)

    def step_cost_wants_plain(self, width: int) -> bool:
        return self._depth_costs.wants_plain(width)

    def set_depth_policy(self, drafter) -> None:  # noqa: ANN001
        """The drafter whose depth the controller chooses (:class:`~arbi_serve.spec_decode.depth_control.DepthControlled`)."""
        self._depth_policy = drafter

    def _steered(self) -> bool:
        """Whether the controller, not the valve, decides draft-or-not at admission for this engine's drafter."""
        return (
            self._depth_policy is not None
            and self._depth_policy.steers_at_admission
            and self._depth_policy.active_controller() is not None
        )

    def _meter_step(self, slate: list[tuple[Request, int]]) -> None:
        """Time the step that just ran, from the movement of its rows' proposed-draft counts."""
        if self._depth_policy is None:
            return
        rows = [(r.request_id, int(r.mtp_proposed)) for r, _n in slate]
        self._meter.note(time.monotonic(), rows, all(not r.is_prefill for r, _n in slate))

    def _steer_depth(self, slate: list[tuple[Request, int]]) -> None:
        """The controller's verdict for this step: a depth for the rows that draft, plain for the rest.

        Runs after the valve, so a row it stood down is not here. A plain verdict stands the row down
        before its drafter's pass is paid; a depth verdict reaches the verify plan through the
        drafter (``depth_target``). Only a drafter that steers at admission is asked: a free proposer
        decides as it proposes.
        """
        policy = self._depth_policy
        if policy is None or not self._steered():
            return
        rows = [r for r, _n in slate if not r.is_prefill and r.sampling.mtp_k > 0]
        for req in rows:
            policy.set_depth_target(req, 0)
        verdict = policy.depth_slate(rows) if rows else None
        if verdict is None:
            return
        width = len(rows)
        for req, on in zip(rows, verdict.active, strict=True):
            if on:
                policy.set_depth_target(req, verdict.depth if verdict.depth < policy.max_k else 0)
            else:
                self._stand_down(req)
                policy.note_plain(req, width)
        CONTROLLER_STEPS.fire_n(1)

    def set_valve_bootstrap(self, batch: int, detail: str) -> None:
        """Seed ``auto`` with the architecture fallback: ``0`` marks a dense verifier (``dense_prior``)."""
        self._valve = SpecValveController(bootstrap_batch=batch, bootstrap_detail=detail)
        self._valve.boot_price = self._boot_price
        self._valve.step_timer = self._step_timer

    def set_valve_boot_price(self, price) -> None:
        """The speculating step's boot-measured price for this engine's valve (``spec_valve_boot``)."""
        self._boot_price = price
        self._valve.boot_price = price

    def set_valve_step_timer(self, timer) -> None:
        """The runner's device step timer for this engine's valve (``spec_decode.step_timing``)."""
        self._step_timer = timer
        self._valve.step_timer = timer

    def valve_widths(self) -> dict:
        """``auto``'s per-cell arm estimates, kept across mode flips; empty until ``auto`` has run."""
        return self._valve.snapshot()

    def _apply_spec_disable_by_load(self, slate: list[tuple[Request, int]]) -> None:
        """Coerce the whole step to mtp_k=0 when speculation is not paying.

        FIRST restore any rows zeroed last step, THEN — if the resolved
        valve says stop — transiently zero ``sampling.mtp_k`` on every
        opted decode row so the step routes through the proven MTP-OFF
        decode path (no seed-drafter, no verify, no worker-bridge
        drafter/seed ops).

        Which rows are zeroed is the same in every mode; the modes differ
        only in what decides. ``off`` never zeroes, ``on`` zeroes at a
        pinned decode width, and ``auto`` asks
        :class:`~arbi_serve.scheduler.spec_valve.SpecValveController`,
        which compares the two arms' measured committed tokens/sec at the
        width being served.

        Rank-symmetric by construction: only rank 0 runs the scheduler,
        and zeroing the K makes rank 0 emit the SAME op stream a
        genuinely non-opted slate emits — the MTP-fill gate
        (``mtp_fill_enabled=False``) + ``mtp_per_req_k=None`` ride the
        per-step broadcast, so the worker rebuilds an identical batch.

        Mutation is scoped to a single engine step: the restore at the
        top of the NEXT call runs before any reader sees the request.
        """
        # Restore last step's zeroed rows (idempotent; survives rows that
        # finished / left the slate — we restore by stashed identity). Their
        # estimates' ``stood_down`` is cleared after this call, for the rows it
        # does not stand down again: nothing between here and there reads it.
        restored = self._spec_disabled
        if restored:
            for req, orig_k in restored.values():
                req.sampling.mtp_k = orig_k
            self._spec_disabled = {}
        self._restored = restored
        try:
            self._gate(slate)
        finally:
            self._restored = _NONE_RESTORED
            if restored:
                held = self._spec_disabled
                for rid, (req, _k) in restored.items():
                    if rid not in held:
                        est = estimate_of(req)
                        if est is not None:
                            est.stood_down = False

    def _gate(self, slate: list[tuple[Request, int]]) -> None:
        """The decision half of :meth:`_apply_spec_disable_by_load`, after the restore."""

        self._stand_down_declined_requests(slate)
        setting = _resolve_setting()
        # A drafter that reads a plain row's acceptance by shadow passes needs no prior:
        # every cell is measured, and a row in a losing cell learns without speculating.
        if setting.mode == MODE_AUTO and self._valve.dense_prior() and not shadow_available():
            opted = [r for r, _n in slate if not r.is_prefill and r.sampling.mtp_k > 0]
            # The prior holds only in a cell with a measured step-cost ratio that every row's own
            # acceptance clears; any other slate is decided by the measured path (``spec_valve``).
            if not dense_prior_refuted(opted, self._valve.step_cost_ratio(opted), DECIDE_MARGIN):
                self._valve.note_prior(opted)
                self.spec_disable_mode = setting.mode
                self.spec_disable_source = SOURCE_ARCH_FALLBACK
                self.spec_disable_threshold = self._valve.disable_batch()
                self.spec_disable_detail = _prior_detail()
                self._note_gate(disabled=False, batch=0, threshold=0)
                return
        self.spec_disable_mode = setting.mode
        self.spec_disable_source = setting.source

        if setting.mode == MODE_OFF:
            self.spec_disable_threshold = 0
            self.spec_disable_detail = setting.detail
            self._note_gate(disabled=False, batch=0, threshold=0)
            return

        # Opted rows are the decode rows that WOULD speculate. Prefill rows
        # never enter the verify pass, so they are neither the load the
        # valve is weighing nor part of what it measures — and a step that
        # carries any of them is not a decode step whose wall clock can be
        # charged to an arm.
        opted = []
        pure_decode = True
        greedy_rows = False
        for req, _n in slate:
            if req.is_prefill:
                pure_decode = False
            elif req.sampling.mtp_k > 0:
                if self._steered():
                    continue
                if (
                    setting.mode == MODE_AUTO
                    and req.sampling.is_greedy
                    and not valve_weighs_greedy()
                ):
                    greedy_rows = True
                else:
                    if req.sampling.is_greedy:
                        _MTP_VALVE_GREEDY_ROWS.fired = 1
                    opted.append(req)
        # ``auto`` never probes a temperature-0 row plain. A verify slate and a
        # plain decode step compute the same position with different kernels
        # (``docs/determinism.md``), so a probe timed off the wall clock would
        # make greedy text depend on when it ran. Such a row speculates on
        # every step and is not in what the valve weighs. A step that carries
        # one is not a clean sample of either arm, so it is scored like a
        # prefill step: skipped, with the phase and arm held.
        if greedy_rows:
            pure_decode = False

        if setting.mode == MODE_ON:
            threshold = setting.pinned
            self.spec_disable_threshold = threshold
            self.spec_disable_detail = setting.detail
            # A non-positive threshold is not "disable at every batch" — it is
            # no threshold at all. The parse never produces one; this is the
            # backstop so it can never be read the other way.
            disable = threshold > 0 and len(opted) >= threshold
        else:
            disable = not self._valve.should_speculate(opted, pure_decode=pure_decode)
            # ``auto`` has no single threshold; it reports the smallest width
            # it has MEASURED a stop verdict at, so the surfaced number means
            # the same thing it does in ``on``.
            self.spec_disable_threshold = self._valve.disable_batch()
            self.spec_disable_detail = self._valve.detail
            self.spec_disable_source = (
                SOURCE_MEASURED if self._valve.measured() else SOURCE_ARCH_FALLBACK
            )

        if not disable or not opted:
            if opted and setting.mode == MODE_AUTO and enabled():
                self._stand_down_rows_below_cost(opted)
            self._note_gate(disabled=False, batch=len(opted), threshold=self.spec_disable_threshold)
            return
        for req in opted:
            self._stand_down(req)
        self.spec_disabled_steps += 1
        _MTP_SPEC_DISABLED_BY_LOAD.fired = 1
        self._note_gate(disabled=True, batch=len(opted), threshold=self.spec_disable_threshold)

    def _stand_down_declined_requests(self, slate: list[tuple[Request, int]]) -> None:
        """Stand down every decode row whose own acceptance is below ``ARBI_MTP_REQUEST_GATE`` (see its module)."""
        floor = float(runtime_flags().mtp_request_gate)
        if floor <= 0.0:
            return
        for req, _n in slate:
            if not req.is_prefill and req.sampling.mtp_k > 0 and declines(req, floor):
                self._stand_down(req)
                REQUEST_GATE_ROWS.fired = 1

    def _stand_down_rows_below_cost(self, opted: list[Request]) -> None:
        """On a speculating slate, stand down each row whose own estimate loses.

        Only a row a host drafter keeps an estimate for
        (:mod:`~arbi_serve.scheduler.spec_row_estimate`) is judged. One whose expected
        tokens per step is below the width's measured step-cost ratio would
        pay a verify width it does not earn back; it decodes plainly and keeps
        measuring itself by shadow drafts until it clears the ratio again.
        """
        ratio = self._valve.step_cost_ratio(opted)
        if ratio <= 0.0:
            return
        losing = []
        for req in opted:
            est = estimate_of(req)
            if est is not None and not est.keeps(ratio):
                losing.append(req)
        # Standing down EVERY row would turn the step plain while the valve
        # charges it to the speculating arm it chose, corrupting that arm's
        # step cost and tokens/sec. Whether the whole slate speculates is the
        # valve's call (its slate model reads these same estimates).
        if len(losing) == len(opted):
            return
        for req in losing:
            self._stand_down(req)
            ROW_ESTIMATE.fire_n(1)

    def _stand_down(self, req: Request) -> None:
        """Run ``req`` plain for this step; the next call restores its ``mtp_k``."""
        if req.request_id not in self._spec_disabled:
            self._spec_disabled[req.request_id] = (req, int(req.sampling.mtp_k))
            req.sampling.mtp_k = 0
            if req.request_id in self._restored and _already_stood_down(req):
                return  # stood down last step and nothing since gave it drafts or a fresh context
            est = estimate_of(req)
            if est is not None:
                est.stood_down = True
            # The step this row is about to run COMMITS a token that the
            # drafter will not observe (the MTP-off path runs no seed-drafter
            # and no verify). Two pieces of drafter state are keyed to the
            # committed prefix and must not be carried across it:
            #
            #   * the cached drafts, which predict the token this step is
            #     about to commit — verifying them on the next speculating
            #     step proposes every draft one position late, so they cost a
            #     whole B*(K+1) verify for an accept rate near zero. Dropping
            #     them makes the next speculating step a cold K=0 tick that
            #     re-seeds instead;
            #   * a tap-conditioned drafter's draft-KV slot, which now covers
            #     a shorter span than the request. ``mtp_drafter_context_stale``
            #     tells it to re-seed rather than append onto the hole.
            #
            # Both are REVERSIBLE: nothing about the row's speculation is
            # lost beyond the drafter context it must rebuild, and the valve
            # restores ``mtp_k`` on the next call as before.
            req.mtp_next_drafts = []
            # The DEVICE handle too: left set, the row still read as holding
            # drafts, so this plain step took the MTP route's synchronous
            # drains instead of the async plain step, and the resume step
            # took the verify pass with nothing to verify instead of the seed.
            req.mtp_next_drafts_dev = None
            req.mtp_next_draft_probs = None
            req.mtp_next_draft_conf = None
            req.mtp_drafter_context_stale = True

    def _note_gate(self, *, disabled: bool, batch: int, threshold: int) -> None:
        """Record the load valve's state, logging only on a transition edge.

        Off the per-step cost path by construction: the common case is a
        bool compare against the state this method last stored. Only an
        edge reaches the clock or the logger, and consecutive edges inside
        ``_TRANSITION_LOG_MIN_INTERVAL_S`` are folded into the next line's
        suppressed count so an oscillating batch cannot flood the log.
        """
        if disabled == self.spec_disabled_now:
            return
        self.spec_disabled_now = disabled
        self.spec_disable_batch = batch
        self._transitions_since_log += 1
        now = time.monotonic()
        if now - self._last_transition_log_s < _TRANSITION_LOG_MIN_INTERVAL_S:
            return
        folded = self._transitions_since_log - 1
        self._transitions_since_log = 0
        self._last_transition_log_s = now
        suffix = f" ({folded} further transition(s) folded)" if folded else ""
        if disabled:
            logger.warning(
                "spec-decode DISABLED: %d MTP-opted decode row(s), valve mode=%s "
                "(ARBI_MTP_SPEC_DISABLE_BATCH / mtp_spec_disable_batch) — %s. "
                "Set the flag to 'off' to always speculate.%s",
                batch,
                self.spec_disable_mode,
                self.spec_disable_detail or f"threshold {threshold}",
                suffix,
            )
        else:
            logger.info(
                "spec-decode RESUMED: %d MTP-opted decode row(s), valve mode=%s — %s.%s",
                batch,
                self.spec_disable_mode,
                self.spec_disable_detail or f"threshold {threshold}",
                suffix,
            )

    def bucket_uniform(self, slate: list[tuple[Request, int]]) -> list[tuple[Request, int]]:
        """Drop MTP-opted decode rows whose K differs from the chosen step K.

        Policy (strict per-step single-K slates):

          1. Find the MTP-opted decode rows in the slate
             (``mtp_k > 0`` and ``not is_prefill``). Prefill rows and
             ``mtp_k == 0`` rows pass through untouched — they don't
             enter the verify pass and never need K-uniformity.
          2. If 0 or 1 distinct K values are present among MTP rows,
             return the slate unchanged. Common case at low traffic.
          3. Otherwise, group MTP rows by K. Pick ``step_k`` as the K
             with the most MTP rows. Tie-break: the K of the
             slate-earliest MTP row at any tied count (FCFS-like —
             oldest-waiting request wins).
          4. Starvation guard. If any OTHER K bucket's consecutive-
             skip count has reached ``batch_cfg.mtp_admission_starvation_steps``,
             override step 3 and pick THAT K instead (oldest-skipped K
             wins on ties). Prevents one K bucket from being
             permanently starved by a heavy stream of another K.
          5. Drop every MTP row whose K != step_k from the slate. The
             dropped rows stay in ``Scheduler.running`` (we never popped
             them) so they're retried next step. Update skip counts:
             ``+1`` for each K bucket we just skipped; reset to ``0``
             for the K bucket we picked.

        Idempotent: calling on an already-uniform slate is O(slate)
        and a no-op past step 2.

        Returns the filtered slate (same rows for prefill / non-opted
        decode; only MTP-opted rows at ``step_k`` survive). The
        scheduler's ``commit()`` only operates on the returned rows;
        the engine's downstream verify pass sees a uniform-K slate by
        construction.
        """
        # Load-adaptive spec disable (runs FIRST so zeroed rows are no
        # longer "MTP-opted" below and pass through as plain decode). Also
        # restores the prior step's zeroed rows. No-op when the threshold
        # flag is unset (''/0).
        self._meter_step(slate)
        self._apply_spec_disable_by_load(slate)
        self._steer_depth(slate)
        if not slate:
            return slate
        # Index MTP-opted decode rows by K.
        mtp_rows_by_k: dict[int, list[int]] = {}
        for i, (req, _n) in enumerate(slate):
            if req.sampling.mtp_k > 0 and not req.is_prefill:
                mtp_rows_by_k.setdefault(int(req.sampling.mtp_k), []).append(i)
        if len(mtp_rows_by_k) <= 1:
            # Already uniform-K (or no MTP rows). Reset skip counts for
            # any K present so a later mixed-K step doesn't carry stale
            # skip credits forward.
            if mtp_rows_by_k:
                only_k = next(iter(mtp_rows_by_k))
                self.skip_counts[only_k] = 0
            return slate
        # Pick the dominant K. Tie-break: K of the slate-earliest MTP
        # row at any tied count (oldest-admitted wins; the slate is
        # FCFS over running by construction).
        starvation_n = int(getattr(self._batch_cfg, "mtp_admission_starvation_steps", 4))
        starved_ks = [k for k in mtp_rows_by_k if self.skip_counts.get(k, 0) >= starvation_n]
        if starved_ks:
            # Force-pick the most-starved (highest skip count) K; on
            # ties pick the K with the oldest slate position
            # (FCFS-fair). Bypasses the dominant-bucket heuristic
            # entirely so a single K=7 row stuck behind a K=1 stream
            # eventually runs.
            def _starve_key(k: int) -> tuple[int, int]:
                return (-self.skip_counts.get(k, 0), mtp_rows_by_k[k][0])

            step_k = min(starved_ks, key=_starve_key)
        else:
            # Dominant bucket: most rows; tie → earliest slate row.
            def _dom_key(k: int) -> tuple[int, int]:
                return (-len(mtp_rows_by_k[k]), mtp_rows_by_k[k][0])

            step_k = min(mtp_rows_by_k, key=_dom_key)
        # Update skip counts: +1 for skipped K buckets; reset for the
        # picked K. We touch only K buckets present this step; absent
        # buckets keep their last skip count (decay only when they
        # reappear with rows competing).
        for k in mtp_rows_by_k:
            if k == step_k:
                self.skip_counts[k] = 0
            else:
                self.skip_counts[k] = self.skip_counts.get(k, 0) + 1
        # Filter the slate: keep prefill / non-MTP rows, plus MTP rows
        # at step_k. Dropped MTP rows remain in Scheduler.running for
        # the next step's slate (we never popped them in schedule()).
        keep_mtp_rows = set(mtp_rows_by_k[step_k])
        out: list[tuple[Request, int]] = []
        for i, entry in enumerate(slate):
            req, _n = entry
            if req.sampling.mtp_k > 0 and not req.is_prefill:
                if i in keep_mtp_rows:
                    out.append(entry)
                # else: drop; stays in Scheduler.running, retried next step.
            else:
                out.append(entry)
        return out
# ---- multi_group.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Graceful cross-resident park queue for the stable-VA residency swap.

Each routing key is one **group** FIFO — a stable-VA resident's key is
``(resident, "")``. The :class:`MultiGroupQueue` holds one FIFO per
key; the run loop drains the currently-active resident's scheduler,
then asks :meth:`pick_next_group` for the cheapest non-empty next
target. ``cheapest`` is decided by the swap class
:func:`arbi_serve.engine.params_hash.cheap_param_diff` reports between
``current_group``'s params and the candidate's params, with an
age-based promotion to prevent indefinite starvation of an
expensive-swap target.

Key design points:

  - The queue carries **opaque** request handles. It never touches the
    model / pool / page table — those live in the engine. This keeps
    the queue trivially testable and lets the engine evolve its own
    request shape without the queue moving in lockstep.
  - Per-key FIFO is preserved (no priority inversion within a
    resident). Cross-resident selection is the only place a "newer"
    request can be served before an "older" one — and only when the
    older request's resident is the most expensive swap target AND its
    age is under the anti-starvation threshold.
  - Time injection (``_now``) is plumbed through every method that
    reads the wall clock, so unit tests are deterministic.

The single-FIFO :class:`Scheduler` serves the active resident; this
queue holds the parked non-active residents.
"""

from __future__ import annotations

import time
from collections import OrderedDict, deque
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request


# A group key is ``(model_path, engine_params_hash)``. The engine's
# active group switches when the orchestrator runs a swap.
GroupKey = tuple[str, str]


class _GroupState:
    """Per-group FIFO + bookkeeping (age, total enqueued count).

    Internal — not exported. Kept as a tiny dataclass-ish struct so the
    queue can extend it without changing the public API.
    """

    __slots__ = ("queue", "oldest_submit_time", "total_enqueued")

    def __init__(self) -> None:
        self.queue: deque[Request] = deque()
        # The submit_time of the oldest still-queued request. Used by
        # ``oldest_age()`` and the anti-starvation gate. Set on first
        # ``add()`` to a previously-empty group; refreshed when the
        # head pops via ``drain_current()`` / ``remove()``.
        self.oldest_submit_time: float | None = None
        # Total ever-enqueued (monotonic). Drives the
        # arbi_serve.scheduler.multi_group.enqueued metric.
        self.total_enqueued: int = 0


class MultiGroupQueue:
    """Per-group FIFO + swap-cost-aware cross-group selector.

    The selector is independent of the swap orchestrator: it scores
    candidates against ``current_group`` using
    :func:`cheap_param_diff` on the cached engine-params dicts the
    engine registers via :meth:`register_group`. When no params dict
    is registered for a candidate yet (which happens when the engine
    has never seen this group), we fall back to "model swap" cost.
    """

    # Swap-class costs. The cheaper the number, the more attractive
    # the target. Mirrors the cost ladder in
    # :mod:`arbi_serve.engine.swap`.
    _SWAP_COST: dict[str, int] = {
        "none": 0,
        "sampling": 0,
        "recipe": 1,
        "backend": 2,
        "model": 3,
    }

    def __init__(self) -> None:
        # Insertion-ordered so iteration order is deterministic (helps
        # ties break the same way every step). Group is dropped when
        # its FIFO empties.
        self._groups: OrderedDict[GroupKey, _GroupState] = OrderedDict()
        # Cached engine-params dicts per group. Used by the selector
        # to score swap cost via cheap_param_diff. Registered by the
        # engine when it admits the first request for a new group.
        self._params_for_group: dict[GroupKey, dict[str, Any]] = {}
        # Aggregate metrics: per (prev, new) transitions count.
        self._swap_counts: dict[tuple[GroupKey, GroupKey], int] = {}

    # ── Registration ────────────────────────────────────────────────

    def register_group(
        self,
        group_key: GroupKey,
        engine_params: dict[str, Any],
    ) -> None:
        """Cache the engine-params dict for ``group_key``.

        Idempotent — re-registration overwrites. The cached dict is
        what :meth:`pick_next_group` passes to
        :func:`cheap_param_diff` when scoring candidates.
        """
        # Defensive copy so the caller mutating their dict can't
        # silently change our scoring.
        self._params_for_group[group_key] = dict(engine_params)

    def engine_params_for(self, group_key: GroupKey) -> dict[str, Any] | None:
        """Returned dict is the cached copy — do NOT mutate."""
        return self._params_for_group.get(group_key)

    # ── Enqueue / dequeue ───────────────────────────────────────────

    def add(
        self,
        req: Request,
        group_key: GroupKey,
        *,
        _now: float | None = None,
    ) -> None:
        """Enqueue ``req`` under ``group_key`` (FIFO within the group).

        Records the submit_time on the request if not already set,
        and tracks the oldest pending submit_time per group for the
        anti-starvation gate.
        """
        now = _now if _now is not None else time.time()
        state = self._groups.get(group_key)
        if state is None:
            state = _GroupState()
            self._groups[group_key] = state
        state.queue.append(req)
        state.total_enqueued += 1
        # Use the request's own submit_time if the engine already set
        # it (request enters the queue post-admission). Otherwise
        # stamp it now.
        if getattr(req, "submit_time", None) is None:
            req.submit_time = now
        if state.oldest_submit_time is None:
            state.oldest_submit_time = req.submit_time

    def pending_count(self) -> int:
        """Total requests parked across all groups (FIFO not yet admitted).

        These requests are NOT on the GPU — they sit pre-admission waiting
        for their group to become active. The critical-section drain
        (:func:`arbi_serve.engine.critical.has_inflight`) subtracts this from
        the live-request count so a run-loop-driven group swap does not wait
        on the very request that triggered it (the self-deadlock the multi-
        group cycling path otherwise hits).
        """
        return sum(len(s.queue) for s in self._groups.values())

    def drain_current(self, group_key: GroupKey) -> list[Request]:
        """Pop every queued request for ``group_key``. Drops the group
        from the keys list so the selector won't pick it again until
        a fresh ``add()``.

        Returns the list in FIFO order.
        """
        state = self._groups.get(group_key)
        if state is None:
            return []
        out = list(state.queue)
        state.queue.clear()
        state.oldest_submit_time = None
        # Drop empty group from the ordering so group_keys() / pick()
        # don't return it.
        del self._groups[group_key]
        return out

    def remove(self, *, request_id: int, group_key: GroupKey) -> bool:
        """Drop a request by id from its group. Returns True if found.

        Used by the engine when a request is cancelled before it gets
        scheduled.
        """
        state = self._groups.get(group_key)
        if state is None:
            return False
        for i, r in enumerate(state.queue):
            if getattr(r, "request_id", None) == request_id:
                del state.queue[i]
                if not state.queue:
                    state.oldest_submit_time = None
                    del self._groups[group_key]
                else:
                    # Refresh oldest_submit_time to the new head.
                    head = state.queue[0]
                    state.oldest_submit_time = getattr(head, "submit_time", None)
                return True
        return False

    # ── Selector ─────────────────────────────────────────────────────

    def pick_next_group(
        self,
        current_group: GroupKey | None,
        *,
        max_age_s: float = 30.0,
        sleep_threshold_s: float = 0.0,
        _now: float | None = None,
    ) -> GroupKey | None:
        """Pick the cheapest non-empty group to drain next.

        Algorithm:

          1. If no groups have pending requests → ``None``.
          2. Compute an age for each candidate — seconds since its
             oldest pending request was enqueued.
          3. Any candidate whose age exceeds ``max_age_s`` is "starving"
             and gets promoted to the front, regardless of swap cost.
             Tie-break starvation by oldest-age (most starved wins).
          4. Otherwise, score each candidate by swap cost vs
             ``current_group``'s params (via
             :func:`cheap_param_diff`). Lowest cost wins; ties broken
             by larger queue depth (drain the bigger backlog first),
             then by oldest age, then by group_key for determinism.

        ``current_group`` may be ``None`` (engine hasn't picked one
        yet — every candidate is "model swap" cost).

        ``sleep_threshold_s`` is accepted but not used by the selector.
        """
        del sleep_threshold_s  # reserved

        if not self._groups:
            return None

        now = _now if _now is not None else time.time()

        # Lazy import — avoid a circular if engine imports the queue.
        from arbi_serve.engine.params_hash import cheap_param_diff

        # If there's only one group AND it's the current one, return
        # it (engine keeps draining; "no-op swap").
        if len(self._groups) == 1:
            (only,) = self._groups.keys()
            return only

        # Build candidate list. Skip ``current_group`` only if there
        # are other non-empty groups to pick from — falling back to
        # "current is the only one" was handled above.
        candidates: list[GroupKey] = [g for g in self._groups]
        if current_group in candidates and len(candidates) > 1:
            candidates.remove(current_group)

        # Anti-starvation: any candidate with age > max_age_s wins
        # over a "cheap" candidate that hasn't aged out.
        cur_params: dict[str, Any] = {}
        if current_group is not None:
            cur_params = self._params_for_group.get(current_group, {})

        starving: list[tuple[float, GroupKey]] = []
        for gk in candidates:
            age = self._oldest_age_for(gk, now)
            if age >= max_age_s:
                starving.append((age, gk))

        if starving:
            # Most-starved first; ties by group_key for determinism.
            starving.sort(key=lambda x: (-x[0], x[1]))
            return starving[0][1]

        # Score by swap cost. The score derives a synthetic engine-
        # params dict from the group_key when no explicit params have
        # been registered, so the selector still classifies "different
        # model" vs "different params, same model" correctly.
        cur_synth = self._synth_params(current_group, cur_params)

        def score(gk: GroupKey) -> tuple[int, int, float, GroupKey]:
            """Rank a candidate group by (swap cost, -depth, -age, group_key) so cheaper/deeper/older wins."""
            new_params = self._params_for_group.get(gk, {})
            new_synth = self._synth_params(gk, new_params)
            klass = cheap_param_diff(cur_synth, new_synth)
            cost = self._SWAP_COST.get(klass, 3)
            depth = len(self._groups[gk].queue)
            age = self._oldest_age_for(gk, now)
            # Lower cost wins → smallest numeric.
            # Larger depth wins → negate.
            # Older wins → negate.
            # group_key tiebreaks deterministically.
            return (cost, -depth, -age, gk)

        return min(candidates, key=score)

    def _synth_params(
        self,
        group_key: GroupKey | None,
        explicit: dict[str, Any],
    ) -> dict[str, Any]:
        """Build the params dict the selector scores against.

        When the engine has registered explicit engine params for
        ``group_key`` (via :meth:`register_group`), use those — they
        carry K_BITS / V_BITS / recipe / etc, so the
        :func:`cheap_param_diff` classifier can distinguish recipe vs
        backend vs model swaps with full fidelity.

        When no explicit params are registered, fall back to a
        synthetic ``{"model": <model_path>, "_params_hash": <hash>}``
        dict — cheap_param_diff will at least correctly tag "different
        model" as the model-tier swap, and "different params_hash on
        the same model" as a backend swap (because _params_hash isn't
        a known engine key, but it's stable per group). To make the
        backend-tier classification work without a known key, we copy
        the params_hash into the ``attention_backend`` slot — a known
        backend-scope key.
        """
        if group_key is None:
            return dict(explicit)
        synth: dict[str, Any] = {"model": group_key[0]}
        if explicit:
            synth.update(explicit)
        # Only synthesize attention_backend if the explicit params
        # haven't already provided one (so registered params dominate).
        if "attention_backend" not in synth:
            synth["attention_backend"] = f"hash:{group_key[1]}"
        return synth

    # ── Metric / introspection helpers ──────────────────────────────

    def is_empty(self) -> bool:
        """Return True when no groups hold queued requests."""
        return not self._groups

    def group_keys(self) -> list[GroupKey]:
        """Insertion-ordered list of non-empty groups."""
        return list(self._groups.keys())

    def depth(self, group_key: GroupKey) -> int:
        """Number of queued requests in ``group_key`` (0 if absent)."""
        state = self._groups.get(group_key)
        return len(state.queue) if state is not None else 0

    def total_depth(self) -> int:
        """Total queued requests across all groups."""
        return sum(len(s.queue) for s in self._groups.values())

    def oldest_age(self, group_key: GroupKey, *, _now: float | None = None) -> float:
        """Seconds since the oldest queued request in ``group_key`` was submitted."""
        now = _now if _now is not None else time.time()
        return self._oldest_age_for(group_key, now)

    def _oldest_age_for(self, group_key: GroupKey, now: float) -> float:
        state = self._groups.get(group_key)
        if state is None or state.oldest_submit_time is None:
            return 0.0
        return max(0.0, now - state.oldest_submit_time)

    def note_swap(self, *, prev: GroupKey, new: GroupKey) -> None:
        """Record a swap transition for the metrics histogram."""
        key = (prev, new)
        self._swap_counts[key] = self._swap_counts.get(key, 0) + 1

    def swap_counts(self) -> dict[tuple[GroupKey, GroupKey], int]:
        """Returns a snapshot of per-pair transition counts. The dict
        is a copy — mutating it does not change the queue's state."""
        return dict(self._swap_counts)

    def snapshot(self, *, _now: float | None = None) -> dict[str, Any]:
        """JSON-friendly view of queue state — used by the
        ``GET /v1/admin/groups`` endpoint.
        """
        now = _now if _now is not None else time.time()
        groups: dict[str, dict[str, Any]] = {}
        for gk, state in self._groups.items():
            key = f"{gk[0]}::{gk[1]}"
            groups[key] = {
                "model_path": gk[0],
                "params_hash": gk[1],
                "depth": len(state.queue),
                "oldest_age_s": self._oldest_age_for(gk, now),
                "total_enqueued": state.total_enqueued,
            }
        return {
            "groups": groups,
            "total_depth": self.total_depth(),
        }


# Tiny helper so _GroupState plays nicely with depth() shape above.
def _depth(state: _GroupState) -> int:
    return len(state.queue)


_GroupState.depth = _depth  # type: ignore[attr-defined]
# ---- offload_manager.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Suspended-job KV offload (batch-backlog parking).

When a SUSPENDED batch decode job's paged-KV pages (and recurrent state if
hybrid) are snapshotted GPU→host→(disk) and its GPU pages freed, a huge
pooled backlog can wait with KV parked on disk instead of pinning VRAM.
On resume the pages are faulted back into a fresh allocation BEFORE the
job rejoins a slate.

The same save/restore core serves every other reason a request stands
down under PRESSURE: the allocation path's preemption parks its victim
through :meth:`OffloadManager.suspend_to_offload` rather than dropping its
work. There is one save path in the tree on purpose — a second copy of the
snapshot/restore contract is a fix that lands on one of them.

FREEZING AND PARKING ARE DIFFERENT VERBS, and freeing COMPUTE and freeing
MEMORY are different needs. A freeze (:meth:`freeze_in_place`) stands a
request down: it stops being scheduled and the next forward is built
without it, while its paged KV stays exactly where it is. A park
(:meth:`suspend_to_offload`) moves that KV off the GPU so the pages are
free, at the cost of a blocking D2H of the whole request on the engine
loop. Only a SHORT POOL needs the second, so only pool pressure and the
allocation path park; an arriving interactive request and an operator's
pause both want the engine to stop working on a row, and both freeze.

What a freeze does move, on a HYBRID model, is the per-request recurrent
row — a working slot the pool holds one of per concurrent sequence, not
storage that belongs to the request. Keeping it would take engine capacity
away to hold nothing (see :meth:`freeze_in_place`). That is a slab row, an
order below the paged KV a park carries.

A SUSPENDED request is therefore not necessarily a parked one. The two are
told apart by :meth:`is_resident_suspended`, which asks whether the KV
actually moved rather than carrying a second flag that could disagree with
the fact. There is ONE freeze and ONE park in the tree, and a trigger
chooses between them — never its own variant of either.

``OffloadManager`` owns the per-step suspend / resume policy and the
pool-pressure watermarks; the parked-job deques (``Scheduler.suspended``,
``Scheduler._dropped_suspended``) stay on the :class:`Scheduler` instance
the manager is constructed with, so the ``_add_inner`` self-heal and code
that reaches into ``Scheduler`` attributes directly keep working. The
manager reads/mutates those via the ``sched`` reference.

There is no store here. A parked request's KV is its own PREFIX — its full
pages committed into the radix tree and their digests pinned in the prefix
tier — so what a park needs is the page table's tier, and what the
scheduler carries is only whether this deployment parks at all
(``Scheduler.parking_enabled``). See
:mod:`arbi_serve.cache.radix_pagetable_offload`.
"""

from __future__ import annotations

import contextlib
import logging
import time
from typing import TYPE_CHECKING

from arbi_serve.cache import _metrics as cache_metrics
from arbi_serve.cache.radix_pagetable_offload import release_park_pins
from arbi_serve.engine.request import RequestState, n_generated, set_state
from arbi_serve.scheduler.preemption import (
    commit_written_pages,
    sequence_prefix,
    written_sequence,
)
from arbi_serve.scheduler.scheduler_admission import _max_reachable_context
from arbi_serve.scheduler.scheduler_counters import _discard_by_identity

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.scheduler import Scheduler

_LOG = logging.getLogger("arbi_serve.scheduler")


class OffloadManager:
    """Per-step suspend / resume policy for batch-backlog KV parking."""

    # Pool-pressure thresholds (fraction of the primary paged pool's
    # total pages). When ALLOCATABLE pages drop below
    # ``_offload_low_watermark``, suspend resident batch decode jobs
    # (oldest-admitted first) until they recover above
    # ``_offload_high_watermark`` — this lets a huge batch backlog keep
    # admitting fresh work (its KV parks on disk) without the pool ever
    # OOM-ing. They size a PARK; whether a parked row can come back is a
    # question about that row, not about a share of the pool (see
    # :meth:`_can_fault_back`). THIS policy suspends batch only;
    # interactive parks only where a human or the allocation path asks for
    # it by name (``pause_by_operator`` / ``Preemptor.preempt_for_space``).
    _offload_low_watermark: float = 0.08
    _offload_high_watermark: float = 0.20
    # Max PARKED jobs faulted back per step — that resume does an H2D (and
    # maybe a disk read); bounding it keeps per-step work small so a resume
    # never delays interactive. A frozen row's return costs no copy at all,
    # so this does not bound it (see :meth:`_resume_parked`).
    _offload_resume_per_step: int = 2

    def __init__(self, sched: Scheduler) -> None:
        self._sched = sched
        # Re-prefill recoveries performed in the CURRENT :meth:`_resume_parked`
        # pass. A recovery is host work proportional to the recovered context
        # (radix walk + savepoint match) and a TTL sweep can expire a whole
        # backlog at once, so it is bounded per step exactly as a fault back
        # is. See :meth:`_recover_lost_snapshot`.
        self._recoveries_in_pass = 0

    def _pool_total_pages(self) -> int:
        num_pages = getattr(self._sched.pool, "num_pages", None)
        if num_pages is not None:
            return int(num_pages)
        return 0

    def is_resident_suspended(self, req: Request) -> bool:
        """Is ``req`` stood down with its PAGED KV still on the GPU?

        A freeze stands a request down without moving its paged KV, so
        SUSPENDED means "not being scheduled", not "its pages are gone",
        and every caller that acts on a stood-down row has to know which
        it is holding. The PAGE TABLE answers it, because the page table
        is what a park changes: parking detaches the request and frees its
        pages, and nothing else in the tree does. Asked of the allocator
        that owns the fact, this needs no second flag to drift from it.

        Not the snapshot store: a freeze on a HYBRID model stages an entry
        there too (the recurrent row it had to release — see
        :meth:`freeze_in_place`), so "has a snapshot" stopped meaning "was
        parked" the moment the two mechanisms split.
        """
        if req.state != RequestState.SUSPENDED:
            return False
        try:
            return self._sched.page_table.length(req.request_id) > 0
        except KeyError:
            return False

    def freeze_in_place(self, req: Request) -> bool:
        """Stand ``req`` down where it is, keeping its paged KV. True when
        it stood down.

        The row leaves ``Scheduler.running`` for ``Scheduler.suspended`` in
        SUSPENDED state, so the next slate is built without it and the
        engine spends no compute on it; its PAGES stay mapped and its KV
        stays on the card. That half is what pool pressure governs, and a
        stand-down must not pay for it: on a pure-attention model a freeze
        is bookkeeping alone, O(1) and no copy.

        THE RECURRENT ROW IS NOT PAGES AND MUST GO BACK. On a hybrid the
        per-request GDN/Mamba/ShortConv row is a WORKING SLOT the engine
        holds while it steps a request, not storage that belongs to it,
        and the pool has one per concurrent sequence (``max_num_seqs``) —
        a far scarcer resource than a KV page. A row held by a request
        that produces nothing is capacity removed from the engine: stand
        down every batch row on interactive arrival without releasing
        theirs and the arriving interactive request is shed for
        ``recurrent_rows_exhausted``, which turns "interactive needs
        compute" into "interactive cannot be admitted at all". So a freeze
        syncs that row out and frees it, and :meth:`unfreeze` re-acquires
        one and restores it. It costs a slab-row D2H, an order below a
        park (which pays that AND the whole paged-KV transfer).

        The snapshot lives in the suspended store, which is the tier that
        already knows how to hold one and is already dropped by every
        terminal path — so a hybrid freeze needs a store and declines
        without one. It does NOT consult ``kv_offload_recurrent``: that
        flag governs whether a PARK may take recurrent state along, and a
        freeze has no choice about the row.

        Only a DECODING row: a mid-prefill row has no point to be stood
        down at, the same refusal the park core states.
        """
        if req.state != RequestState.DECODING:
            return False
        sched = self._sched
        if sched._has_recurrent_state() and not self._release_recurrent_row(req):
            return False
        sched._running_remove(req)
        set_state(req, RequestState.SUSPENDED)
        sched.suspended.append(req)
        # A view into a staging buffer the rows that run meanwhile overwrite; the
        # unfrozen row feeds its last host token instead, as a parked one does.
        req.last_sampled_gpu = None
        if sched._metrics is not None:
            sched._metrics.decode_dec()
        # Counted apart from a park: both end with the row in SUSPENDED, and an
        # operator reading one number for the pair cannot tell a stand-down
        # that moved nothing from an offload that moved a whole request's KV.
        cache_metrics.counter_inc(
            "arbi_serve.suspended.freeze_total",
            labels={"service_tier": "flex" if req.is_flex else "default"},
        )
        _LOG.debug("freeze req=%s (paged KV left in place)", req.request_id)
        return True

    def unfreeze(self, req: Request) -> bool:
        """Return a frozen ``req`` to the decoding set.

        The inverse bookkeeping — and, on a hybrid, the re-acquisition of
        the working slot the freeze gave back. Nothing about the paged KV
        is asked of the pool, because the row never gave it up.

        Declines (leaving ``req`` frozen for a later step) when no
        recurrent row is free right now — the same answer a fault-back
        gives an exhausted pool, and for the same reason: an allocation
        that RAISES on the engine loop is not an option. Declines a row
        that is not frozen at all; a parked one goes back through
        :meth:`resume_from_offload`.
        """
        sched = self._sched
        if not self.is_resident_suspended(req):
            return False
        if sched._has_recurrent_state() and not self._restore_recurrent_row(req):
            return False
        _discard_by_identity(sched.suspended, req)
        set_state(req, RequestState.DECODING)
        sched._running_add(req)
        if sched._metrics is not None:
            sched._metrics.decode_inc()
        cache_metrics.counter_inc(
            "arbi_serve.suspended.unfreeze_total",
            labels={"service_tier": "flex" if req.is_flex else "default"},
        )
        _LOG.debug("unfreeze req=%s (paged KV never left the GPU)", req.request_id)
        return True

    def _release_recurrent_row(self, req: Request) -> bool:
        """Sync ``req``'s recurrent row to host and return it to the pool.

        The freeze half of the working-slot contract. Blocking D2H for the
        same reason the park's gather is (the forward runs on another stream
        and the row is handed to the next admission the moment it is freed),
        then staged as a TAIL ENTRY at this request's own tail digest.

        A freeze moves no paged KV, so it has no chain — just the one entry at
        the position between two page boundaries, which is where a recurrent
        row sits and where no savepoint is ever written. It is pinned, because
        a frozen row is as live as a parked one. A later park of the same
        frozen row addresses the SAME digest (a frozen request produces no
        token, so its tail cannot have moved) and adds the KV half to it,
        which is why the park reads its recurrent state back from here rather
        than re-taking it off a slot another request owns by then.
        """
        sched = self._sched
        store = self._park_store()
        snap_fn = getattr(sched.pool, "snapshot_recurrent_row", None)
        if store is None or snap_fn is None:
            return False
        chain = self._plan_tail_only(req)
        if chain is None:
            return False
        tensors = snap_fn(req.request_id, async_copy=False) or {}
        if not tensors:
            return False
        # A row freezing again after an unfreeze must not take a second
        # reference only one release will come back for.
        release_park_pins(sched.page_table, getattr(req, "parked_chain", None))
        req.parked_chain = None
        if not store.pin(chain.tail_key, chain.entry_nbytes):
            # Nowhere to hold the state, so the slot stays where it is. A
            # freeze that hands the row back without keeping its state is a
            # request that cannot decode when it comes back.
            return False
        from arbi_serve.cache.prefix_tier_store import PrefixTierEntry

        store.stage(
            chain.tail_key,
            PrefixTierEntry(
                page_tensors={},
                tenant_id=chain.tenant_id,
                token_ids=tuple(chain.tail_tokens),
                num_tokens=len(chain.tail_tokens),
                tier_eligible_tokens=len(chain.tail_tokens),
                recurrent_tensors=tensors,
            ),
        )
        req.parked_chain = chain
        free_recurrent = getattr(sched.pool, "free_recurrent_state", None)
        if free_recurrent is not None:
            free_recurrent(req.request_id)
        return True

    def _plan_tail_only(self, req: Request):
        """The tail digest for a request whose paged KV is staying put."""
        plan_park = getattr(self._sched.page_table, "plan_park", None)
        if plan_park is None:
            return None
        return plan_park(req.request_id, written_sequence(self._sched.page_table, req))

    def _restore_recurrent_row(self, req: Request) -> bool:
        """Take a recurrent row back for ``req`` and queue its state into it.

        The unfreeze half. Asks for a free row BEFORE allocating, because
        ``alloc_recurrent_state`` raises on an exhausted pool and a raise
        here lands on the engine loop; a refusal leaves the request frozen
        and the next step asks again.
        """
        sched = self._sched
        entry = self._frozen_tail_entry(req)
        if entry is None or not entry.recurrent_tensors:
            # The state the freeze synced out is gone (evicted, or past the
            # disk TTL). The row cannot decode correctly against state it
            # does not have, and that is the parked path's own case — so it
            # answers it, rather than a second copy of the drop here.
            self.resume_from_offload(req)
            return False
        rec_free_fn = getattr(sched.pool, "recurrent_free_rows", None)
        rec_free = rec_free_fn() if rec_free_fn is not None else None
        if rec_free is not None and rec_free < 1:
            return False
        alloc_recurrent = getattr(sched.pool, "alloc_recurrent_state", None)
        queue_resume = getattr(sched.pool, "queue_savepoint_resume", None)
        if alloc_recurrent is not None:
            alloc_recurrent(req.request_id)
        if queue_resume is not None:
            queue_resume(req.request_id, entry.recurrent_tensors)
        # The row is live on the card again, so the claim goes. The entry
        # stays in the tier as ordinary cache — it is a real recurrent state
        # for a real prefix, and nothing about unfreezing makes it wrong.
        release_park_pins(sched.page_table, req.parked_chain)
        req.parked_chain = None
        return True

    def manage(self) -> None:
        """Per-step stand-down / resume policy. Interactive is the priority.

        WHICH MECHANISM depends on what is actually short:
          * ANY interactive request present → flex DECODE rows are left
            running: one token per row is cheap, so they ride along in the
            interactive request's forwards. What yields to interactive is
            flex PREFILL, which the slate gate skips (see
            ``compute_step_budget``). Pressure while interactive is present is
            met on demand by the allocation path, not parked here.
          * pool pressure → PARK oldest-admitted resident batch
            decode jobs (KV offloaded GPU→host→disk, pages freed) until
            allocatable pages recover above the high watermark. Pages are
            what is short here, and only moving bytes can produce them.
        Resume: :meth:`_resume_parked`, on BOTH branches — a stood-down
        request is not only a batch backlog any more (preemption parks
        whatever victim it picked, interactive included), and a policy that
        resumes only at idle would turn a preempted interactive request's
        re-prefill into an open-ended stall, which is the worse half of the
        trade this path exists to avoid.
        """
        sched = self._sched
        pool = sched.pool
        # Before anything else: a park whose bound has run out stops holding
        # tier retention. Cheap (a walk of the parked deque) and first, so a
        # park attempted this step can claim what an expired one just gave up.
        self._expire_parks()
        # The holding queue counts: an interactive request deferred for a row is the demand.
        interactive_present = sched._interactive_present()
        total = self._pool_total_pages()

        if interactive_present:
            # Flex decode rows are NOT stood down for an interactive arrival: one token per row is
            # cheap, so they ride along in the interactive request's forwards (the slate gate
            # skips only flex PREFILL). Nor are they parked here: a park is a blocking D2H per row
            # on the engine loop the interactive request is waiting on. Pressure is met where it
            # bites instead, one victim at a time (``Preemptor.preempt_for_space`` for pages,
            # ``Scheduler._yield_row_to_interactive`` for a recurrent row). What is still stood
            # down stays so, and only interactive rows of our own parking come back here;
            # ``allow_batch=False`` keeps a flex row from re-taking what the arrival just obtained.
            if sched.suspended:
                self._resume_parked(allow_batch=False)
            return

        # No interactive present. First relieve pool pressure by parking
        # the oldest resident batch decode jobs. "Pressure" is the MIN
        # headroom across the paged-KV pool AND (on hybrid models) the
        # per-request recurrent slab-row pool — a GDN/Mamba backlog can
        # exhaust recurrent rows while paged-KV pages stay plentiful, so
        # we must offload (which frees both) on either pressure source.
        rec_free_fn = getattr(pool, "recurrent_free_rows", None)
        rec_total_fn = getattr(pool, "recurrent_total_rows", None)
        rec_total = rec_total_fn() if rec_total_fn is not None else None

        # Recurrent watermarks use a 1-row floor: small recurrent pools
        # (max_num_seqs == max_batch, e.g. 8) would round an 8%/20%
        # fraction to 0 and the pressure check would never fire. The
        # floor makes "1 row left" count as pressure and "≥1 row free"
        # the relief target on tiny pools.
        rec_low = max(1, int(rec_total * self._offload_low_watermark)) if rec_total else 0
        rec_high = max(1, int(rec_total * self._offload_high_watermark)) if rec_total else 0

        # Paged headroom is the pages a fresh allocation can OBTAIN, which
        # is what :meth:`_can_fault_back` and admission both gate on — one
        # notion of capacity for the whole subsystem. The pool's free LIST
        # is a different, smaller number on a radix table: the refcount-0
        # prefix-cache pages the evictor reclaims on demand are not on it.
        # Sized off the free list, "pressure" is a warm cache, and the
        # policy parks rows to relieve a shortage that does not exist and
        # that parking them cannot relieve.
        available_fn = getattr(sched.page_table, "available_pages", None)

        def _allocatable() -> int:
            if available_fn is not None:
                return int(available_fn())
            return pool.free_pages(sched.primary_paged_kind)

        def _under_pressure() -> bool:
            f = _allocatable()
            if total > 0 and f < int(total * self._offload_low_watermark):
                return True
            if rec_total and rec_free_fn is not None:
                rf = rec_free_fn()
                if rf is not None and rf <= rec_low:
                    return True
            return False

        def _relieved() -> bool:
            f = _allocatable()
            paged_ok = total <= 0 or f >= int(total * self._offload_high_watermark)
            rec_ok = True
            if rec_total and rec_free_fn is not None:
                rf = rec_free_fn()
                rec_ok = rf is None or rf >= rec_high
            return paged_ok and rec_ok

        if _under_pressure():
            # Oldest-admitted first (leftmost of the deque).
            for req in list(sched.running):
                if _relieved():
                    break
                if (
                    req.is_flex
                    and req.state == RequestState.DECODING
                    and not self.suspend_to_offload(req)
                ):
                    # Defensive: no progress — stop to avoid a spin.
                    break

        # Resume parked jobs. A BATCH job comes back only when no fresh
        # batch work is queued: gating the batch backlog on an empty batch
        # waiting queue is its anti-thrash invariant — if waiting batch jobs
        # are competing for the just-freed capacity, resuming a parked job
        # only to re-park it next step (when the waiting job takes the row)
        # churns the GPU↔host copy for no progress. The parked jobs wait on
        # disk/host until the queue clears, which is exactly the "pool the
        # backlog, make a few progress" model. Capacity is NOT asked here:
        # the pressure watermarks above size a park, and whether a specific
        # parked row can come back is a question about that row's pages,
        # asked per row in :meth:`_can_fault_back`. Guarded on ``suspended``
        # at BOTH call sites rather than inside: with nothing parked — every
        # step of an ordinary serving run — this costs one truth test and
        # not the waiting scan that sizes the batch gate.
        if sched.suspended:
            any_batch_waiting = any(r.is_flex for r in sched.waiting)
            self._resume_parked(allow_batch=not any_batch_waiting)

    def _can_fault_back(self, req: Request) -> bool:
        """Can the pool seat THIS parked row's state again, right now?

        The question a resume means, put to the allocator that answers it
        for real: ``page_table.can_allocate`` is the predicate admission
        uses, so a resume and an admission compete over one notion of
        capacity. On a radix table that notion counts the refcount-0
        prefix-cache pages the evictor reclaims on the next allocation —
        a pool whose pages are held by reclaimable cache has room, and a
        resume asked about the pool's FREE LIST instead would refuse
        forever under a healthy prefix cache while the rows it refuses are
        the only ones that could free anything.

        A hybrid row also needs its recurrent slab row back, and that
        allocation RAISES on an exhausted pool rather than declining — so
        it is asked here, where a refusal is a row that waits one more
        step instead of an exception on the engine loop.

        O(1) per parked row considered: a free-list length plus the radix
        table's maintained evictable counter, and one walk of the pool's
        handful of state views. ``total_length`` is the row's whole KV
        extent, which is what :meth:`resume_from_offload` re-allocates.
        """
        sched = self._sched
        can_allocate = getattr(sched.page_table, "can_allocate", None)
        if can_allocate is not None and not can_allocate(req.total_length):
            return False
        if sched._has_recurrent_state():
            rec_free_fn = getattr(sched.pool, "recurrent_free_rows", None)
            rec_free = rec_free_fn() if rec_free_fn is not None else None
            if rec_free is not None and rec_free < 1:
                return False
        return True

    def _expire_parks(self) -> int:
        """Give back the claim of every park past the bound. Returns the count.

        THE PARK BOUND IS THE SCHEDULER'S CLOCK. It is a property of a park —
        a live holder saying it will come back — and not of a cache entry, so
        it is measured here, where the parked request is, rather than folded
        into the tier's TTL, which answers a different question about the same
        map.

        Expiring a park does NOT destroy anything, and it does not give up on
        the request either. The pins drop and the entries rejoin the cache as
        ordinary prefix pages; the request keeps its chain and its place in
        ``suspended``, and its next resume runs exactly as before — it just has
        no claim any more, so it succeeds only while the cache happens to still
        hold what it needs, and takes the fault-miss path when it does not. The
        bound exists to stop a forgotten park holding retention forever, not to
        kill requests on a timer.
        """
        bound = float(getattr(self._sched.cache_cfg, "kv_offload_ttl_seconds", 0.0) or 0.0)
        if bound <= 0:
            return 0
        store = self._park_store()
        if store is None:
            return 0
        now = time.monotonic()
        expired = 0
        for req in self._sched.suspended:
            chain = getattr(req, "parked_chain", None)
            if chain is None or now - chain.parked_at <= bound:
                continue
            if not any(store.pinned(k) for k in chain.keys):
                # Already expired (or destroyed). "Is anything still pinned?"
                # is the expiry state itself rather than a second flag beside
                # it, so the two cannot disagree.
                continue
            release_park_pins(self._sched.page_table, chain)
            expired += 1
        if expired:
            cache_metrics.counter_inc(
                "arbi_serve.suspended.park_expired_total", labels={}, value=expired
            )
        return expired

    def _resume_parked(self, *, allow_batch: bool) -> None:
        """Return stood-down requests, interactive first. A FAULT-BACK is
        bounded per step; an unfreeze is free and is not.

        ORDER is the whole priority policy here: a parked interactive
        request is served before any parked batch job, and the sort is
        stable so each class keeps its parked-order (oldest first) inside
        it. Nothing else is needed to express "interactive first".

        No row passes a HEADROOM gate — a share of the pool a row does not
        need is not a reason to strand it, and the row this path exists to
        save is exactly the one a headroom gate strands. The gate is
        :meth:`_can_fault_back`, which asks only whether this row's own
        pages (and its recurrent row) are obtainable; the allocation in
        :meth:`resume_from_offload` is the arbiter behind it and leaves the
        job parked when it disagrees. That is the thrash guard the batch
        branch gets from ``any_batch_waiting`` without a queue condition
        that can go on being true forever: a cycle here needs the pool to
        hand the whole row back first, and costs a copy the size of what it
        re-parks.
        """
        sched = self._sched
        resumed = 0
        self._recoveries_in_pass = 0
        # ``False < True``: not-batch sorts first, stably.
        for req in sorted(sched.suspended, key=lambda r: r.is_flex):
            if req.is_flex and not allow_batch:
                continue
            # An operator's pause outranks every policy here. The policy
            # parks on its own judgement and is entitled to unpark on the
            # same judgement, but it did not make this decision and cannot
            # revisit it: a pause that the scheduler could undo a step
            # later is not a pause. Only an operator's resume clears it.
            if getattr(req, "operator_paused", False):
                continue
            # A FROZEN row is :meth:`unfreeze`'s business whatever it
            # decides, and neither gate below is its question: there is no
            # paged allocation for the pool to refuse, and the per-step cap
            # bounds an H2D fault-back, which this is not. Capping it would
            # strand a frozen backlog two rows per step behind an
            # interactive stream that costs it nothing.
            if self.is_resident_suspended(req):
                self.unfreeze(req)
                continue
            if resumed >= self._offload_resume_per_step:
                continue
            # A row the pool cannot seat yet is skipped, not a break: the
            # parked rows have different page counts and a small one fits
            # where the one ahead of it does not.
            if not self._can_fault_back(req):
                continue
            if self.resume_from_offload(req):
                resumed += 1

    def drain_dropped_suspended(self) -> list[Request]:
        """Return + clear jobs whose resume failed irrecoverably.

        The engine run loop calls this each step and runs the terminal
        path (``finished`` + on_finished) for each — they already carry a
        ``finish_reason``. Empty list in the common case.
        """
        sched = self._sched
        if not sched._dropped_suspended:
            return []
        out = sched._dropped_suspended
        sched._dropped_suspended = []
        return out

    def _park_store(self):
        """The tier a park pins in, or ``None``.

        Reached through the page table rather than off the scheduler: the
        store belongs to the radix table, and parking IS prefix tiering now —
        a boot with no radix table or no tier has nowhere to park, which is
        the same sentence as "there is no store".
        """
        return getattr(self._sched.page_table, "_tier_store", None)

    def _refuse_park(self, req: Request, reason: str) -> bool:
        """Count a refused park BY NAME and return False.

        An operator whose batch jobs mysteriously never park has to be able to
        read WHY off a counter rather than infer it from an absence. Every
        return-False in :meth:`suspend_to_offload` comes through here.
        """
        cache_metrics.counter_inc(
            "arbi_serve.suspended.park_refused_total", labels={"reason": reason}
        )
        _LOG.debug("park refused req=%s: %s", req.request_id, reason)
        return False

    def _park_recurrent_tensors(self, req: Request, *, frozen: bool) -> dict | None:
        """The recurrent row that must travel with ``req``'s tail, or ``None``.

        ``None`` means this request cannot be parked whole. Parking the paged
        KV and leaving the recurrent state behind is not a cheaper partial
        save, it is the wrong answer: the resumed request decodes against zero
        GDN/Mamba state, which is the corruption a prefix-cache hit without a
        savepoint produces. An empty dict is not ``None`` — a pure-attention
        model has no recurrent state and parks fine without one.

        A FROZEN row's state is already on host and its working slot already
        back in the pool, so snapshotting the slot again would read whatever
        request owns it now. The freeze's own tail entry IS the state, and it
        is addressed by the same digest this park is about to use, so the park
        reads it back rather than re-taking it.
        """
        sched = self._sched
        if not sched._has_recurrent_state():
            return {}
        if frozen:
            staged = self._frozen_tail_entry(req)
            if staged is None or not staged.recurrent_tensors:
                return None
            return dict(staged.recurrent_tensors)
        snap_fn = getattr(sched.pool, "snapshot_recurrent_row", None)
        if snap_fn is None:
            return {}
        # Blocking D2H: the forward runs on a separate worker-thread stream
        # that an async copy issued here is not ordered against, and the park
        # hands the row back the moment this returns.
        return snap_fn(req.request_id, async_copy=False) or {}

    def _frozen_tail_entry(self, req: Request):
        """The tail entry a freeze staged for ``req``, or ``None``."""
        store = self._park_store()
        chain = getattr(req, "parked_chain", None)
        if store is None or chain is None:
            return None
        return store.fault_in(chain.tail_key)

    def suspend_to_offload(self, req: Request) -> bool:
        """Park ``req``: pin its prefix in the tier, give its pages back.

        A park does not copy this request's KV anywhere. Its full pages are
        committed into the radix tree, where they already were in every sense
        that matters, and their digests are PINNED in the prefix tier — the
        promise that a demote of any of them will be kept rather than gated or
        evicted. Only the partial last page, which is no page of any tree, is
        staged; see :mod:`arbi_serve.cache.radix_pagetable_offload` for why it
        is stored rather than recomputed.

        The pages are then released to the allocator, which is what "free the
        pages" has to mean for the callers that measure the result:
        ``available_pages`` counts a refcount-0 tree page as available and
        ``_alloc_pages_with_eviction`` reclaims it on demand. The D2H is paid
        one page at a time by the evictor, for the pages pressure actually
        takes, and never at all for a page another live request is sharing.

        Offloadable: a DECODING job, or one an operator FROZE with its KV
        still resident. A mid-prefill job is not (no stable resume contract).
        PRIORITY is not a gate: preemption and an operator's pause both hand
        interactive rows here, and refusing them would leave the caller no way
        to free the pages except by throwing the work away.

        Runs on the engine loop thread. Every refusal is counted by name
        (:meth:`_refuse_park`). Returns True on park.
        """
        sched = self._sched
        store = self._park_store()
        # A DECODING row parks out of the running set; a row an operator FROZE
        # is already stood down and only its KV still has to move, so the same
        # core serves both and the queue bookkeeping at the end is what
        # differs. Read once: nothing below changes the answer.
        frozen = self.is_resident_suspended(req)
        if not (frozen or req.state == RequestState.DECODING):
            return self._refuse_park(req, "not_parkable_state")
        if store is None:
            return self._refuse_park(req, "no_prefix_tier")
        if not bool(getattr(req.sampling, "cache_enabled", True)):
            # The per-request prefix-cache opt-out is a privacy promise: this
            # request declined to read or write the shared cache. Parking it
            # means writing its KV into a shared, content-addressed tier,
            # which is the thing it declined. Pressure falls back to
            # preemption, which re-prefills.
            return self._refuse_park(req, "cache_disabled")
        if sched._has_recurrent_state() and not sched._offload_recurrent and not frozen:
            return self._refuse_park(req, "recurrent_offload_off")
        recurrent = self._park_recurrent_tensors(req, frozen=frozen)
        if recurrent is None:
            return self._refuse_park(req, "recurrent_state_lost")

        # The generated tokens' pages are private and unmatchable until this
        # runs — and they are exactly what the park is about to key on.
        seq = commit_written_pages(sched.page_table, req, unpaired=True)
        plan_park = getattr(sched.page_table, "plan_park", None)
        chain = plan_park(req.request_id, seq) if plan_park is not None else None
        if chain is None or not chain.keys:
            return self._refuse_park(req, "nothing_to_park")
        # A FROZEN row already holds a pin on this same tail digest (its
        # freeze staged the recurrent half there). Release it before pinning
        # the chain, or the park takes a second reference to an entry only one
        # release will ever come back for.
        release_park_pins(sched.page_table, getattr(req, "parked_chain", None))
        req.parked_chain = None
        if not self._pin_chain(store, chain):
            # The tier cannot promise to keep this much. Refused HERE, while
            # the request is still whole: a park that discovers it cannot be
            # kept after it has given up its pages can be neither undone nor
            # completed.
            return self._refuse_park(req, "pin_budget")
        if not sched.page_table.park_request(req.request_id, chain, recurrent_tensors=recurrent):
            release_park_pins(sched.page_table, chain)
            return self._refuse_park(req, "tail_not_staged")
        req.parked_chain = chain

        free_recurrent = getattr(sched.pool, "free_recurrent_state", None)
        if free_recurrent is not None:
            free_recurrent(req.request_id)
        req.state_handles.pop(sched.primary_paged_kind, None)
        # Drop the GPU sample ref; resume re-establishes it from CPU.
        req.last_sampled_gpu = None
        # Drop any parked optimistic advance: resume re-derives total_length
        # from the committed output_token_ids, and the pages a parked verify's
        # draft slots lived in went back just above.
        req.drop_parked_advances()
        if not frozen:
            # A frozen row already left ``running`` for ``suspended`` and was
            # already counted out of decode when the operator paused it — this
            # park moved its KV, not its place in the scheduler.
            sched._running_remove(req)
            set_state(req, RequestState.SUSPENDED)
            sched.suspended.append(req)
            if sched._metrics is not None:
                sched._metrics.decode_dec()
        # The priority label is READ OFF THE REQUEST, not assumed: since
        # preemption and operator pause park interactive rows too, a
        # hard-coded "background" would report an interactive park as batch and
        # make the one series that answers "who is parked" untrue.
        cache_metrics.counter_inc(
            "arbi_serve.suspended.offload_total",
            labels={"service_tier": "flex" if req.is_flex else "default"},
        )
        _LOG.debug(
            "suspend→offload req=%s pages=%d tail=%s",
            req.request_id,
            len(chain.page_keys),
            "yes" if chain.tail_key else "none",
        )
        return True

    def _pin_chain(self, store, chain) -> bool:
        """Pin every digest in ``chain``, or none of them.

        All-or-nothing because a partly pinned chain is a park whose resume
        stops at the first unpinned page — which is a re-prefill of everything
        past it, bought at the price of the retention that was pinned. The
        caller is better off not parking.
        """
        taken: list[str] = []
        for key in chain.keys:
            if not store.pin(key, chain.entry_nbytes):
                for done in taken:
                    store.unpin(done)
                return False
            taken.append(key)
        return True

    # ── fault miss: rebuild the KV instead of ending the request ─────

    def _recover_lost_snapshot(self, req: Request, *, cause: str | None = None) -> bool:
        """A parked ``req`` whose snapshot is gone: re-prefill it, or drop it.

        RESUMING AGAINST MISSING KV IS NEVER AN OPTION — half a request's
        state produces output nothing can vouch for, and that refusal is
        what the fault-miss branch has always been about. What is NOT
        forced is ending the request: the token sequence whose KV was lost
        is still on the :class:`Request` (its fed stream — prompt, output
        and any injected context, in the order the model saw them), and a
        full prefill over that sequence rebuilds the paged KV and, on a
        hybrid model, the recurrent state with it. So a 24h TTL expiry or
        a disk-budget eviction costs the job a re-prefill instead of its
        life, and the client gets the answer it asked for instead of a
        truncated one.

        The rebuilt request goes back through ORDINARY ADMISSION
        (:meth:`Scheduler.add`): it queues behind interactive work, takes
        the prefix match, the recurrent row and the admission gates every
        fresh request takes, and re-prefills in chunks under the same
        per-step budget. A re-prefill is far more expensive than a fault
        back, so it must not get a shortcut a fault back does not have.

        Returns False always — the request leaves ``suspended`` for
        ``waiting`` (recovered) or for the dropped-job terminal path, and
        neither is the "rejoined the running set" that
        :meth:`resume_from_offload` reports.
        """
        # A recovery walks the radix tree over the whole rebuilt sequence and
        # runs the savepoint match, host work proportional to the context —
        # and a TTL sweep expires a WHOLE backlog at once. Bounded by the same
        # per-step figure a fault back is, so a mass expiry cannot turn one
        # ``schedule()`` call into a stall that interactive traffic waits
        # behind. A row past the bound stays parked and is offered again next
        # step; it is not dropped for arriving late — and it is not counted
        # either, or one lost snapshot would read as a miss per step until
        # the pass had room for it.
        if self._recoveries_in_pass >= self._offload_resume_per_step:
            return False
        cache_metrics.counter_inc("arbi_serve.suspended.fault_miss_total", labels={})
        refusal = self._reprefill_refusal(req)
        if refusal is not None:
            outcome, finish_reason = refusal
            # ``cause`` names what took the KV, and it only reaches the client
            # on the paths where the request actually ends. A recovery that
            # succeeds says nothing about it — nothing was lost that the
            # re-prefill did not put back. The bare ``offload_lost`` is the one
            # a specific cause replaces; a refusal that named ITSELF (media, a
            # length limit) already says the more useful thing.
            if cause is not None and finish_reason == "offload_lost":
                finish_reason = cause
            return self._drop_lost(req, outcome, finish_reason)
        self._recoveries_in_pass += 1
        return self._readmit_for_reprefill(req)

    def _reprefill_refusal(self, req: Request) -> tuple[str, str] | None:
        """``(metric outcome, finish_reason)`` when ``req`` must NOT re-prefill.

        ``None`` when it may. Four refusals, and each one names itself
        rather than arriving as a bare ``offload_lost``, because "we are
        re-prefilling a lot" and "we are losing jobs" are different
        operational facts and an operator has to be able to tell them
        apart.

        MEDIA. ``prompt_token_ids`` carries expanded placeholder positions
        for a multimodal request, and the encoder caches keyed to them
        (``_media_embeds`` / ``_mrope_full``) are built once, against the
        prompt as it was. A rebuilt sequence is longer than that grid, so
        recovering one would either mis-scatter the media embeddings or
        feed an M-RoPE row positions for a prompt it no longer has. The
        request is dropped by name instead of reconstructed wrongly.

        BUDGET. The recovery is bounded per request — see
        :meth:`_reprefill_budget`.

        LENGTH. ``max_context`` and ``max_tokens`` apply to the rebuilt
        sequence exactly as to a fresh one. A sequence that has already
        reached either did not lose an answer to the snapshot going
        missing; it finishes with the reason it actually hit.
        """
        if req.multimodal is not None or req.cache_key_ids is not None:
            return ("media", "offload_lost_media")
        seq_len = req.fed_length
        if seq_len <= 0:
            return ("dropped", "offload_lost")
        max_context = self._max_context()
        if max_context and seq_len >= max_context:
            return ("length", "context")
        max_tokens = getattr(req.sampling, "max_tokens", None)
        if max_tokens is not None and n_generated(req) >= int(max_tokens):
            return ("length", "length")
        if req.offload_reprefill_tokens + seq_len > self._reprefill_budget(req):
            return ("budget", "offload_lost_recovery_budget")
        return None

    def _reprefill_budget(self, req: Request) -> int:
        """Tokens ``req`` may spend, in total, re-prefilling after a fault miss.

        IT MUST TERMINATE. A job whose snapshot keeps disappearing under
        the pressure that evicted it re-prefills its whole context each
        time it comes back, which is a load amplifier: the slow
        degradation that lost the first snapshot is exactly the condition
        that loses the next one, and paying a full context per round is
        how that becomes an outage.

        The bound is the request's OWN REACH — its rebuilt prompt plus its
        remaining output budget, capped by ``max_context`` — so it is read
        off config the engine already resolved rather than invented as a
        new knob. That makes the worst case uniform across request shapes:
        every request may waste at most one full context of prefill on
        recovery, whether as one recovery of a long sequence or many of a
        short one, so the amplification a fleet of them can produce is
        bounded by its own admitted work. The reach is INVARIANT under a
        recovery (:func:`_max_reachable_context` charges the folded tokens
        against the output budget that grew the prompt), so the bound
        cannot inflate itself by being re-read after each round.
        """
        max_context = self._max_context()
        reach = _max_reachable_context(req)
        if reach is None:
            return max_context or 0
        return min(int(reach), max_context) if max_context else int(reach)

    def _max_context(self) -> int:
        """The engine's resolved per-request context limit, 0 when unknown.

        ``CacheConfig.max_context`` is ``"auto"`` until the boot resolves
        it; a scheduler built without that resolution has no limit to
        enforce here and says so rather than guessing one.
        """
        try:
            return int(getattr(self._sched.cache_cfg, "max_context", 0) or 0)
        except (TypeError, ValueError):
            return 0

    def _drop_lost(self, req: Request, outcome: str, finish_reason: str) -> bool:
        """End ``req``: its KV is gone and it cannot be rebuilt. Returns False."""
        sched = self._sched
        _discard_by_identity(sched.suspended, req)
        cache_metrics.counter_inc(
            "arbi_serve.suspended.fault_recovery_total",
            labels={"outcome": outcome},
        )
        req.finish_reason = req.finish_reason or finish_reason
        sched._dropped_suspended.append(req)
        _LOG.debug("offload fault miss req=%s → drop (%s)", req.request_id, outcome)
        return False

    def _readmit_for_reprefill(self, req: Request) -> bool:
        """Rewrite ``req`` as a fresh prefill of its fed stream and re-admit it.

        The victim rewrite :meth:`Preemptor.preempt_for_space` performs,
        reached from the other direction: there the pages are thrown away
        to make room, here they are already gone. The sequence is the FED
        STREAM (:meth:`Request.fed_token_ids`) rather than
        ``prompt + output``, because a request that had context injected
        mid-decode saw those tokens at positions no concatenation of the
        two lists reproduces — and the fed stream is the record of what
        was actually forwarded, which is precisely the KV being rebuilt.

        The GENERATION BUDGET moves with the fold, via
        :meth:`~arbi_serve.engine.request.Request.fold_output_into_prompt`.
        The tokens leaving ``output_token_ids`` were generated and
        streamed; scored against the live list alone the request would
        generate a full budget AGAIN and answer at a length the caller
        never asked for. Recording them keeps the total generated count
        the same as an uninterrupted run's, and keeps the request's reach
        — what :meth:`_reprefill_budget` is measured against — invariant.

        Returns False: the request is queued, not running.
        """
        sched = self._sched
        seq = req.fed_token_ids()
        # Whatever the row still holds goes back first. A PARKED row holds
        # nothing (the park freed its pages and unregistered it), but a
        # FROZEN hybrid row reaches here through ``_restore_recurrent_row``
        # with its paged KV still resident and still registered — and
        # admission registers from scratch. Commit before releasing so the
        # pages this request is about to recompute are in the tree for its
        # own re-match to find, the same order the preempt path uses.
        self._commit_before_release(req)
        sched.page_table.remove_request(req.request_id)
        free_recurrent = getattr(sched.pool, "free_recurrent_state", None)
        if free_recurrent is not None:
            free_recurrent(req.request_id)
        req.state_handles.pop(sched.primary_paged_kind, None)
        req.prompt_token_ids = seq
        req.fold_output_into_prompt()
        req.context_injections = []
        req.context_consumed = 0
        req.prompt_consumed = 0
        req.cached_prefix_tokens = 0
        req.last_sampled_gpu = None
        req.drop_parked_advances()
        # The prebuilt CPU-prep arrays were sliced from the OLD prompt.
        from arbi_serve.engine.cpu_prep import cancel_prep

        cancel_prep(req)
        req.offload_reprefill_tokens += len(seq)
        req.requeued_time = time.time()
        # The pause latch says the per-step policy may not put this row back
        # on a slate, and the policy never reaches a recovery through it: the
        # resume pass skips a paused row before it can fault. The one trigger
        # that gets here with the latch set is the operator's own resume, so
        # clearing it is what that operator asked for — and leaving it set on
        # a row that is queued rather than parked would strand a flag nothing
        # reads and nobody can clear.
        req.operator_paused = False
        _discard_by_identity(sched.suspended, req)
        set_state(req, RequestState.WAITING)
        # ``add`` is TOTAL: it never raises, it defers a request that cannot
        # get a recurrent row yet, and it routes an unexpected failure to the
        # dropped-job terminal path. So a recovery cannot strand the request
        # or take the engine loop down.
        sched.add(req)
        cache_metrics.counter_inc(
            "arbi_serve.suspended.fault_recovery_total",
            labels={"outcome": "reprefill"},
        )
        cache_metrics.counter_inc(
            "arbi_serve.suspended.fault_recovery_tokens",
            value=len(seq),
            labels={"service_tier": "flex" if req.is_flex else "default"},
        )
        _LOG.debug(
            "offload fault miss req=%s → re-prefill tokens=%d spent=%d",
            req.request_id,
            len(seq),
            req.offload_reprefill_tokens,
        )
        return False

    def _commit_before_release(self, req: Request) -> None:
        """Publish a still-resident row's written pages before dropping them.

        Only a FROZEN row has any: a park already released its pages, and
        what it shared stayed in the tree at refcount 0 for the re-match to
        find. Delegated to the preempt path's own commit so the truncation
        rule that keeps an uncomputed slot out of the shared tree lives in
        one place.
        """
        preemptor = getattr(self._sched, "_preemptor", None)
        commit = getattr(preemptor, "_commit_written_pages", None)
        if commit is not None:
            commit(req)

    def resume_from_offload(self, req: Request) -> bool:
        """Bring ``req``'s KV back and rejoin running. Inverse of the park.

        The full pages come back through the ORDINARY prefix path: a match
        over the sequence the park committed walks the radix tree for whatever
        is still hot and faults the rest out of the tier, and neither the
        matcher nor the restorer can tell a parked page from a cached one.
        That is the whole point of keying a park by prefix — the resume is a
        cache hit, and a second request that shares the prefix gets the same
        pages for free.

        Only the tail is this method's own work, because admission is
        page-aligned and a tail is not.

        Fails (returns False, leaves the job suspended) when the pool cannot
        seat the request right now — the caller retries on a later step once
        pages free up. A fault MISS never resumes: the KV is not there to
        resume against. It goes to :meth:`_recover_lost_snapshot`, which
        re-prefills the request rather than ending it wherever the token
        sequence can be rebuilt, and drops it by name where it cannot. Under
        prefix-chain keying that recovery is CHEAPER than it reads: a miss at
        page ``i`` still leaves pages ``0..i-1`` matched, so the rebuild is
        the suffix and not the context. Either way the request does not rejoin
        the running set HERE, so a miss returns False.
        """
        sched = self._sched
        store = self._park_store()
        chain = getattr(req, "parked_chain", None)
        if store is None or chain is None:
            return False
        if self.is_resident_suspended(req):
            # Its pages never left, so there is nothing to fault back and no
            # re-admission to make — the row is still REGISTERED, and asking
            # the table to admit it again would refuse. A frozen row reaches
            # here only when the state it was waiting to restore is gone,
            # which is the recovery's question, and the recovery already knows
            # how to take a still-resident row apart.
            return self._lost_park(req, "frozen")
        # Re-admit the request against its own prefix. The tree match and the
        # tier restore both happen inside this call; what comes back is how
        # many tokens of KV the request now has without recomputing anything.
        rematch = self._rematch_parked_prefix(req, chain)
        if rematch is None:
            return False
        matched, recurrent = rematch
        if matched < chain.written_tokens:
            # Some page of the chain is gone — expired, flushed, or lost to a
            # failed spill. Everything BEFORE it was still matched, which is
            # the arithmetic a job-keyed store could never offer: the rebuild
            # is the suffix, not the context. That is the recovery path's
            # question, and it is asked with the token sequence that answers
            # it rather than with this request's id.
            return self._lost_park(req, "page" if matched < chain.page_tokens else "tail")
        if sched._has_recurrent_state() and not recurrent:
            return self._lost_park(req, "recurrent")
        req.state_handles[sched.primary_paged_kind] = sched.page_table.page_ids(req.request_id)
        if recurrent:
            alloc_recurrent = getattr(sched.pool, "alloc_recurrent_state", None)
            queue_resume = getattr(sched.pool, "queue_savepoint_resume", None)
            if alloc_recurrent is not None:
                alloc_recurrent(req.request_id)
            if queue_resume is not None:
                queue_resume(req.request_id, recurrent)
        # The retention this request claimed is no longer claimed: its KV is
        # live on the card again. The entries stay in the tier as ORDINARY
        # cache, where another request's prefix match may still hit them.
        release_park_pins(sched.page_table, chain)
        req.parked_chain = None
        _discard_by_identity(sched.suspended, req)
        set_state(req, RequestState.DECODING)
        sched._running_add(req)
        if sched._metrics is not None:
            sched._metrics.decode_inc()
        cache_metrics.counter_inc(
            "arbi_serve.suspended.resume_total",
            labels={"service_tier": "flex" if req.is_flex else "default"},
        )
        _LOG.debug("resume←offload req=%s pages=%d", req.request_id, len(chain.page_keys))
        return True

    def _rematch_parked_prefix(self, req: Request, chain) -> tuple[int, dict] | None:
        """Re-register ``req`` against its own prefix; return tokens covered.

        ``None`` when the pool cannot seat it — a refusal, not a loss, and the
        request stays parked for a later step. The match runs through
        ``add_request`` exactly as a fresh admission's does, so the parked
        request takes the prefix cache, the tier restore, the refcounts and
        the tenant scope every request takes. A resumed request is an
        ordinarily admitted request; it does not come back as an untenanted,
        uncacheable stranger, which is what the job-keyed resume had to make it.
        """
        sched = self._sched
        table = sched.page_table
        seq = sequence_prefix(req, chain.written_tokens)
        try:
            covered = int(
                table.add_request(
                    req.request_id,
                    prompt_token_ids=seq,
                    tenant_id=chain.tenant_id,
                    cache_enabled=True,
                )
            )
        except RuntimeError:
            # True exhaustion, post-eviction. A refusal, not a loss: the pins
            # are still held, so the chain is still there for the next step.
            with contextlib.suppress(Exception):
                table.remove_request(req.request_id)
            return None
        # The request is back on pages it did not hold, possibly at the same
        # COUNT — which is exactly what the runner's block-table skip cache
        # cannot see. See :meth:`RadixPageTable.note_rebound_request`.
        note_rebound = getattr(table, "note_rebound_request", None)
        if note_rebound is not None:
            note_rebound()
        recurrent: dict = {}
        if covered >= chain.page_tokens:
            restore = getattr(table, "restore_parked_tail", None)
            tail = restore(req.request_id, chain) if restore is not None else None
            if tail is not None:
                covered += len(chain.tail_tokens)
                recurrent = tail
        return covered, recurrent

    def _lost_park(self, req: Request, what: str) -> bool:
        """``req``'s prefix cannot be produced in full. Hand it to the recovery.

        The pins go first and unconditionally: whatever is left of the chain is
        ordinary cache from here, and a pin nobody will ever unpin is retention
        lost for the life of the process.

        Then :meth:`_recover_lost_snapshot`, which is the miss path for every
        reason a park can come back short. Keying by prefix makes that recovery
        CHEAPER rather than different: the re-admission it performs takes the
        prefix match like any other, so the pages that were still there are
        matched and only the suffix past the first missing one is recomputed.

        WHAT THE CAUSE IS FOR. If the recovery refuses — a multimodal request,
        a request past its budget — the request ends, and then it matters WHY
        its KV went. A park broken by an admin flush is not the same event as
        one that aged out or lost a page to pressure, and a request that
        vanished because an unrelated admin action ran is the worst kind of
        unexplained. A flush is the one cause that DESTROYS the entries rather
        than releasing a claim on them, which is exactly how it is told apart.
        """
        sched = self._sched
        chain = getattr(req, "parked_chain", None)
        destroyed = chain is not None and self._park_was_destroyed(chain)
        release_park_pins(sched.page_table, chain)
        req.parked_chain = None
        # The re-match registered this request and ref'd whatever it DID find,
        # and from here it is going back through admission from scratch — down
        # either branch, including the one that ends it. So the registration
        # goes, and it goes through the RECOVERY's own release rather than
        # here, because a still-resident row (a frozen one) has pages to
        # commit before they are dropped and only that path knows to.
        _LOG.debug("offload fault miss req=%s (%s)", req.request_id, what)
        return self._recover_lost_snapshot(
            req, cause="offload_lost_cache_flush" if destroyed else None
        )

    def _park_was_destroyed(self, chain) -> bool:
        """Whether something DESTROYED this chain rather than letting it age.

        A flush drops the store's pin along with the entry, because a pin that
        outlives its bytes holds budget nothing can free. Expiry releases the
        pin too — but expiry leaves the ENTRIES, so the two are told apart by
        whether anything of the chain is still there to find.
        """
        store = self._park_store()
        if store is None:
            return False
        return not any(store.contains(k) for k in chain.keys)

    # ── operator-addressed trigger ───────────────────────────────────
    #
    # An operator asks for a FREEZE, not for a park -- the same mechanism the
    # interactive-arrival branch uses, reached through a different trigger and
    # carrying a latch the policy reads. A human standing a request down asked
    # for it to stop being scheduled and said nothing about the pool, so the
    # pause moves nothing; if the pool later needs those pages, preemption
    # parks the frozen row through ``suspend_to_offload`` like any other
    # victim. What the operator adds over the policy's freeze is only the
    # latch: the policy may undo its own decision, and must not undo this one.

    def pause_by_operator(self, req: Request) -> bool:
        """Freeze ``req`` on an operator's instruction. True when it froze.

        A FREEZE plus a latch, and nothing else. A pause is a decision about
        scheduling: paying a blocking device→host copy of the whole request
        to free pages nobody asked for buys nothing, and it makes the resume
        able to FAIL on an allocation, for pages that never needed releasing.
        If the pool does come to need them, preemption parks the frozen row
        then — and that is the only thing that ever will.

        The engine loop exempts SUSPENDED from the request timeout, which is
        what a frozen request wants: it waits as long as the operator leaves
        it waiting, at no cost to anything that is not short of pages.

        Priority does NOT gate this. The policies stand batch down only,
        because their job is to protect interactive throughput; an operator
        asking for a specific request to stand down has already made that
        judgement, and refusing to pause an interactive request would leave
        the one class a human most often needs to stand down unpausable.

        The latch is set BEFORE the mechanism runs so a freeze that succeeds
        is never briefly visible to the policy as an ordinary stood-down row,
        and cleared again if it declines -- a request that did not stand down
        must not be left carrying a pause nobody can see.

        The trigger in :mod:`~arbi_serve.scheduler.operator_pause` refuses the
        pause outright on an engine with no store, because there a frozen
        row's pages could never be reclaimed at all.
        """
        if getattr(req, "operator_paused", False):
            return False
        req.operator_paused = True
        if self.freeze_in_place(req):
            return True
        req.operator_paused = False
        return False

    def resume_by_operator(self, req: Request) -> bool:
        """Return ``req`` to decoding on an operator's instruction.

        Two cases, and the mechanisms tell them apart themselves. Nothing
        moved (the ordinary pause): :meth:`unfreeze` runs the bookkeeping
        backwards and CANNOT fail — there is nothing to allocate, because
        the pages were never released. Something moved (pressure parked it
        while it stood paused): it faults back through the core, and a pool
        that cannot seat it right now leaves it parked AND paused, which is
        the honest state — clearing the latch would hand it to the policy,
        exactly the handover the operator's pause withheld.
        """
        if not getattr(req, "operator_paused", False):
            return False
        if self.is_resident_suspended(req):
            if not self.unfreeze(req):
                return False
            req.operator_paused = False
            return True
        if self.resume_from_offload(req):
            req.operator_paused = False
            return True
        return False
# ---- operator_pause.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Pause and resume one in-flight request, addressed by id.

A PAUSE IS NOT A STOP. Stopping ends a request the way it would have ended
anyway; pausing keeps it, frozen where it stood, and resuming carries it on
from there.

A PAUSE IS NOT A PARK EITHER. Moving a request's paged KV off the GPU is what
PRESSURE does -- the pool-pressure policy and the allocation path's preemption.
An operator asking for a request to stand down said nothing about the pool, so
the pause does not move its KV, and the resume cannot fail on pages that were
never released. If the pool does come to need those pages, preemption takes
them from the frozen row -- within its priority class, the row giving up no
progress goes first -- and that park is what a later resume faults back.

What the pause DOES give back, on a hybrid model, is the recurrent working
slot: the pool holds one per concurrent sequence, so a paused request keeping
one would take capacity away from the engine to hold nothing. That is the
freeze's own contract, shared with the interactive-arrival trigger, and it is
a slab row rather than a request's whole KV.

The mechanism stays in
:class:`~arbi_serve.scheduler.offload_manager.OffloadManager`; this module only
resolves the id, states the refusals, and reports which of the two happened.

WHY A LATCH AND NOT JUST A CALL. The per-step policy unparks parked requests on
its own judgement as soon as the pool has headroom. Without
``Request.operator_paused`` an operator's pause would survive only until the
next step that found room, which is not a pause. The latch is what the policy
reads to know the decision was not its to revisit.

REFUSES RATHER THAN NO-OPS, and says which. Every one of these is a state a
caller can legitimately reach by racing the engine, so each gets its own reason
rather than a shared failure: a request can finish between the timeline read
and the click, and a pool with no free pages can decline a resume that is
otherwise perfectly valid.
"""

from __future__ import annotations

from typing import Any

from arbi_serve.flag_truth import path_counter

#: Marks that an operator parked / unparked a live request. Separate marks
#: from the policy counters (``arbi_serve.suspended.offload_total``) on
#: purpose: a reader comparing parked-job counts needs to tell a scheduler
#: decision from a human one, and one counter answers neither "is the policy
#: engaging" nor "did somebody pause this". Marks, not totals -- nothing reads
#: a count of operator actions, and the parked-job gauges already carry
#: how many.
request_paused_by_operator = path_counter("request_paused_by_operator")
request_resumed_by_operator = path_counter("request_resumed_by_operator")


def _offload_manager(eng: Any):
    """The scheduler's offload manager, or ``None`` when unreachable."""
    scheduler = getattr(eng, "scheduler", None)
    if scheduler is None:
        return None
    return getattr(scheduler, "_offload_manager", None)


def _no_store_reason(eng: Any) -> str | None:
    """Why a pause is unavailable on this engine, or ``None`` when it is.

    The freeze itself needs no store -- it moves nothing. What needs one is
    the way OUT of a freeze that the pool cannot afford: with nowhere to put
    a frozen request's KV, preemption cannot reclaim its pages, so the pause
    would hold VRAM the engine may come to need for as long as it lasts. A
    pause that can cost the pool a request's worth of pages indefinitely is
    refused rather than offered.
    """
    if not getattr(getattr(eng, "scheduler", None), "parking_enabled", False):
        return (
            "this engine does not park, so a paused request's pages could never "
            "be reclaimed if the pool came under pressure (parking is turned off "
            "with --disable-kv-parking, there is no prefix tier to pin in, or "
            "kv_parking_serves_here refused this topology)"
        )
    return None


def pause_now(eng: Any, *, request_id: str) -> dict:
    """Freeze one running request where it stands, KV untouched.

    Refuses when the store is absent (see :func:`_no_store_reason`), when the
    id is not running, when the request is already paused, and when the
    request is not DECODING -- a mid-prefill row has no point to be frozen at
    and no stable resume contract, the same refusal the park core states.
    """
    from arbi_serve.sampler.thinking_budget import _find_request

    reason = _no_store_reason(eng)
    if reason is not None:
        return {"paused": False, "how": "refused", "reason": reason}
    manager = _offload_manager(eng)
    if manager is None:
        return {
            "paused": False,
            "how": "refused",
            "reason": "this engine exposes no offload manager to pause through",
        }
    scheduler = getattr(eng, "scheduler", None)
    req = _find_request(list(getattr(scheduler, "running", None) or ()), request_id)
    if req is None:
        return {
            "paused": False,
            "how": "refused",
            "reason": f"request {request_id!r} is not running",
        }
    if getattr(req, "operator_paused", False):
        return {"paused": True, "how": "already_paused", "reason": ""}
    if manager.pause_by_operator(req):
        request_paused_by_operator.fired = 1
        # ``how`` is the wire contract the generated client and the admin
        # console read; the values are theirs to recognise, not a description
        # of the mechanism this call happened to use.
        return {"paused": True, "how": "offloaded", "reason": ""}
    return {
        "paused": False,
        "how": "refused",
        "reason": (
            "the request is not in a pausable state -- only a DECODING row has "
            "a resume point, so a row still prefilling cannot be paused"
        ),
    }


def resume_now(eng: Any, *, request_id: str) -> dict:
    """Return one paused request to decoding.

    Instant when the pause is all that ever happened -- the KV never left the
    GPU, so there is nothing to allocate and nothing that can decline. It only
    faults back when pressure parked the request while it stood paused, and
    only that case can be refused for want of pages, which leaves it parked
    and paused rather than dropping the pause on the floor.

    Refuses when the id is not among the stood-down requests, and when it is
    parked by POLICY rather than by an operator (there is nothing for an
    operator to release -- the scheduler unparks it itself).
    """
    from arbi_serve.sampler.thinking_budget import _find_request

    manager = _offload_manager(eng)
    scheduler = getattr(eng, "scheduler", None)
    if manager is None or scheduler is None:
        return {
            "resumed": False,
            "how": "refused",
            "reason": "this engine exposes no offload manager to resume through",
        }
    req = _find_request(list(getattr(scheduler, "suspended", None) or ()), request_id)
    if req is None:
        running = _find_request(list(getattr(scheduler, "running", None) or ()), request_id)
        if running is not None:
            return {"resumed": True, "how": "already_running", "reason": ""}
        return {
            "resumed": False,
            "how": "refused",
            "reason": f"request {request_id!r} is not paused",
        }
    if not getattr(req, "operator_paused", False):
        return {
            "resumed": False,
            "how": "refused",
            "reason": (
                "this request was parked by the scheduler, not by an operator; "
                "it resumes on its own once the pool has headroom"
            ),
        }
    if manager.resume_by_operator(req):
        request_resumed_by_operator.fired = 1
        return {"resumed": True, "how": "faulted_back", "reason": ""}
    return {
        "resumed": False,
        "how": "refused",
        "reason": (
            "the pool could not give this request pages right now; it stays "
            "paused rather than silently rejoining the scheduler's queue"
        ),
    }
# ---- partial_prefill_first.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Partial prefills before full chunks (``ARBI_PARTIAL_PREFILL_FIRST``).

A prefill that needs LESS than a full chunk this step — a short prompt, the
tail a prefix-cache hit leaves, the last chunk of a long prompt — goes before
any prefill that would take a full chunk. Depth-first FCFS
(:mod:`arbi_serve.scheduler.step_budget`) otherwise hands the oldest prompt
the whole ``chunk_prefill``-wide budget every step, so a chat turn arriving
behind a 128k prefill waits out every chunk of it.

With the flag on, ``Scheduler.schedule`` builds a step in this order:

1. decode rows (pass 1 defers every PREFILLING row to the end of its sweep,
   so a decode row is never sized out by a prefill ahead of it in
   ``running``);
2. running partial prefills, in queue order;
3. running full-chunk prefills, sized against the budget minus a RESERVE —
   the oldest waiting partial prefills that fit whole, in queue order
   (:meth:`PartialFirstStep.row_budget`);
4. the admission pass, which picks those waiting partials first
   (:meth:`PartialFirstStep.next_partial`) and then falls through to the
   ordinary FCFS pick for whatever budget is left.

Partials overtake full-chunk prompts, never each other: they are taken in
queue order, and one that fails a gate ends admission for the step exactly as
the ordinary pick does, so a cache-hit turn that cannot go yet keeps its place
and nothing behind it is admitted first. It is then not reserved for on the
following step (:meth:`PartialFirstStep.note_stop`), so a candidate that
cannot fit (pages, activation) costs the full chunks every other step at most.

Only INTERACTIVE waiting requests jump: priority classes are untouched, and
a background request is still admitted only by the ordinary pick. Waiting
candidates are found in :attr:`Scheduler._partial_waiting`, kept by
``_waiting_add`` / ``_waiting_remove`` at the size each request had when it
entered ``waiting`` (after its prefix-cache match), so a step with no partial
prefill waiting scans nothing.
"""

from __future__ import annotations

from itertools import chain
from typing import TYPE_CHECKING

from arbi_serve.engine.request import RequestState
from arbi_serve.flag_truth import FiringWindow, path_counter

if TYPE_CHECKING:
    from collections.abc import Iterable, Iterator

    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.prefix_grouping import PrefixSerialContext
    from arbi_serve.scheduler.scheduler import Scheduler


#: Marked on every step the rule orders; ``flag_contracts_sched`` holds the
#: canonical config to it.
_PATH = path_counter("partial_prefill_first_step", FiringWindow.SERVE)


def set_partial_prefill_first(sched: Scheduler, on: bool) -> None:
    """Snapshot the live flag; turning it off forgets the side index."""
    sched._partial_prefill_first = on
    if not on or getattr(sched, "_partial_waiting", None) is None:
        sched._partial_waiting = {}


def note_waiting_add(sched: Scheduler, req: Request, *, left: bool = False) -> None:
    """Index ``req`` as a partial candidate when it needs less than a chunk.

    In queue order: a request put back at the head of ``waiting`` (``left``,
    a preemption) goes to the head of the index too.
    """
    if (
        getattr(sched, "_partial_prefill_first", False)
        and not req.is_flex
        and req.num_remaining_prompt < sched.batch_cfg.chunk_prefill
    ):
        if left and sched._partial_waiting:
            sched._partial_waiting = {req.request_id: req, **sched._partial_waiting}
        else:
            sched._partial_waiting[req.request_id] = req


def note_waiting_remove(sched: Scheduler, req: Request) -> None:
    partial = getattr(sched, "_partial_waiting", None)
    if partial:
        partial.pop(req.request_id, None)


def partial_first_step(
    sched: Scheduler, chunk_cap: int, interactive_present: bool
) -> PartialFirstStep | None:
    """The step's ordering state, or ``None`` when the flag is off.

    Off as well under per-task queues, whose own picker owns admission order.
    """
    if not getattr(sched, "_partial_prefill_first", False) or sched._task_queues is not None:
        return None
    _PATH.fired = 1
    return PartialFirstStep(sched, chunk_cap, interactive_present)


class PartialFirstStep:
    """One ``schedule()`` call's partial-first ordering."""

    __slots__ = (
        "_sched",
        "_chunk",
        "_interactive_present",
        "_seen",
        "_partial_rows",
        "_full_rows",
        "_reserve",
        "last_pick",
    )

    def __init__(self, sched: Scheduler, chunk_cap: int, interactive_present: bool) -> None:
        self._sched = sched
        self._chunk = int(chunk_cap)
        self._interactive_present = interactive_present
        self._seen: set[int] = set()
        self._partial_rows: list[Request] = []
        self._full_rows: list[Request] = []
        self._reserve: int | None = None
        #: The candidate :meth:`next_partial` returned last, until the next pick.
        self.last_pick: Request | None = None

    # ── pass 1: running rows ────────────────────────────────────────
    def running_rows(self, running: Iterable[Request]) -> Iterator[Request]:
        """``running`` with each PREFILLING row revisited after the sweep.

        The deferred lists are filled while the first sweep runs and read
        when ``chain`` reaches them: partial prefills, then full ones.
        """
        return chain(list(running), self._partial_rows, self._full_rows)

    def defer(self, req: Request) -> bool:
        """True on a PREFILLING row's first visit: queue it, skip it for now."""
        rid = req.request_id
        if rid in self._seen:
            return False
        self._seen.add(rid)
        if req.num_remaining_prompt < self._chunk:
            self._partial_rows.append(req)
        else:
            self._full_rows.append(req)
        return True

    def row_budget(self, req: Request, budget: int) -> int:
        """A full-chunk row's budget: what the waiting partials leave."""
        if req.num_remaining_prompt < self._chunk:
            return budget
        if self._reserve is None:
            self._reserve = self._reserve_for(budget)
        return max(0, budget - self._reserve)

    def _eligible(self, req: Request) -> bool:
        sched = self._sched
        if req.is_duplex_frame or req.is_flex:
            return False
        if req.num_remaining_prompt >= self._chunk:
            return False
        ready = getattr(sched, "_media_preparation_ready", None)
        if ready is not None and not ready(req):
            return False
        return not sched._prefill_runs_on_peer(req)

    def _reserve_for(self, budget: int) -> int:
        """Tokens of the oldest waiting partials that fit whole, in queue order.

        A candidate that failed its gate last step ends the reserve once (its
        mark is cleared), so a candidate that cannot be admitted does not
        hold budget away from the full chunks on every step.
        """
        total = 0
        for req in self._sched._partial_waiting.values():
            if getattr(req, "_partial_first_blocked", False):
                req._partial_first_blocked = False
                break  # it holds its place, so nothing behind it goes either
            if not self._eligible(req):
                continue
            need = max(1, req.num_remaining_prompt)
            if total + need > budget:
                break  # queue order: nothing behind this one is reserved for
            total += need
        return total

    # ── pass 2: waiting candidates ──────────────────────────────────
    def next_partial(
        self, budget: int, prefix_context: PrefixSerialContext | None
    ) -> Request | None:
        """The oldest waiting partial prefill, in queue order.

        Never one behind it: partials overtake full-chunk prompts, not each
        other. One that does not fit the budget whole takes what is left, as
        any request does; one that fails a gate ends admission for the step
        exactly as the ordinary pick does, so nothing behind it goes first.
        """
        pick = None
        if budget > 0:
            for req in self._sched._partial_waiting.values():
                if req.state != RequestState.WAITING or not self._eligible(req):
                    continue
                if prefix_context is not None and prefix_context.pick([req]) is not req:
                    continue
                pick = req
                break
        self.last_pick = pick
        return pick

    def note_stop(self) -> None:
        """Admission ended. A partial pick still waiting failed a gate:
        reserve nothing for it next step (see :meth:`_reserve_for`)."""
        req = self.last_pick
        if req is not None and req.state == RequestState.WAITING:
            req._partial_first_blocked = True
# ---- preemption.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Preemption victim picker (priority + fairness aware).

When a running request needs a new KV page and the primary paged pool is
full, :meth:`Preemptor.preempt_for_space` takes a request's pages. The
victims are the running requests AND the frozen ones — stood down by an
operator's pause or by interactive arrival, still holding their KV.
Batch-priority goes before any interactive request; within a priority class
a frozen row goes before a running one (it gives up no progress it was
making), then the lowest-fairness-weight tenant, then the most-recently
admitted row. Nothing is ever parked FOR being frozen: a short pool is the
only reason this runs at all.

WHICH request loses its pages is that ordering. What happens TO it has one
input: whether its KV has anywhere to go. With a destination the victim is
PARKED through the offload core (:meth:`OffloadManager.suspend_to_offload`,
the same save every other park trigger calls) — KV snapshotted off the
GPU, pages freed, and a later resume faults it back with every token it
had already computed. Without one the victim is DROPPED: pages released,
decode state reset, re-queued to re-prefill whatever the radix tree no
longer holds of it.

Both paths must exist and the reason is not that one of them is older.
Saving preserves the WORK and requires somewhere to put it; dropping
preserves the SYSTEM and requires nothing. A scheduler that cannot free a
page when it has nowhere to put the contents can only OOM or refuse the
request, and both are worse for the caller than a re-prefill — so the drop
path is the last resort under pressure, and a deployment that runs with KV
offload off (no host RAM or disk spent on this) is served by it on every
preemption, not degraded by it.

The DROP rewrites its victim: ``prompt_token_ids`` is rebuilt to cover
everything the request had been fed, and ``output_token_ids`` is emptied
into the generated history
(:meth:`~arbi_serve.engine.request.Request.fold_output_into_prompt`). That
fold is the seam to be careful at. The token sequence is unchanged by it,
so anything scoped to ``prompt + output`` is unaffected — the prefix
cache, the repetition penalty, the KV the re-prefill rebuilds. What
changes is that ``output_token_ids`` stops meaning "what this request has
said" and means only "what is still in the live decode list", so every
consumer of the first sense reads
:func:`~arbi_serve.engine.request.generated_token_ids` /
:func:`~arbi_serve.engine.request.n_generated` instead: the generation
budget, the presence / frequency penalty history, the completion counts.
The M-RoPE grid is extended rather than rebuilt, and a multimodal victim
is preempted like any other — refusing one would wedge the pool it is
supposed to be yielding, and in a vision deployment every candidate is
multimodal.

The picker operates over the live :class:`Scheduler` it is constructed
with — it reads/mutates ``sched.running`` / ``sched.waiting`` and reads
``sched.page_table`` / ``sched.pool`` / ``sched.primary_paged_kind`` /
``sched._metrics`` and the tenant fairness helper.
"""

from __future__ import annotations

import time
from typing import TYPE_CHECKING, Any

from arbi_serve.cache import _metrics as cache_metrics
from arbi_serve.engine.request import RequestState, length_budget_spent, set_state
from arbi_serve.multimodal.rope import extend_mrope_grid_for_fold

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.scheduler import Scheduler


def written_sequence(page_table: Any, req: Request) -> list[int]:
    """The token prefix whose KV this request has actually WRITTEN.

    Two positions in the full sequence do not have KV and the page table is
    the only thing that knows it: a decode row's most recently sampled token
    is appended to ``output_token_ids`` at sample time but is not fed until
    the next step's forward, and a chunked-prefill row has consumed only part
    of its prompt. Anything that publishes or keys off this request's KV — the
    preempt commit, and a park, which commits for the same reason — has to
    stop where the KV does, or it names a page with an uncomputed slot.

    Empty when the table does not know the request, or knows it to hold
    nothing.
    """
    length = getattr(page_table, "length", None)
    if length is None:
        return []
    try:
        written = int(length(req.request_id))
    except KeyError:
        return []
    if written <= 0:
        return []
    return sequence_prefix(req, written)


def sequence_prefix(req: Request, n_tokens: int) -> list[int]:
    """``req``'s first ``n_tokens`` tokens, across the prompt/output seam.

    A request's sequence is two lists and the boundary between them moves, so
    every caller that wants "the first N tokens as the model saw them" has to
    cross it the same way. Materializes only the prefix asked for: a
    mid-prefill row's bound stops inside its prompt, and the concatenation the
    truncation would immediately discard is never built.
    """
    cache_ids = req.cache_token_ids()
    n_cached = len(cache_ids)
    if n_tokens <= n_cached:
        return list(cache_ids[:n_tokens])
    return list(cache_ids) + list(req.output_token_ids[: n_tokens - n_cached])


def commit_written_pages(page_table: Any, req: Request, *, unpaired: bool = False) -> list[int]:
    """Promote ``req``'s completed full pages into the radix tree.

    ``commit_full_pages`` runs at end-of-prefill and again at
    :meth:`Scheduler.finished`. A preempt is neither, and neither is a park,
    so a DECODING row reaching either has its generated tokens' pages sitting
    private and unmatchable at the moment they matter most — the preempt is
    about to recompute exactly those tokens, and the park is about to key its
    retention on them. Returns the sequence committed.

    ``unpaired`` is the park's: its chain is resumed with its own recurrent
    row, so it is committed past the savepoints a hybrid's publish otherwise
    stops at (:mod:`arbi_serve.cache.radix_pagetable_savepoints`). A preempt
    stays paired — it resumes through ordinary admission.
    """
    seq = written_sequence(page_table, req)
    commit = getattr(page_table, "commit_full_pages", None)
    if seq and commit is not None:
        if unpaired:
            commit(req.request_id, token_ids=seq, unpaired=True)
        else:
            commit(req.request_id, token_ids=seq)
    return seq


class Preemptor:
    """Priority- and fairness-aware preemption victim picker."""

    def __init__(self, sched: Scheduler) -> None:
        self._sched = sched

    def fairness_key(self, req: Request) -> float:
        """Tiebreak key used by the preemption picker.

        Higher ``fairness_weight`` = more important; we preempt the
        LOW-weight victim first when the pool is exhausted. Anon /
        no-tenant requests are weight 1.0 by default.
        """
        tenant = self._sched._tenant_for(req)
        return float(getattr(tenant, "fairness_weight", 1.0))

    def victim_ordering(self) -> list[Request]:
        """Everything that holds KV, in the order it loses its pages.

        The candidates are the running set plus the FROZEN rows — stood
        down by an operator's pause or by interactive arrival, still
        holding their KV
        (:meth:`~arbi_serve.scheduler.offload_manager.OffloadManager.is_resident_suspended`).
        A frozen row is a candidate, never a reason: nothing is parked for
        being idle, only because the pool is short. When it IS short and a
        victim must be chosen, the frozen row is the better one, since it
        gives up no progress it was making — so it sorts ahead of a running
        row of the SAME priority class, and behind the priority key rather
        than in front of it. Standing a request down must not be what
        exposes it to eviction ahead of work the engine is actively doing.

        Keys, in order: priority class (batch = 0 before interactive = 1,
        so batch is evicted first); idle (frozen = 0 before running = 1);
        fairness weight (lowest first); recency (most-recently-admitted or
        most-recently-frozen first).

        STABLE UNDER REMOVAL, which is what lets a caller that needs
        several victims compute this once and consume it. Removing an
        element shifts the index of everything to its right down by one,
        uniformly, so the ``-index`` tiebreak preserves the relative order
        of every survivor; the priority, idle and weight keys do not change
        at all. That covers a frozen row too: parking one does not move it
        out of ``suspended`` — only its KV moves — so it simply stops
        matching the predicate, exactly like a preempted row leaving
        ``running``. The all-interactive/unweighted fast path is the same
        order the sort produces for those keys, so a mid-sequence
        transition into it (the last weighted or batch row was the victim)
        agrees with the precomputed remainder as well.

        With nothing frozen — the steady state — this is the running deque
        and the ordering it always was.
        """
        sched = self._sched
        mgr = sched._offload_manager
        frozen = [r for r in sched.suspended if mgr.is_resident_suspended(r)]
        running = list(sched.running)
        candidates = frozen + running if frozen else running
        any_batch = any(r.is_flex for r in candidates)
        any_weighted = any(self.fairness_key(r) != 1.0 for r in candidates)
        if any_batch or any_weighted:
            # Priority and/or fairness in play — sort explicitly.
            # ``(prio_rank, idle_rank, weight, -index)``: batch-before-
            # interactive, then frozen-before-running, then low-weight,
            # then rightmost. Stable across equal keys.
            n_frozen = len(candidates) - len(running)
            indexed = list(enumerate(candidates))
            indexed.sort(
                key=lambda kv: (
                    1 if not kv[1].is_flex else 0,
                    0 if kv[0] < n_frozen else 1,
                    self.fairness_key(kv[1]),
                    -kv[0],
                )
            )
            return [kv[1] for kv in indexed]
        # Fast path: all interactive, no fairness configured.
        # Most-recent-first like pre-priority (rightmost preempts
        # first). Byte-identical to the legacy default behaviour when
        # nothing is frozen, and the sort's own order when something is.
        return frozen[::-1] + running[::-1] if frozen else running[::-1]

    def preempt_for_space(
        self,
        slate_req_ids: set[int] | None = None,
        *,
        admitting_is_batch: bool = False,
        spare_running_peers: bool = False,
        ordering: list[Request] | None = None,
    ) -> bool:
        """Free a running request's KV pages. True when one was freed.

        ``spare_running_peers`` — the caller is admitting a WAITING request, not
        growing a running one. A waiting request has produced nothing this
        residency, so it never earns the pages of a running peer of its own
        class: the victim would re-queue at the head of ``waiting``, be
        re-admitted into the pages its own eviction just freed, and take its
        preemptor's pages in turn. Each lap re-prefills a whole sequence and
        emits no token, so under oversubscription the engine spends its full
        forward budget on recompute and generates nothing (measured on
        ``tests/test_preempt_no_pingpong.py``: 60 recomputed tokens per
        generated one). With the flag set only a frozen row (it gives up no
        progress it was making) or a batch row under an interactive admission
        is a victim; otherwise the waiting request waits for pages to free
        naturally. A RUNNING row that needs a page for its next token keeps
        the right to preempt the newest peer, which is what guarantees the
        oldest row always finishes.

        PARK FIRST, DROP AS THE FALLBACK. The victim's pages are the
        product either way; what differs is whether the work that filled
        them survives. When the scheduler has a suspended store the victim
        is handed to :meth:`OffloadManager.suspend_to_offload` — one call
        to the core every other park trigger uses, never a second save
        path here — which snapshots its KV off the GPU, frees the pages
        and leaves it SUSPENDED with its ``output_token_ids`` and its
        place in the sequence intact; the resume faults it back and not
        one token is recomputed. Everything below the park is the DROP:
        pages released, prompt rebuilt as prompt+output, decode state
        reset, re-queued at the head of ``waiting`` to re-prefill.

        The drop is not a legacy path and must not rot into one. It is
        what runs when there is nowhere to put the victim's KV — the
        store is absent because the deployment chose not to spend host RAM
        and disk on offload, or the core declines this particular request
        — and in that situation freeing the page by giving up the work is
        the only remaining way to stay available. Saving preserves the
        work and needs a destination; dropping preserves the system and
        needs nothing. Remove the drop and a full pool with offload off
        has no lever left but to OOM or refuse.

        Each drop counts WHY the save was unavailable
        (``preempt_park_unavailable_total{reason}``) against the parks
        (``preempt_park_total``), so "are we still throwing work away, and
        because of what" is read off the metrics rather than off this file.

        Duplex-lane requests (``Request.is_duplex_frame``) are never
        victims at all, by either route — see the loop's guard.

        A FROZEN row is a victim like any other, and is only ever PARKED.
        It stands down still holding its pages, so it is exactly what a
        pass looking for pages should consider; within its priority class
        it goes first, because it gives up no progress it was making. What
        it never gets is the drop — that path rewrites a victim into a
        re-prefill from ``waiting``, where nothing remembers it was stood
        down. Every other guard here applies to it unchanged, including
        ``admitting_is_batch``: the ordering puts batch rows first, frozen
        or running, so reaching an interactive row still means no batch
        victim is left.

        Priority bias (opportunistic batch). The victim picker is
        priority-aware: low-priority ``"flex"`` running requests are
        evicted BEFORE any interactive request. Within a priority class
        the legacy ordering holds — lowest fairness-weight tenant first,
        then most-recently-admitted (rightmost of the deque). So an
        interactive request never loses its KV pages while any batch
        request is still resident, which is what keeps interactive TTFT
        flat under a batch backlog.

        ``admitting_is_batch`` — when the request DRIVING this
        preemption is itself background-priority, interactive requests are
        excluded from the victim pool entirely: we never preempt
        interactive to make room for batch. If no batch victim is
        available the preempt fails and the batch admission is deferred
        to a later step (it only ever runs on genuinely spare capacity).

        Fairness tiebreak. Within a priority class we PREEMPT THE
        LOWEST-WEIGHT TENANT FIRST. Equal-weight tenants fall back to
        most-recent-first. Without any priority or quota config every
        request is interactive / weight 1.0, so the ``ordering`` below
        reduces to a most-recent-first deque walk.

        ``slate_req_ids`` is the set of request ids already attached
        to the in-progress slate this :meth:`Scheduler.schedule` call.
        We refuse to preempt those: the slate row holds a Python
        reference to the live ``Request`` object, and preempting it
        in-place would rebuild ``prompt_token_ids`` / reset
        ``prompt_consumed`` / clear ``output_token_ids`` while the slate
        row still points at the same object. Downstream
        :meth:`_build_batch` then either slices a stale prompt at line
        945 or — when both the rebuilt prompt and the cleared output are
        empty (the ``chunk_prefill=256`` second-admission case) — raises
        ``IndexError: list index out of range`` reading
        ``prompt_token_ids[-1]``. Excluding slate reqs from the victim
        pool keeps preempt scoped to genuinely-idle running rows; if
        no eligible victim remains, the caller's
        ``can_allocate / preempt`` gate fails and admission breaks
        out of its loop (the request retries next step).

        What the victim keeps. Its pages are COMMITTED into the radix
        tree before they are released (:meth:`_commit_written_pages`), so
        the restarted prefill can alias back what it already computed
        instead of recomputing it. That claim is made at ADMISSION, not
        here — see ``Scheduler._rebind_preempted_prefix`` — because a
        matched page is ref-ed back up and stops being evictable, and a
        request sitting in ``waiting`` holding its whole prefix takes the
        pool away from every request that could actually run. Here the
        pages go to ref 0: still in the tree, matchable, and reclaimable
        by whoever needs them first.

        ``ordering`` — a victim order this call should consume instead of
        building its own, for a caller taking several victims in a row
        (:meth:`~arbi_serve.scheduler.scheduler_allocation._AllocationMixin._preempt_until_allocatable`).
        Entries already gone from ``running`` are skipped by the
        ``_running_remove`` guard below, and :meth:`victim_ordering`
        documents why a precomputed order picks the same victims in the
        same sequence as rebuilding it per victim does."""
        sched = self._sched
        mgr = sched._offload_manager
        if ordering is None:
            ordering = self.victim_ordering()
        for victim in ordering:
            if victim.is_duplex_frame:
                # A duplex-lane connection's Request must never be reset
                # via the generic preemption path (task #45).
                # Everything below rebuilds ``prompt_token_ids`` down to
                # the pre-consumed prefix, clears ``output_token_ids``,
                # drops the recurrent/Mamba state, and restarts prefill
                # from scratch — correct for an ordinary request (it just
                # redoes work) but destructive for a duplex session: the
                # "prompt" a duplex request would restart from is the
                # one-time seed/system-prompt prefix, not the audio/
                # conversation history the connection has streamed since
                # (``new_duplex_request``'s docstring), so a preempted
                # duplex request would silently lose that history with no
                # way to recover it — corruption, not just a latency
                # cost. A duplex request's KV/state growth is bounded
                # instead by its own hard cap, closed CLEANLY by the
                # duplex lane (``arbi_serve/realtime/duplex_lane.py``),
                # never by bumping it back to WAITING. It is therefore
                # simply never a valid preemption victim, regardless of
                # priority/fairness class.
                continue
            # A FROZEN row is a victim as well as a running one: it stands
            # down holding its KV, and pages are what this pass is for. Read
            # once — every guard below has to know which kind it is holding,
            # and for a running row the answer is one state compare.
            frozen_victim = mgr.is_resident_suspended(victim)
            if not frozen_victim and victim.state not in (
                RequestState.PREFILLING,
                RequestState.DECODING,
            ):
                # Not resident any more. ``ordering`` is a snapshot a caller
                # consumes across several victims (:meth:`victim_ordering`),
                # and a park earlier in the same pass leaves its victim in
                # that snapshot as a SUSPENDED row whose page-table entry is
                # gone — the ``page_table.length`` read below would raise
                # KeyError on it. The state IS the O(1) residency test.
                continue
            if sched.page_table.length(victim.request_id) == 0:
                continue
            if slate_req_ids is not None and victim.request_id in slate_req_ids:
                # Refuse to preempt a request that already has a row on
                # the in-progress slate — see method docstring.
                continue
            if getattr(victim, "context_consumed", 0) or getattr(
                victim, "pending_context_token_ids", None
            ):
                # Refuse to preempt a request carrying injected context.
                # The rewind below reconstructs a sequence as
                # ``prompt[:consumed] + output``, which cannot express
                # context that arrived AFTER output — the injected tokens
                # would be dropped and ``context_consumed`` would inflate
                # ``total_length`` against a request re-prefilling from
                # zero. Skipping costs at most admission backpressure.
                continue
            if length_budget_spent(victim):
                # Already generated everything it was promised. Asked of
                # the rule that decides ``finish_reason="length"`` rather
                # than restated, so the two cannot drift apart. Such a
                # victim is one sampled token from releasing its pages on
                # its own; preempting it would buy a full re-prefill to
                # produce a token the caller is not owed. Skipping is both
                # the cheaper and the correct answer.
                continue
            if admitting_is_batch and not victim.is_flex:
                # Never preempt an interactive request to make room for
                # a batch request. ``ordering`` puts batch victims first,
                # so once we reach an interactive row there are no batch
                # victims left — bail out and let the batch admission
                # retry on genuinely spare capacity next step.
                break
            if (
                spare_running_peers
                and not frozen_victim
                and not (victim.is_flex and not admitting_is_batch)
            ):
                continue
            prio = "flex" if victim.is_flex else "default"
            if frozen_victim:
                # PARK OR SKIP, never the drop below. The drop rewrites a
                # victim into a fresh re-prefill from ``waiting`` — a path
                # where nothing reads the pause latch and nothing remembers
                # the row was stood down, so a frozen request would silently
                # start running again, and an operator-paused one would come
                # back from a pause nobody lifted. With nowhere to put its
                # KV the freeze simply keeps its pages and the pass moves on.
                if mgr.suspend_to_offload(victim):
                    cache_metrics.counter_inc(
                        "arbi_serve.scheduler.preempt_park_total",
                        labels={"service_tier": prio},
                    )
                    return True
                # Not a drop, so not a drop REASON: the unavailable counter
                # is read against the recompute tokens below, and nothing
                # was recomputed or thrown away here.
                continue
            # ── Park, if this victim's KV has anywhere to go ──────────
            #
            # One condition decides it: a destination. The store is the
            # destination, and the core is the only thing that knows
            # whether it can take THIS request (it refuses anything not
            # DECODING — a mid-prefill row has no stable resume point —
            # and, on a hybrid, refuses without recurrent offload, because
            # half a save resumes against zero GDN/Mamba state). So ask it
            # rather than restating its conditions here, and let the two
            # answers it can give be the two reasons a drop happens.
            #
            # A park costs a blocking D2H of the victim's KV on the engine
            # loop and the drop costs nothing here — but the drop's bill
            # arrives anyway, as a re-prefill of every token the victim had
            # computed, and a forward over those tokens is far more engine
            # time than a copy of their KV. There is therefore no burst
            # size at which dropping is the cheaper answer, and no cap on
            # parks per pass: the pass already stops preempting the moment
            # its demand is allocatable.
            if not sched.parking_enabled:
                # This deployment does not park — it asked for no parking, or
                # it has no prefix tier to pin a parked prefix in. Nothing to
                # save into, so the page can only be freed by giving up the
                # work — see the method docstring.
                park_unavailable = "no_store"
            elif mgr.suspend_to_offload(victim):
                cache_metrics.counter_inc(
                    "arbi_serve.scheduler.preempt_park_total",
                    labels={"service_tier": prio},
                )
                return True
            else:
                # The core holds a destination but declined this request:
                # it is not in a state whose resume point is well defined.
                park_unavailable = "declined"
            cache_metrics.counter_inc(
                "arbi_serve.scheduler.preempt_park_unavailable_total",
                labels={"reason": park_unavailable},
            )
            # Drop the victim from running BEFORE mutating it; matches
            # the pre-J ``sched.running.pop()`` semantics. Use ``remove``
            # (O(n)) rather than ``pop`` because the picked victim is
            # now identity-keyed, not always the rightmost.
            if not sched._running_remove(victim):
                # Defensive — victim already removed (shouldn't fire,
                # but keeps the loop linear-progress).
                continue
            # The victim's decode-completed full pages are not in the tree
            # yet — ``commit_full_pages`` runs at end-of-prefill and again
            # at ``Scheduler.finished``, and a preempt is neither. Commit
            # them HERE, before the drop below ``_ref_down``s the path, so
            # the tokens this request generated are matchable at all: they
            # are exactly what its restarted prefill is about to recompute.
            # Keyed on the tokens whose KV is actually written — see
            # :meth:`_commit_written_pages`.
            self._commit_written_pages(victim)
            # The restarted sequence is the WHOLE prompt plus whatever has
            # been generated from it. Not ``prompt[:prompt_consumed] +
            # output``: a victim caught mid-prefill has consumed only part
            # of its prompt and no output yet, so that expression DROPS the
            # unconsumed tail and the request goes on to answer a prompt
            # that stops early — silent output corruption, and reachable
            # whenever a chunked-prefill row misses a step's token budget
            # and so is not on the slate that protects it (see
            # ``test_a_mid_prefill_victim_keeps_its_unconsumed_prompt``).
            # The two forms agree exactly where the old one was sound —
            # ``output`` is non-empty only once the prompt is fully
            # consumed, and then the slice is the identity.
            new_prompt = list(victim.prompt_token_ids) + list(victim.output_token_ids)
            # The media-salted cache view (multimodal) parallels
            # ``prompt_token_ids`` one-for-one over the prompt, so the
            # rewritten sequence's salted view is that list plus the
            # output. Rebuilt in lockstep, or ``cache_token_ids()`` would
            # hand the re-match — and every later commit — a stale key.
            new_cache_ids = None
            if victim.cache_key_ids is not None:
                new_cache_ids = list(victim.cache_key_ids) + list(victim.output_token_ids)
            # One seam for the free + page-less re-add: it carries the
            # victim's cache identity (tenant namespace + cache opt-out)
            # across the preempt. Never open-code remove + add_request
            # here — add_request's defaults are "global namespace, cache
            # writes ON", which silently defeats both privacy controls.
            #
            # PAGE-LESS, deliberately. The victim will re-use the pages it
            # just committed, but it claims them at ADMISSION
            # (``Scheduler._rebind_preempted_prefix``), not here: a matched
            # page is ref-ed back UP and stops being LRU-evictable, and a
            # request sitting in ``waiting`` that pins its whole prefix
            # takes the pool away from every request that could actually
            # run — and the scheduler cannot escape that, since preemption
            # is its only lever and its victims are the ones holding the
            # pages. Between here and the re-bind they are ref-0 and
            # evictable, which is the correct standing: free space that a
            # request can reclaim if nothing needs it first.
            sched.page_table.readmit_preempted(victim.request_id)
            victim.prompt_token_ids = new_prompt
            victim.cache_key_ids = new_cache_ids
            victim.prompt_consumed = 0
            # THE fold. Records the generated tokens as generated before
            # emptying the live list, so everything scoped to "what this
            # request has said" — the generation budget, the presence /
            # frequency penalty history, the completion counts — keeps its
            # meaning across the rewrite, and rebases the detokenizer
            # cursor that indexes the list being emptied.
            folded = victim.fold_output_into_prompt()
            # The cached M-RoPE grid is ``(3, len(prompt))`` against the
            # prompt as it was, and the prompt just grew by the folded
            # tokens. Extended rather than refused: the folded tokens are
            # text at the end of the sequence, so their positions are
            # reconstructed exactly and no vision tower re-runs.
            extend_mrope_grid_for_fold(victim, folded)
            victim.cached_prefix_tokens = 0
            victim.state_handles[sched.primary_paged_kind] = sched.page_table.page_ids(
                victim.request_id
            )
            # Recurrent / short-conv: the restarted prefill re-reads this
            # row from its first token, so the slab must not still hold the
            # state the pre-preempt sequence left there. Free + re-alloc
            # gives a fresh row (queued for zero-clear); the row index may
            # differ, which is fine — the metadata builder resolves it via
            # ``row_for(req_id)`` next step. A savepoint restore resolved by
            # the re-bind is queued ON TOP of that fresh row.
            free_recurrent = getattr(sched.pool, "free_recurrent_state", None)
            alloc_recurrent = getattr(sched.pool, "alloc_recurrent_state", None)
            if free_recurrent is not None:
                free_recurrent(victim.request_id)
            if alloc_recurrent is not None:
                alloc_recurrent(victim.request_id)
            # Drop GPU sample reference — the request will re-prefill
            # from scratch, so the runner's first decode after re-add
            # falls back to the CPU H2D path until the next sample
            # lands.
            victim.last_sampled_gpu = None
            # Drop any parked optimistic advance — the request re-prefills
            # from scratch (output_token_ids cleared above), so a parked tick
            # has no meaning and must not inflate total_length. Covers the
            # MTP verify park too: its draft slots were freed by the page
            # release above, so the drain must not retire them again.
            victim.drop_parked_advances()
            # Preemption REWRITES ``prompt_token_ids`` (above) — the
            # prebuilt CPU-prep numpy arrays are now stale. Drop them
            # so :meth:`ModelRunner._build_batch` falls back to the
            # legacy Python-list slice (which reads ``victim.prompt_
            # token_ids`` live). The next admission can choose to
            # rebuild via :func:`schedule_prep`; for the common case
            # of decode-time preemption this stays on the legacy path
            # since re-prefill is rare in steady state.
            from arbi_serve.engine.cpu_prep import cancel_prep

            cancel_prep(victim)
            prev_state = victim.state
            set_state(victim, RequestState.WAITING)
            # Start of the victim's SECOND queue residency. The
            # first-schedule latch (``RequestTiming.t_first_scheduled_step``)
            # is once-only and still holds the original boundary, so the live
            # swimlane needs this to avoid drawing the first attempt's prefill
            # and decode as queue wait.
            victim.requeued_time = time.time()
            # SPMD: log the decision HERE, where it is unambiguous. The
            # append below puts the victim at the HEAD of ``waiting``, so
            # the same ``schedule()`` call's waiting-admit pass routinely
            # re-admits it onto the very slate this preempt made room for —
            # after which nothing downstream can tell it apart from an
            # ordinary fresh prefill row, and the broadcast PreemptRow the
            # workers need to replay the free/re-add/recurrent-recycle goes
            # missing (see ``Scheduler.drain_spmd_preempts``).
            sched.record_spmd_preempt(victim.request_id, len(new_prompt))
            # Arm the prefix re-bind for the admission pass that follows.
            # Scoped to THIS ``schedule()`` call by construction: the
            # scheduler clears the set at the end of the call, so a victim
            # that is not re-admitted on the pass its preempt made room for
            # simply re-prefills. That is the whole window — the victim
            # goes to the HEAD of ``waiting`` — and it keeps the SPMD
            # amendment sound, since the delta is built from the log after
            # ``schedule()`` returns and can never observe a half-armed
            # re-bind from an earlier tick.
            sched._preempt_rebind_ids.add(victim.request_id)
            sched._waiting_add(victim, left=True)
            # Preemption evidence — counts evictions split by the
            # victim's priority class so the validation harness can
            # confirm batch is preempted (not interactive) under load.
            # DROPS only: a park is counted by ``preempt_park_total`` and
            # must not land here, because this counter is read against the
            # recompute tokens below and a park recomputes nothing. The
            # pair therefore keeps meaning what it always meant — work
            # thrown away, and how much of it.
            cache_metrics.counter_inc(
                "arbi_serve.scheduler.preempt_total",
                labels={"service_tier": prio},
            )
            # Recompute evidence. This is what the victim's restarted
            # prefill costs with no re-match at all — the behaviour this
            # path had before, and still the cost of every miss. The
            # re-bind's ``preempt_prefix_tokens_saved`` is counted against
            # it, so the ratio of the two IS this path's prefix-hit rate,
            # measured rather than inferred, and identically zero when no
            # re-bind fires.
            cache_metrics.counter_inc(
                "arbi_serve.scheduler.preempt_recompute_tokens_total",
                value=len(new_prompt),
                labels={"service_tier": prio},
            )
            if sched._metrics is not None:
                if prev_state == RequestState.PREFILLING:
                    sched._metrics.prefill_dec()
                elif prev_state == RequestState.DECODING:
                    sched._metrics.decode_dec()
                sched._metrics.queue_inc()
            return True
        return False

    # ── Prefix-aware re-admit ────────────────────────────────────────

    def _commit_written_pages(self, victim: Request) -> None:
        """Promote the victim's completed full pages into the radix tree.

        Thin delegator to :func:`commit_written_pages`, which the park path
        reaches for the same reason this one does — see its docstring.
        """
        commit_written_pages(self._sched.page_table, victim)
# ---- prefill_cache_limit.py ----
# SPDX-License-Identifier: Apache-2.0
"""One source-query boundary shared by KV and recurrent cache admission."""

from arbi_serve.distributed.kv_prefix_resume import computed_prefix


def resume_match_limit(req, *limits):
    prefix = computed_prefix(req)
    bounded = [int(limit) for limit in limits if limit is not None]
    if prefix is not None:
        # Keep one owned source forward, which captures and ships the final
        # prefix state. The receiver still owns the logical prompt's last row.
        bounded.append(max(0, prefix - 1))
    return min(bounded) if bounded else None


def probe_resume(sched, req, tenant_id):
    tokens = req.cache_token_ids()
    limit = resume_match_limit(req)
    if sched._savepoint_chain_bs is not None:
        kwargs = {"max_match_len": limit} if limit is not None else {}
        hashes = sched.page_table.savepoint_page_hashes(tokens, tenant_id=tenant_id, **kwargs)
        return hashes, sched._savepoint_store.best_match_hashes(tenant_id, hashes)
    kwargs = {"max_tokens": limit} if limit is not None else {}
    return None, sched._savepoint_store.best_match(tenant_id, tokens, **kwargs)
# ---- prefill_chunk.py ----
# SPDX-License-Identifier: Apache-2.0
"""Prefill quantum sizing: media cadence and the existing measured memory bound."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request


def activation_chunk_cap(
    self,
    req: Request,
    want: int,
    *,
    act_prefill_tokens: int,
    act_rows: int,
    act_gather_tokens: int,
    act_query_tokens: int,
    slate_is_empty: bool,
) -> int:
    """``want`` narrowed to the prefill tokens the step's budget covers.

    The token count is the one term of the step's cost admission can move
    without refusing the row: a prefill row advances at whatever width fits,
    so a card with less free VRAM than a full-width chunk serves the prompt
    in narrower chunks instead of OOMing the forward on it. Every other term
    the model prices — the rows, the padded gather — is fixed by the slate
    the caller is building.

    The gather is charged at the UNNARROWED width, so the cap it yields is
    the conservative one: narrowing can only lower the row's own gather.

    Returns at least 1 on an empty slate. One row is the minimum unit of
    progress, and a row too expensive even at one token is the case
    :meth:`_activation_admits` names and admits with a warning — the same
    boundary, reached the same way, rather than a second policy here.
    """
    from arbi_serve.scheduler.scheduler import _ACTIVATION_NARROWED

    media_cap = getattr(self, "_media_prefill_cap", None)
    if media_cap is not None:
        want = media_cap(req, want)
    model = self._activation_model
    if model is None or want <= 0:
        return want
    cap = model.max_prefill_tokens(
        rows=act_rows + 1,
        gather_kv_tokens=max(act_gather_tokens, self._gather_charge(req, want)),
        other_prefill_tokens=act_prefill_tokens,
        query_tokens=act_query_tokens,
    )
    if cap is None:
        return want
    if cap >= want:
        return want
    _ACTIVATION_NARROWED.fired = 1
    return max(1, cap) if slate_is_empty else max(0, cap)
# ---- prefix_grouping.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Prefix-serial admission for concurrent requests sharing a prompt.

The scheduler lets one active request publish a shared prefix before related
followers enter their first slate. Followers are rebound to the radix cache
and skip that work; unrelated requests may fill every spare batch slot.

The common no-sharing path uses a tenant-scoped index of the first full page.
It returns the FCFS head after one dictionary miss. Full page-aligned LCP work
and bounded queue scanning happen only after a first-page collision.

``ARBI_PREFIX_GROUPING=off`` disables the policy and restores strict FCFS.
"""

from __future__ import annotations

from collections.abc import Iterable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request


def grouping_enabled() -> bool:
    """Evaluate the ``ARBI_PREFIX_GROUPING`` env switch.

    Default: disabled. Explicit opt-in enables the advanced concurrent-prefix
    policy; ordinary radix prefix caching does not need the grouper.
    """
    from arbi_serve.flag_truth import path_counter
    from arbi_serve.runtime_flags import runtime_flags
    from arbi_serve.runtime_flags_parsers import prefix_grouping_arm

    try:
        return prefix_grouping_arm(runtime_flags().prefix_grouping)[0]
    except ValueError:
        # Both doors validate — the boot parser and the override registry — so
        # this is reachable only by installing an overlay directly. Recorded
        # rather than raised: a scheduling step is the wrong place to discover
        # a bad config, and declining is what the flag's default does anyway.
        path_counter("prefix_grouping_enabled").refuse("unparseable_value_ignored")
        return False


def _page_chunks(token_ids: list[int], block_size: int) -> tuple[tuple[int, ...], ...]:
    """Reduce a token sequence to its page-aligned chunk tuple.

    Trailing tokens that don't fill a full page are dropped — those
    can never participate in radix-cache matching anyway.
    """
    n_full = len(token_ids) // block_size
    return tuple(tuple(token_ids[i * block_size : (i + 1) * block_size]) for i in range(n_full))


def score_pair(req_a: Request, req_b: Request, block_size: int) -> int:
    """Common page-aligned prefix length, in tokens, between two requests.

    The metric the engine actually cares about: ``score_pair == K``
    means batching A and B together aliases ``K`` tokens of prefill
    into one physical computation instead of two.
    """
    a = _page_chunks(req_a.prompt_token_ids, block_size)
    b = _page_chunks(req_b.prompt_token_ids, block_size)
    n = min(len(a), len(b))
    lcp = 0
    while lcp < n and a[lcp] == b[lcp]:
        lcp += 1
    return lcp * block_size


def _chunks_cached(req: Request, block_size: int) -> tuple[tuple[int, ...], ...]:
    """Per-request memo of :func:`_page_chunks`.

    ``group_for_batch`` runs on EVERY ``schedule()`` step while the
    waiting queue is non-empty, and rebuilt each candidate's page-chunk
    tuple from scratch — at window=128 and 16k-token prompts that is
    ~2M tuple elements per engine step, a measured double-digit share
    of the engine thread under a c64 long-context backlog. The prompt
    is immutable once queued, so the chunk tuple is computed once per
    (request, block_size) and cached on the request. Guarded by
    identity on ``prompt_token_ids`` so any exotic prompt swap
    invalidates naturally. Decisions are bit-identical to the uncached
    path.
    """
    memo = getattr(req, "_pg_chunks_memo", None)
    ids = req.prompt_token_ids
    if memo is not None and memo[0] is ids and memo[1] == block_size:
        return memo[2]
    chunks = _page_chunks(ids, block_size)
    req._pg_chunks_memo = (ids, block_size, chunks)
    return chunks


def _cached_lcp_tokens(req_a: Request, req_b: Request, block_size: int) -> int:
    a = _chunks_cached(req_a, block_size)
    b = _chunks_cached(req_b, block_size)
    n = min(len(a), len(b))
    lcp = 0
    while lcp < n and a[lcp] == b[lcp]:
        lcp += 1
    return lcp * block_size


def _first_page_cached(req: Request, block_size: int) -> tuple[int, ...] | None:
    """Return the first full prompt page without materialising every page."""

    ids = req.prompt_token_ids
    if len(ids) < block_size:
        return None
    memo = getattr(req, "_prefix_first_page_memo", None)
    if memo is not None and memo[0] is ids and memo[1] == block_size:
        return memo[2]
    first = tuple(ids[:block_size])
    req._prefix_first_page_memo = (ids, block_size, first)
    return first


@dataclass
class PrefixSerialContext:
    """Per-step active-prefix index for rare-path serial admission.

    The common no-sharing lookup is one dictionary miss on a memoized first
    page. Full LCP comparison runs only after that tenant-scoped collision.
    """

    block_size: int
    publish_granularity: int
    window: int
    owner: PrefixGrouper | None = None
    _leaders: dict[tuple[str, tuple[int, ...]], list[Request]] = field(default_factory=dict)

    def add_leader(self, req: Request) -> None:
        if req.state.name != "PREFILLING":
            return
        if not bool(getattr(req.sampling, "cache_enabled", True)):
            return
        first = _first_page_cached(req, self.block_size)
        if first is None:
            return
        key = (str(getattr(req, "tenant_id", "") or ""), first)
        self._leaders.setdefault(key, []).append(req)

    def _decision(self, candidate: Request) -> tuple[bool, bool, int]:
        """Return ``(blocked, refresh, shared_tokens)`` for ``candidate``."""

        was_blocked = bool(getattr(candidate, "_prefix_serial_blocked", False))
        if bool(getattr(candidate, "_prefix_serial_started", False)):
            return False, False, 0
        if not bool(getattr(candidate.sampling, "cache_enabled", True)):
            return False, False, 0
        first = _first_page_cached(candidate, self.block_size)
        if first is None:
            return False, was_blocked, 0
        key = (str(getattr(candidate, "tenant_id", "") or ""), first)
        leaders = self._leaders.get(key)
        if not leaders:
            return False, was_blocked, 0

        cached = int(getattr(candidate, "cached_prefix_tokens", 0) or 0)
        blocked_shared = 0
        ready_shared = 0
        for leader in leaders:
            if leader is candidate:
                continue
            # Interactive latency is never traded for reuse produced by a
            # background/batch request.
            if not candidate.is_flex and leader.is_flex:
                continue
            shared = _cached_lcp_tokens(candidate, leader, self.block_size)
            if shared <= cached:
                continue
            granularity = max(self.block_size, self.publish_granularity)
            published = (int(leader.prompt_consumed) // granularity) * granularity
            published = (published // self.block_size) * self.block_size
            if published >= shared:
                ready_shared = max(ready_shared, shared)
            else:
                blocked_shared = max(blocked_shared, shared)
        if ready_shared > cached:
            return False, True, ready_shared
        if blocked_shared > cached:
            return True, False, blocked_shared
        return False, was_blocked, 0

    def pick(self, candidates: Iterable[Request]) -> Request | None:
        """Return the first unblocked candidate, scanning only after a hit."""

        for idx, candidate in enumerate(candidates):
            if idx >= self.window:
                break
            blocked, refresh, shared = self._decision(candidate)
            if blocked:
                if self.owner is not None:
                    self.owner.blocked_possible = True
                if not bool(getattr(candidate, "_prefix_serial_blocked", False)):
                    from arbi_serve.cache import _metrics as cache_metrics

                    cache_metrics.counter_inc(
                        "arbi_serve.prefix_cache.serial_deferred_total",
                        labels={"tenant": str(getattr(candidate, "tenant_id", "") or "_global")},
                    )
                candidate._prefix_serial_blocked = True
                candidate._prefix_serial_target = shared
                continue
            if refresh:
                from arbi_serve.cache import _metrics as cache_metrics

                cache_metrics.counter_inc(
                    "arbi_serve.prefix_cache.serial_rebind_total",
                    labels={"tenant": str(getattr(candidate, "tenant_id", "") or "_global")},
                )
                candidate._prefix_serial_refresh = True
            return candidate
        return None


class PrefixGrouper:
    """Stateless-ish grouper — maintains no cross-step state.

    The current implementation is pure-function over the pending queue.

    Args:
        block_size: page size; the grouper works in page-chunk units.
        window: cap on how many leading pending-queue entries are
            considered as candidates. Bounds the grouper's per-step
            cost at O(window²).
    """

    def __init__(self, block_size: int, window: int = 128) -> None:
        if block_size <= 0:
            raise ValueError(f"PrefixGrouper: block_size={block_size} invalid.")
        if window <= 0:
            raise ValueError(f"PrefixGrouper: window={window} invalid.")
        self.block_size = block_size
        self.window = window
        # Rare-path hint. False means the scheduler need not build an empty
        # context after the last active leader leaves prefill.
        self.blocked_possible = False

    def serial_context(
        self,
        leaders: Iterable[Request],
        *,
        publish_granularity: int,
    ) -> PrefixSerialContext:
        """Build the per-step active-prefix index used by the scheduler."""

        context = PrefixSerialContext(self.block_size, publish_granularity, self.window, owner=self)
        for leader in leaders:
            context.add_leader(leader)
        return context

    # ── Public scoring helpers (used by tests + scheduler diagnostics) ──

    def score_pair(self, req_a: Request, req_b: Request) -> int:
        """Page-aligned shared-prefix token count between two requests at this grouper's block size."""
        return score_pair(req_a, req_b, self.block_size)

    def shared_tokens(self, batch: list[Request]) -> int:
        """Total shared-prefix tokens within a candidate batch.

        Computed as the sum of (matching-page count × ``block_size``)
        savings against the leader. The leader pays its own prefill;
        each follower saves up to its LCP with the leader. This is the
        exact same accounting the radix cache will produce when the
        batch hits.
        """
        if len(batch) < 2:
            return 0
        leader = batch[0]
        return sum(self.score_pair(leader, r) for r in batch[1:])

    # ── Group selection ──────────────────────────────────────────────

    def group_for_batch(
        self,
        pending: list[Request],
        max_batch: int,
    ) -> list[Request]:
        """Pick a batch from ``pending`` maximising shared-prefix density.

        Algorithm: take ``pending[0]`` (FCFS leader — preserves
        head-of-line fairness; we never starve the oldest waiting
        request), then greedily admit up to ``max_batch - 1`` more
        from ``pending[1 : 1+window]`` in DESCENDING order of LCP with
        the leader. Ties broken FCFS.

        Returns the chosen requests in admission order (leader first,
        then highest-LCP siblings). The scheduler's main loop then
        admits them into the batch as if they were the head of the
        FCFS queue — which they effectively are.

        Returning a SUBSEQUENCE of the original pending order is
        important: the scheduler will pop these from the actual deque
        in the order returned, and the leader-first invariant
        guarantees no head-of-line starvation.
        """
        if max_batch <= 0 or not pending:
            return []
        if max_batch == 1 or len(pending) == 1:
            return [pending[0]]

        leader = pending[0]
        # Score the leader against the next ``window`` candidates.
        candidates = pending[1 : 1 + self.window]
        # Memoize the leader's page-chunk tuple once instead of
        # rebuilding it inside every ``score_pair`` call. Pre-H.3a this
        # rebuilt the leader's chunks ``window`` times — at window=128
        # and a 2K-token leader prompt that's ~128 redundant chunk
        # rebuilds per admit cycle. Sub-µs at small batch but trivially
        # avoidable.
        bs = self.block_size
        leader_chunks = _chunks_cached(leader, bs)
        n_leader = len(leader_chunks)
        scored: list[tuple[int, int, Request]] = []
        for idx, r in enumerate(candidates):
            cand_chunks = _chunks_cached(r, bs)
            n = n_leader if n_leader < len(cand_chunks) else len(cand_chunks)
            lcp = 0
            while lcp < n and leader_chunks[lcp] == cand_chunks[lcp]:
                lcp += 1
            scored.append((lcp * bs, idx, r))
        # Higher LCP first; ties → smaller original index (FCFS).
        scored.sort(key=lambda t: (-t[0], t[1]))

        out = [leader]
        for lcp, _idx, r in scored:
            if len(out) >= max_batch:
                break
            # Only include if the candidate ACTUALLY shares something
            # OR there is still budget to admit it as a regular FCFS
            # entry. Keeping zero-LCP candidates in (still preserving
            # FCFS order via the tie-break) gives the scheduler the
            # same admit count it had before; the clustering only
            # REORDERS within ``max_batch``, never DENIES admission to
            # a request the FCFS path would have admitted.
            _ = lcp  # used implicitly via sort order
            out.append(r)
        return out


def _resolve_window(window: int | None = None) -> int:
    """Resolve the effective grouper window from ``ARBI_PREFIX_GROUPING``.

    Factored out of :func:`build_grouper_from_env` so the scheduler can
    re-resolve the window on every step (the flag is one of the fresh-read
    runtime flags — a live change must apply without a member rebuild, and
    the window rides the same value as the mode). Both call sites share this
    one implementation so the truth table stays single-sourced.
    """
    from arbi_serve.flag_truth import path_counter
    from arbi_serve.runtime_flags import runtime_flags
    from arbi_serve.runtime_flags_parsers import (
        PREFIX_GROUPING_DEFAULT_WINDOW,
        prefix_grouping_arm,
    )

    _window_counter = path_counter("prefix_grouping_window_override")
    fallback = window or PREFIX_GROUPING_DEFAULT_WINDOW
    try:
        _enabled, env_window = prefix_grouping_arm(runtime_flags().prefix_grouping)
    except ValueError:
        # Same defence as :func:`grouping_enabled`, on the counter that owns
        # the window: the per-step refresh re-reads the flag, so an overlay
        # installed between the two calls lands here.
        _window_counter.refuse("unparseable_window_ignored")
        return fallback
    if env_window is None:
        _window_counter.refuse("unset_default_window_128")
        return fallback
    if env_window == fallback:
        _window_counter.refuse("value_equals_effective_default")
    else:
        _window_counter.fired = 1
    return env_window


def build_grouper_from_env(
    block_size: int,
    window: int | None = None,
) -> PrefixGrouper | None:
    """Construct a grouper if env hasn't disabled it; else ``None``.

    The scheduler treats ``None`` as "FCFS, do nothing fancy" — that's
    the disabled path.
    """
    from arbi_serve.flag_truth import path_counter

    # Flag-truth (ARBI_PREFIX_GROUPING): the flag's only power is to
    # ENABLE the default-off grouper — that edge fires.
    _mode_counter = path_counter("prefix_grouping_enabled")
    if not grouping_enabled():
        _mode_counter.refuse("default_off")
        return None
    _mode_counter.fired = 1

    return PrefixGrouper(block_size=block_size, window=_resolve_window(window))


def refresh_grouper_window(grouper: PrefixGrouper) -> None:
    """Re-resolve ``grouper.window`` from the CURRENT env, in place.

    Called every scheduling step while grouping is enabled (see
    ``Scheduler.schedule``) so a live ``ARBI_PREFIX_GROUPING`` flip takes
    effect on the next step without discarding the grouper object —
    preserving its cross-step ``blocked_possible`` hint, which a full
    rebuild would otherwise reset.
    """
    grouper.window = _resolve_window()
# ---- quota_filter.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Per-tenant rate-limit + concurrency-cap slate filter.

This is the LAST admission gate before a step's slate goes out: it
drops slate rows whose tenant has exhausted its quota, leaving those
requests queued (``Scheduler.running`` / ``Scheduler.waiting``) for the
next step. Zero cost when every request is anon / UNLIMITED.

``QuotaFilter`` owns the :class:`QuotaTracker` and the per-reason
deferral counters (the test / metrics surface). The
:meth:`Scheduler._tenant_for` resolver is passed in so tenant resolution
stays single-sourced on the scheduler.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from arbi_serve.server.shed import record_shed
from arbi_serve.tenant.quota import QuotaTracker

if TYPE_CHECKING:
    from collections.abc import Callable

    from arbi_serve.engine.request import Request
    from arbi_serve.tenant.context import TenantContext


class QuotaFilter:
    """Per-tenant rate-limit + concurrency-cap admission filter."""

    def __init__(
        self,
        tenant_for: Callable[[Request], TenantContext],
        quota_tracker: QuotaTracker | None = None,
    ) -> None:
        self._tenant_for = tenant_for
        # Per-tenant quota tracker. ``None`` (default) installs a
        # fresh in-memory tracker scoped to this scheduler instance;
        # the engine wiring can pass a shared one when multiple
        # schedulers run inside one process. The tracker enforces
        # tenant rate limits + concurrency caps as an ADDITIVE
        # admission filter — when no :class:`TenantContext` is
        # attached or the budget is :data:`UNLIMITED`, the gate is
        # zero-cost (one attribute read).
        self.tracker: QuotaTracker = quota_tracker or QuotaTracker()
        # Per-tenant deferred-by-quota counters (metrics surface).
        # ``deferred[reason] -> count`` accumulates across the
        # scheduler's lifetime; the test harness reads this to assert
        # rate-limit enforcement fires.
        self.deferred: dict[str, int] = {}
        # (tenant_id, reason) pairs already logged once — see :meth:`apply`.
        self._logged_edges: set[tuple[str, str]] = set()

    def apply(
        self,
        slate: list[tuple[Request, int]],
    ) -> list[tuple[Request, int]]:
        """Drop slate rows whose tenant has exhausted its quota.

        Hot-path order: skipped rows leave the requesting request in
        ``Scheduler.running`` / ``Scheduler.waiting`` for the next step's
        slate. Pre-existing FCFS / chunk-prefill / page-boundary
        admission gates have already passed; this filter is the LAST gate
        before the slate goes out, so pages aren't allocated only to
        be rolled back.

        ``cost_tokens`` is the new tokens the request will produce
        this step (``n_tok`` from the slate row). For prefill rows
        ``n_tok`` is the chunk size; for decode rows it's 1
        (or ``mtp_k`` for a verify pass — the verify slate emits the
        post-MTP-bucketing K rows separately).

        Empty slate, no-tenant slate (anon / UNLIMITED everywhere),
        and no-tracker → fast no-op.

        Side effect: increments per-reason deferral counters readable
        via :meth:`deferred_by_quota` for tests / metrics.
        """
        if not slate:
            return slate
        out: list[tuple[Request, int]] = []
        for req, n_tok in slate:
            tenant = self._tenant_for(req)
            # Fast-path: anon / UNLIMITED budget skips the tracker.
            budget = tenant.quota_budget
            if (
                tenant.tenant_id in ("", "anon")
                and budget.tokens_per_second is None
                and budget.max_concurrent_requests is None
                and budget.max_prompt_tokens is None
            ):
                out.append((req, n_tok))
                continue
            decision = self.tracker.try_admit(
                tenant,
                prompt_tokens=len(req.prompt_token_ids),
                cost_tokens=float(n_tok),
                request_id=req.request_id,
            )
            if decision.admitted:
                out.append((req, n_tok))
                continue
            self.note_deferred(tenant, decision)
        return out

    def note_deferred(self, tenant, decision) -> None:
        """Record a known refusal without reserving a request or spending tokens."""
        self.deferred[decision.reason] = self.deferred.get(decision.reason, 0) + 1
        # The in-memory tally above is not exported anywhere. Emit the
        # shed receipt so per-tenant deferrals reach the same counter as
        # every other refusal. This gate re-evaluates the SAME queued
        # request every step, so COUNT each one (the rate stays exact)
        # but LOG only the edge — the first time this (tenant, reason)
        # pair defers — or a single rate-limited tenant would emit a
        # WARNING per step and bury the log it is meant to serve.
        tenant_id = getattr(tenant, "tenant_id", "?")
        edge = (tenant_id, decision.reason) not in self._logged_edges
        if edge:
            self._logged_edges.add((tenant_id, decision.reason))
        record_shed(
            layer="quota",
            reason=decision.reason,
            status=429,
            detail=f"tenant={tenant_id} (first of this kind; counted every step)",
            log=edge,
        )

    def deferred_by_quota(self) -> dict[str, int]:
        """Return per-reason deferral counts since boot (test / metrics hook).

        Keys are :class:`QuotaDecision.reason` strings
        (``"rate_limited_tps"``, ``"concurrent_cap"``,
        ``"prompt_too_long"``). Reset only by reconstructing the
        scheduler.
        """
        return dict(self.deferred)
# ---- savepoint_admission.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Recurrent-state savepoint snapshot worker (device-side).

The :class:`Scheduler.commit` per-token accounting loop stays in
``scheduler.py`` (the off-by-one class hides in that loop and can't be
GPU-validated here); only the device-side snapshot worker — the async
D2H clone + ``put`` into the host-RAM savepoint store — lives here.

The admission-side resume-key resolution stays inline in
:meth:`Scheduler._add_inner`: it is woven through the radix
``add_request`` / ``prompt_consumed`` accounting and the KV-coverage
cross-check, where lifting it would risk the documented token-accounting
off-by-one. ``SavepointSnapshotter`` reads ``sched._savepoint_store`` /
``sched.pool`` via the ``sched`` reference.
"""

from __future__ import annotations

import logging
import time
from collections import OrderedDict
from typing import TYPE_CHECKING, Any

from arbi_serve.cache import _metrics as cache_metrics
from arbi_serve.cache.savepoint_retention import (
    RetentionCounters,
    TrailRecency,
    pair_eviction_sink,
)
from arbi_serve.flag_truth import FiringWindow, path_counter
from arbi_serve.scheduler.prefill_cache_limit import probe_resume, resume_match_limit
from arbi_serve.scheduler.savepoint_boundary_commit import (
    _CROSSING_WRITE_TOTAL as _CROSSING_WRITE_TOTAL,
)
from arbi_serve.scheduler.savepoint_boundary_commit import (
    _PROMPT_END_WRITE as _PROMPT_END_WRITE,
)
from arbi_serve.scheduler.savepoint_boundary_commit import _BoundaryCommitMixin
from arbi_serve.scheduler.savepoint_resume_fallback import (
    live_resume_at_or_below,
    serve_or_fall_back,
)
from arbi_serve.scheduler.savepoint_trail import (
    BranchPoints,
    record_savepoint_write,
    wrote_past,
)
from arbi_serve.scheduler.savepoint_trail import (
    boundary_already_stored as boundary_already_stored,
)

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.scheduler import Scheduler

_LOG = logging.getLogger("arbi_serve.scheduler")

#: How many step intervals may be open at once. The loop awaits one step at a
#: time, so one is the steady state; the slack covers a step that raises
#: between the open and the close, which would otherwise leave a stamp behind
#: for ever.
_MAX_OPEN_STEP_STAMPS = 4


def _slate_key(slate) -> tuple:
    """The step's row sequence — the same for the emitted list and the plan's tuple."""
    return tuple((id(req), int(n)) for req, n in slate)


#: Whether a savepoint was written DURING generation, at a KV-page boundary,
#: so the deepest saved state covers the reply and not only the prompt. Every
#: refusal names why the ids and the slab could not be trusted to agree.
_DECODE_WRITE = path_counter("savepoint_decode_write", FiringWindow.SERVE)

#: ``ARBI_SAVEPOINT_CROSSING_WRITES`` — when a governor crossing inside the
#: prompt is written (:attr:`~arbi_serve.runtime_flags_fields_core.
#: RuntimeFlagsCoreFields.savepoint_crossing_writes`).
CROSSING_POLICIES: tuple[str, ...] = ("demand", "always", "never")
#: A tenant's crossings being armed, by the evidence that armed them.
_CROSSING_ARMED_TOTAL = "arbi_serve.savepoint.crossing_armed_total"
#: A request whose radix walk reached past the deepest savepoint it could
#: resume from by a governor span or more: a crossing write between the two
#: would have served it, and nothing did. Labelled by whether the tenant's
#: crossings were armed when it happened — ``unarmed`` is the policy's price,
#: ``armed`` is a crossing that was wanted and still missing (not yet
#: written since the arming, or lost to the ring).
_PARTIAL_MATCH_LOST_TOTAL = "arbi_serve.savepoint.partial_match_lost_total"


def _page_of(sched) -> int:
    return max(1, int(getattr(sched, "_savepoint_page_bs", 0) or 0))


def crossing_policy_from_flag(raw: Any) -> str:
    """The crossing-write policy a flag value names, refused by name otherwise."""
    policy = str(raw).strip().lower()
    if policy not in CROSSING_POLICIES:
        raise ValueError(
            f"ARBI_SAVEPOINT_CROSSING_WRITES={raw!r} is not one of {CROSSING_POLICIES}."
        )
    return policy


def _ring_attached(sched) -> bool:
    """True when snapshots land in a bounded pinned-host ring.

    The ring changes what "the entry is gone" MEANS: a wrap is routine, an LRU
    eviction between match and get is a budget fault. The two must not share a
    failure path.
    """
    fn = getattr(getattr(sched, "pool", None), "savepoint_ring", None)
    return fn is not None and fn() is not None


class SavepointSnapshotter(_BoundaryCommitMixin, BranchPoints):
    """Async device-side recurrent-state snapshot into the savepoint store."""

    def __init__(self, sched: Scheduler) -> None:
        self._sched = sched
        #: Last decode boundary written per request. A row can be committed
        #: again without advancing (a refused step, a retry), and a re-put at
        #: the same key would refresh recency for a state nothing new reached.
        self._last_decode_boundary: dict[int, int] = {}
        #: Ring hand-out the request's next write on that side may OVERWRITE,
        #: keyed ``(request_id, from_decode)`` — the same split
        #: :func:`record_savepoint_write` supersedes by, so the entry named
        #: here is always the newest one the next write dominates. A write that
        #: takes a slot in place costs the ring no position, which is what
        #: turns a turn's several writes into two live slots
        #: (arbicity/arbi-serve#2296).
        self._reclaimable: dict[tuple[int, bool], tuple[int, int]] = {}
        #: Which conversation TRAIL each in-flight request continues. The
        #: link is content, not identity: a request that resumed from an
        #: entry belongs to that entry's trail, and everything it writes
        #: joins the same one. Held here rather than on the request so no
        #: conversation key is ever added to the wire format — see
        #: :mod:`arbi_serve.cache.savepoint_retention`.
        self._trail_of_req: dict[int, int] = {}
        #: Request -> the key it started a prefetch for. Held so a request
        #: that is cancelled, fails, or simply finishes can release a read
        #: nobody will collect; without it a departed request pins a future
        #: until the store is rebuilt.
        self._prefetched_for: dict[int, Any] = {}
        self._retention: TrailRecency | None = None
        self.retention_counters = RetentionCounters()
        #: The device budget reads and writes share. ``None`` until a
        #: boot has MEASURED the drive's sustained rate — the class
        #: refuses a placeholder, because an unvalidated threshold is
        #: what parked ``prefix_tier`` (#2299 §11). Without it a restore
        #: is simply not charged; nothing here invents a figure.
        self.tier_budget = None
        #: The background flusher, attached by the same boot that
        #: measured the rate. See :meth:`attach_flusher`.
        self.flusher = None
        #: Open intervals, keyed by the step's ROW SEQUENCE rather than by
        #: the slate object: the scheduler emits a list and the step plan
        #: carries a tuple built from it, so the object the commit side sees
        #: is never the one ``schedule`` returned. Matching on identity
        #: therefore closed nothing at all — 216 intervals opened, 0 closed,
        #: on the boot that found it. Bounded, so a step that raises between
        #: the two leaves at most a few stamps behind.
        self._step_stamps: OrderedDict[tuple, tuple[int, int, int]] = OrderedDict()
        #: Running mean microseconds of a DECODE-ONLY step, and how many were
        #: seen. It is the baseline a mixed step's prefill chunk is charged
        #: against — see :meth:`observe_step_prefill`.
        self._decode_step_us = 0.0
        self._decode_steps = 0
        #: Prefill observations actually fed to the store this boot. Zero is
        #: the state in which the disk tier holds nothing, so it is reported
        #: rather than inferred from a threshold that never appeared.
        self.prefill_observations = 0
        #: Steps this seam opened an interval for, and steps it closed one on.
        #: A closed count far below the opened one means the interval is not
        #: reaching its partner — which is the shape that makes the whole
        #: measurement silently absent, so it is counted rather than assumed.
        self.steps_stamped = 0
        self.steps_closed = 0

    def attach_flusher(self, budget, *, idle_sleep_s: float = 0.05):
        """Start the band flusher against a MEASURED device budget.

        Separate from construction because its one input is a
        measurement this scheduler cannot take: the drive's sustained
        bytes/s. Until a boot supplies one, the window still ranks and
        the pair still demotes — an entry is simply flushed when the
        allocator reaches it, which
        ``evictions_that_waited_for_a_flush`` then reports as the
        invariant not holding, rather than being hidden.
        """
        from arbi_serve.cache.savepoint_retention import SavepointFlusher

        window = self.retention
        store = self._sched._savepoint_store
        if window is None or store is None:
            return None
        row = self._row_nbytes()
        if row <= 0:
            # A flush costs the budget what the entry weighs, and nothing here
            # knows what that is. A band spending zero per write is not a
            # band — it would issue every flush the moment it saw one, which
            # is the device contention the budget exists to prevent.
            return None
        self.tier_budget = budget
        self.flusher = SavepointFlusher(
            store=store,
            window=window,
            budget=budget,
            entry_nbytes=lambda _key, _row=row: _row,
            counters=self.retention_counters,
            idle_sleep_s=idle_sleep_s,
        )
        self.flusher._prefill_observations = lambda: self.prefill_observations
        self.flusher._rate_seam = lambda: {
            "steps_stamped": self.steps_stamped,
            "steps_closed": self.steps_closed,
            "decode_baseline_n": self._decode_steps,
            "decode_baseline_us": int(self._decode_step_us),
        }
        self.flusher.start()
        return self.flusher

    # ── The prefill rate the disk tier's break-even races ────────────
    #
    # A savepoint is worth a disk round trip only when restoring it beats
    # re-prefilling the tokens it covers. The store times its own two legs —
    # the drive and the cipher — and the pool times the bus; the third term,
    # what a prefill costs per token, is the engine's and only the engine can
    # take it. This pair is that seam: the scheduler is the one site holding
    # both a step's prefill token count and the interval its forward ran in.
    #
    # A MIXED step's wall time pays for its decode rows as well, and dividing
    # it by the prefill tokens alone prices a prefill token at whatever the
    # decode rows happened to cost. Waiting for a PURE-prefill step instead
    # sounds safe and measures nothing: past the first wave of a boot there
    # is essentially always something decoding, so a served engine runs
    # almost none of them and the threshold never appears — the tier stays
    # inert and the boot line goes on saying the rate is unmeasured. Measured
    # on a card: zero observations over a twelve-conversation drive.
    #
    # So the charge is MARGINAL, against a baseline this boot measured: a
    # decode-only step's wall time is what the decode rows cost, and what a
    # mixed step costs ABOVE it is what its prefill chunk cost. Both terms
    # are this engine's own, on this card, and the subtraction is floored at
    # zero so a noisy step can only decline to observe, never invent a rate.
    #
    # The baseline's batch width is the known approximation: a wide batch
    # overcharges the prefill (the disk gate reads this feed too).

    def note_slate_dispatched(self, slate: list) -> None:
        """Open the interval for the step ``slate`` is about to run.

        Called by :meth:`Scheduler.schedule` as it hands the slate out, which
        is where the interval has to start: everything after it — the batch
        build, the metadata, the forward, the sample — is what a re-prefill
        of these tokens would cost again.

        A no-op unless the disk tier is on: with no tier there is no
        break-even to feed, and the canonical config must not pay a clock
        read per step for a number nothing consumes.
        """
        self._step_stamp = None
        store = self._sched._savepoint_store
        if getattr(self._sched, "_remote_gate", None) is None and not getattr(
            store, "disk_enabled", False
        ):
            return
        tokens = 0
        decode_rows = 0
        for req, n_tok in slate:
            if getattr(req, "is_prefill", False):
                tokens += int(n_tok)
            else:
                decode_rows += 1
        if tokens < 1 and decode_rows < 1:
            return
        self.steps_stamped += 1
        self._step_stamps[_slate_key(slate)] = (time.monotonic_ns(), tokens, decode_rows)
        while len(self._step_stamps) > _MAX_OPEN_STEP_STAMPS:
            self._step_stamps.popitem(last=False)

    def observe_step_prefill(self, slate: list) -> None:
        """Close that interval at commit and feed the store, or the baseline.

        Matched to the slate the stamp was opened on by its ROW SEQUENCE, not
        by object identity: the scheduler emits a list, the step plan carries
        a tuple built from it, and the commit side sees the second. Matching
        is still exact — the requests are the same objects and the token
        counts are the step's — and it is what keeps one step's tokens from
        being charged to another step's clock when several are in flight.
        """
        stamp = self._step_stamps.pop(_slate_key(slate), None)
        if stamp is None:
            return
        self.steps_closed += 1
        started_ns, tokens, decode_rows = stamp
        elapsed_us = (time.monotonic_ns() - started_ns) / 1000.0
        if elapsed_us <= 0:
            return
        if tokens < 1:
            # A decode-only step. This is the baseline every mixed step is
            # charged against, and it is the only place it can be taken.
            self._decode_steps += 1
            self._decode_step_us += (elapsed_us - self._decode_step_us) / self._decode_steps
            return
        if decode_rows:
            if self._decode_steps == 0:
                # No baseline yet, so the decode rows' share is unknown.
                # Declining is the whole discipline: the threshold appears
                # when it has been measured and not before.
                return
            elapsed_us -= self._decode_step_us
            if elapsed_us <= 0:
                return
        gate = getattr(self._sched, "_remote_gate", None)
        if gate is not None:
            gate.observe_prefill(tokens, elapsed_us)
        observe = getattr(self._sched._savepoint_store, "observe_prefill", None)
        if observe is None:
            return
        observe(tokens, elapsed_us)
        self.prefill_observations += 1

    @property
    def retention(self) -> TrailRecency | None:
        """The recency window over conversation trails, built on first use.

        ``None`` when no savepoint store is wired — with nothing retained
        there is nothing to rank. Built lazily because its one input, how
        many entries the resident tier holds, is the store's cap over the
        model's measured slot size, and the cap is resolved against the
        pinned-host budget after the scheduler is constructed.
        """
        store = self._sched._savepoint_store
        if store is None:
            return None
        if self._retention is None:
            self._retention = TrailRecency(resident_entries=self._resident_entries(store))
            self._register_pair_sink(store, self._retention)
        return self._retention

    def _register_pair_sink(self, store, window: TrailRecency) -> None:
        """Link the KV and recurrent halves at the radix eviction seam (#2297).

        Registered from HERE, and not from boot, because the sink needs
        both the store (built at boot) and the window (built on the first
        savepoint this boot resolves). Registering it at the first use of
        either is what keeps the pair from being a wiring order nobody
        can see. A page table with no such seam — the flat table, or an
        older radix — keeps today's drop.
        """
        # A scheduler without a page table at all is a legitimate caller —
        # the ring's own unit tests drive the snapshotter with a minimal
        # stub, and the pair sink is an enhancement, never a requirement.
        # Reaching THROUGH the attribute rather than for it turned that
        # into an AttributeError raised from inside a snapshot.
        register = getattr(getattr(self._sched, "page_table", None), "register_pair_sink", None)
        if register is None:
            return
        block_size = int(getattr(store, "block_size", 0) or 0)
        if block_size <= 0:
            return
        register(
            pair_eviction_sink(
                store,
                block_size=block_size,
                window=window,
                counters=self.retention_counters,
            )
        )

    def _resident_entries(self, store) -> int:
        """How many entries the resident savepoint tier holds, measured.

        The store's cap over one row's byte cost — the model's own recurrent
        geometry, reported by the pool. Both move: the cap follows the
        conversation working set and is clipped against what the host can
        hold, and the row size is the model's. N follows this number down,
        which is the whole of "N shrinks under real pressure".

        WHY THE RING IS NOT MIN-ED IN, AND WHY IT ONCE HAD TO BE
        =======================================================
        This used to be ``min(cap / row, ring.slots)``, and the reasoning was
        sound while it held: an admitted entry's ``tensors`` were VIEWS into
        the ring slot the snapshot landed in, so a resident entry WAS a slot
        and the ring's wrap — not the byte cap — was the bound that bit. A
        window sized on the cap alone would have believed it held everything
        the cap admits while the ring recycled underneath it.

        That premise is gone. The store copies an admitted entry's bytes out
        of its staging slot into a pageable retention region and drops the
        stamp (``RecurrentSavepointStore.promote_tick``), so a slot is held
        for one TRANSFER and the ring is sized in transfers — ``max_batch``
        times the hand-outs a turn holds, sixteen where retention wants
        forty-four. Keeping the MIN would now under-size the window by the
        ratio between those two numbers, for a bound that no longer bounds
        anything the window is about.

        The consequence is not visible in the canonical configuration, which
        is exactly why this must not be left to be discovered: with no offload
        directory the flush band never starts and nothing reads the window's
        capacity. It bites the day the disk tier is turned back on, as a band
        that flushes a quarter of the trails it should.
        """
        row = self._row_nbytes()
        if row <= 0:
            return 0
        return int(store.max_bytes) // row

    def _restore_from_disk(self, key):
        """Fault a demoted savepoint back, or ``None`` when there is none.

        Returns ``None`` unchanged on a store with no disk tier, so the
        two failures below it — a ring wrap, and the LRU budget fault —
        keep their own meanings. A restore that throws is a miss: the
        request re-prefills, exactly as it would have with no savepoint.
        """
        store = self._sched._savepoint_store
        restore = getattr(store, "restore", None)
        if restore is None:
            return None
        budget = self.tier_budget
        row = self._row_nbytes()
        try:
            if budget is None or row <= 0:
                entry = restore(key)
            else:
                with budget.restoring(row):
                    entry = restore(key)
        except Exception:  # noqa: BLE001 — an unreadable blob is a miss
            cache_metrics.counter_inc("arbi_serve.savepoint.retention.restore_error_total")
            return None
        if entry is not None:
            cache_metrics.counter_inc("arbi_serve.savepoint.retention.restores_from_disk")
        return entry

    def _row_nbytes(self) -> int:
        """One savepoint's byte cost, or 0 when nothing can answer.

        Reaches FOR the pool rather than through it, for the same reason the
        pair sink reaches for the page table: a scheduler stand-in with no
        pool is a legitimate caller — the ring's own unit tests drive this
        class with a minimal stub — and an ``AttributeError`` raised from
        inside a snapshot is the failure that shape produces.
        """
        pool = getattr(self._sched, "pool", None)
        probe = getattr(pool, "savepoint_row_nbytes", None)
        return int(probe()) if probe is not None else 0

    def forget_request(self, req_id: int) -> None:
        """Drop per-request decode bookkeeping when the request goes away."""
        self._last_decode_boundary.pop(int(req_id), None)
        # A prefetch started for a request that is gone is a read nobody will
        # collect. The BYTES are not thrown away — a completed read left an
        # ordinary resident entry the byte cap governs — but the future is
        # dropped so a departed request cannot pin one, and it is counted as
        # wasted, which is what it was.
        self._forget_prefetch_for(int(req_id))
        self._forget_write_trail(int(req_id))
        self.forget_branch_point(int(req_id))

    def _forget_prefetch_for(self, req_id: int) -> None:
        """Release the prefetch this request started, if it started one."""
        key = self._prefetched_for.pop(int(req_id), None)
        store = self._sched._savepoint_store
        forget = getattr(store, "forget_prefetch", None)
        if key is not None and forget is not None:
            forget(key)

    def request_completed(self, req: Request) -> None:
        """A turn finished, so the entry it resumed from may now be replaced.

        Deferred to here, and not to the first deeper write, because a
        conversation is only ever resumed from a COMPLETE turn or from the
        same prompt again — never from half an answer. Every savepoint this
        request wrote before finishing covers a point no later request will
        ask for, so dominating the previous turn's entry against one of them
        would rank the only reachable state below a pile of unreachable ones,
        and a request that is cancelled or fails would leave the conversation
        worse than it found it.

        Replaced only by a deeper PROMPT-side write of this request. A turn
        whose prompt ended inside the page it resumed at (the same prompt
        sent again: a regeneration, a retry) wrote nothing deeper, so the
        entry it resumed from is still its conversation's newest reachable
        state; dominating it would rank that state for eviction first.
        """
        key = getattr(req, "savepoint_resume_key", None)
        store = self._sched._savepoint_store
        if key is not None and (not wrote_past(req, key) or self.is_shared(key)):
            # A shared context's end is every sibling's resume point; one
            # sibling's deeper turn does not replace it for the others.
            req.savepoint_resume_key = None
            return
        if key is not None and store is not None:
            store.mark_dominated(key)
            window = self.retention
            if window is not None:
                window.note_dominated(key)
            req.savepoint_resume_key = None

    # ── crossing writes: the policy and the evidence that arms it ─────

    @property
    def crossing_policy(self) -> str:
        return crossing_policy_from_flag(
            getattr(self._sched, "_savepoint_crossing_writes", "demand")
        )

    def _crossings_armed(self) -> set[str]:
        armed = self.__dict__.get("_crossings_armed_tenants")
        if armed is None:
            armed = self.__dict__["_crossings_armed_tenants"] = set()
        return armed

    def crossings_wanted(self, tenant_id: str) -> bool:
        """Does ``tenant_id`` write a savepoint at a governor crossing?

        ``always`` and ``never`` answer for every tenant; ``demand`` — the
        default — answers yes only for a tenant :meth:`note_prefix_reach` has
        armed, because a crossing write is a whole recurrent state copied to
        host mid-step and what it buys is a resume for a DIFFERENT
        conversation that shares the prompt up to that crossing. The
        scheduler's arming seam and the commit seam both ask this, for the
        same step, so the forward never emits a state the commit declines.
        """
        policy = self.crossing_policy
        if policy == "always":
            return True
        if policy == "never":
            return False
        return (tenant_id or "") in self._crossings_armed()

    def note_prefix_reach(
        self, tenant_id: str, reach: int, usable: int, limit: int, *, fork: bool = False
    ) -> None:
        """A request's radix walk reached ``reach`` tokens of its prompt; the
        deepest savepoint it could resume from covers ``usable`` (0 for none);
        ``limit`` is the whole pages the prompt itself has.

        THE DEMAND IS VISIBLE WITHOUT THE ENTRY EXISTING. A hit on a crossing
        write cannot be observed while crossings are not written, so arming
        on hits would never fire. But the tree knows how far a prefix is
        shared and the store knows how deep its entries go, and both are
        already on the admission path (the walk's page digests, the best
        match) — so the counterfactual is read directly: a governor line
        between ``usable`` and ``reach`` is a crossing write that WOULD have
        served this request. That is a conversation sharing a prefix with a
        stored one and diverging before its end — the cross-conversation
        case the crossing writes exist for. Two shapes are NOT demand: a
        request whose reach and deepest savepoint sit in one governor span,
        and a request the tree matched to its LAST page (``reach == limit``)
        while holding an entry for it — a conversation resending its own
        history, whose reach past its prompt-end write is its own reply
        (written, if at all, by the decode write; no prefill ever crossed
        there), and which the prompt-end write serves. A full match with NO
        entry at all is demand: a prompt that is a proper prefix of a stored
        one (the shared opening alone) has nothing to resume from.

        Counted every time as ``partial_match_lost_total``, and under the
        ``demand`` policy the first such request arms the tenant's crossing
        writes; from then on its prefills write them, and the NEXT
        conversation sharing that prefix resumes at the crossing.
        """
        chunk = max(1, int(getattr(self._sched, "_savepoint_chunk_size", 1)))
        if int(reach) // chunk <= int(usable) // chunk:
            return
        if int(reach) >= int(limit) and int(usable) > 0:
            return
        tenant = tenant_id or ""
        wanted = self.crossings_wanted(tenant)
        cache_metrics.counter_inc(
            _PARTIAL_MATCH_LOST_TOTAL,
            labels={"crossings": "armed" if wanted else "unarmed"},
        )
        if wanted or fork or self.crossing_policy != "demand":
            # ``fork``: the walk stopped where the tree forks, and this
            # request writes the state at the fork itself — the exact point a
            # crossing on the grid would only approach.
            return
        self._crossings_armed().add(tenant)
        cache_metrics.counter_inc(_CROSSING_ARMED_TOTAL, labels={"signal": "reach_past_savepoint"})
        _LOG.info(
            "savepoint crossing writes armed for tenant %r: a request's radix walk reached "
            "%d tokens of a stored prefix but the deepest savepoint it could resume from "
            "covers %d, so a crossing write at the governor line between them (every %d "
            "tokens) would have served it. This tenant's prefills write crossings from now "
            "on; partial_match_lost_total counts the requests this one and any later ones "
            "cost.",
            tenant or "_global",
            int(reach),
            int(usable),
            chunk,
        )

    def resolve_resume(
        self,
        req: Request,
        tenant_id: str,
        cache_enabled: bool,
    ) -> tuple[object | None, object | None]:
        """Resolve an admission-time savepoint resume for ``req``.

        Returns ``(savepoint_resume_key, savepoint_entry)`` — both
        ``None`` when no host-RAM checkpoint covers a page-aligned
        prefix of the request's prompt. The ``prompt_consumed`` / radix
        ``match_len`` accounting that consumes this result stays inline
        in ``_add_inner`` (the documented off-by-one site).

        An entry lost between the probe and the read (ring overwrite, LRU
        eviction) falls back to the deepest shallower savepoint that can be
        served, counted on ``savepoint.resume_fallback_total``.
        """
        sched = self._sched
        savepoint_resume_key = None
        savepoint_entry = None
        drain = getattr(getattr(sched, "page_table", None), "drain_savepoint_losses", None)
        if drain is not None:
            drain()  # the tree reflects every savepoint lost so far
        if (
            cache_enabled
            and sched._has_recurrent_state()
            and sched._savepoint_store is not None
            and req.prompt_token_ids
        ):
            page_hashes, savepoint_resume_key = probe_resume(sched, req, tenant_id)
            if page_hashes is not None:
                # The walk's reach and the deepest usable savepoint are both
                # in hand: the demand for a crossing write is read here, off
                # the same two numbers, with no lock and no second walk.
                bs = int(sched._savepoint_chain_bs)
                usable = int(savepoint_resume_key.num_tokens) if savepoint_resume_key else 0
                fork = self.note_branch_point(req, tenant_id, page_hashes, usable)
                self.note_prefix_reach(
                    tenant_id,
                    len(page_hashes) * bs,
                    usable,
                    (len(req.cache_token_ids()) // bs) * bs,
                    fork=fork,
                )
            if savepoint_resume_key is not None:
                # The entry this request resumes from is a prefix of every
                # snapshot it will go on to write, so it joins the trail and
                # is dominated by the first of them. This is the seam that
                # makes retention per-CONVERSATION without the server ever
                # having a conversation id: turn N+1 identifies turn N's
                # savepoint by matching its content, and that match is the
                # only link between them that exists.
                req.savepoint_resume_key = savepoint_resume_key
                # ...and that same match is what tells the recency window
                # WHICH conversation just came back. Touched here, at the
                # resume rather than at the first write, so a turn's own
                # prefill time cannot age its conversation out of the
                # window it is in the middle of using.
                window = self.retention
                if window is not None:
                    self._trail_of_req[int(req.request_id)] = window.note_resume(
                        savepoint_resume_key
                    )
                # START THE READ HERE, which is the earliest moment anything
                # knows it is wanted. Everything between this line and the
                # ``get`` below — the reach probe, two debug renders, the
                # radix walk in ``resolve_match`` — is work the drive can be
                # spinning under. A no-op when the entry is resident, when the
                # tier is off, or when nothing has been prefetched; it never
                # raises, because a prefetch that cannot start leaves the
                # request doing exactly what it did before.
                prefetch = getattr(sched._savepoint_store, "prefetch", None)
                if prefetch is not None and prefetch(savepoint_resume_key):
                    self._prefetched_for[int(req.request_id)] = savepoint_resume_key
            # ``isEnabledFor`` FIRST, and the probe inside it. ``probe_reach``
            # takes the store lock and sorts the tenant's stored lengths — on
            # the admission path, for every request, to fill in arguments the
            # logger discards when DEBUG is off. Python evaluates a call's
            # arguments before the call, so the level check inside ``debug()``
            # is too late to save any of it, and the lock is contended with
            # the store's own writers rather than merely costing CPU.
            if page_hashes is not None and _LOG.isEnabledFor(logging.DEBUG):
                _reach, _stored = sched._savepoint_store.probe_reach(tenant_id, page_hashes)
                # DEBUG, not INFO: this fires on EVERY request, and a
                # per-request log line in the serving path is exactly the
                # observability tax the engine is protected from.
                _LOG.debug(
                    "savepoint probe: req=%s prompt_len=%s radix_reach=%s stored_desc=%s hit=%s",
                    req.request_id,
                    len(req.cache_token_ids()),
                    _reach,
                    _stored,
                    savepoint_resume_key.num_tokens if savepoint_resume_key else None,
                )
            _LOG.debug(
                "savepoint best_match: req=%s tenant=%s prompt_len=%s key=%s store_entries=%s",
                req.request_id,
                tenant_id or "_global",
                len(req.prompt_token_ids),
                savepoint_resume_key,
                len(sched._savepoint_store),
            )
            if savepoint_resume_key is not None:
                # The entry, from RAM, a landed prefetch or the disk tier — or,
                # when the deepest one is gone between the probe and here (a
                # ring overwrite, an LRU eviction), the deepest SHALLOWER one
                # on the same path. Never the whole match discarded.
                savepoint_resume_key, savepoint_entry = serve_or_fall_back(
                    self, req, tenant_id, savepoint_resume_key, page_hashes
                )
                req.savepoint_resume_key = savepoint_resume_key
            if savepoint_entry is None and page_hashes:
                # A TOTAL LOSS: the tree reaches this prompt's KV but no savepoint
                # on the path can resume it, so the match is capped at zero and
                # the prompt re-prefills from token 0 (the retention harness's gate).
                cache_metrics.counter_inc(
                    "arbi_serve.savepoint.hybrid_no_savepoint_fallback_total",
                    labels={"tenant": tenant_id or "_global"},
                )
        if savepoint_entry is not None and savepoint_resume_key is not None:
            # WHICH savepoint a resume restores from is the number that decides
            # how many are worth keeping. ``depth`` is how many whole
            # ``chunk_prefill`` spans of prompt the resume leaves to
            # re-prefill, so 0 means "within one chunk of the end" and a
            # distribution concentrated at 0 means a short ring loses nothing.
            prompt_len = len(req.cache_token_ids())
            depth = max(0, prompt_len - int(savepoint_entry.num_tokens_covered)) // max(
                1, int(sched._savepoint_chunk_size)
            )
            cache_metrics.counter_inc(
                "arbi_serve.savepoint.resume_depth_total",
                labels={"depth": str(min(depth, 16))},
            )
            # WHICH KIND of savepoint served this resume. The decode write
            # costs a whole savepoint per KV-page crossing of the reply — a
            # ring hand-out, a region, and the bytes — and doubles the ring's
            # staging term, so whether it is worth keeping is a question about
            # how often a resume lands on one rather than on the prompt-end
            # entry the same turn wrote for free. Classifying a run by hand
            # answered it once; this makes the engine answer it every time.
            #
            # Through the retention counters rather than a name of its own,
            # because that family already forwards to OTEL as
            # ``savepoint_retention_total{counter}``. A savepoint metric that
            # reaches only an INFO line on the box is the exact shape
            # ``tests/test_savepoint_metric_forwarding_guard.py`` exists to
            # refuse, and it is right to.
            self.retention_counters._bump(
                "resumes_from_decode"
                if getattr(savepoint_entry, "from_decode", False)
                else "resumes_from_prompt_end"
            )
            if self.is_shared(savepoint_resume_key):
                # A subset of the two above: the entry is a shared context's end.
                cache_metrics.counter_inc("arbi_serve.savepoint.retention.resumes_from_fork")
            _LOG.info(
                "savepoint resume: req=%s covered=%s of prompt_len=%s depth_from_newest=%s "
                "entries=%s",
                req.request_id,
                savepoint_entry.num_tokens_covered,
                prompt_len,
                depth,
                len(sched._savepoint_store),
            )
        return savepoint_resume_key, savepoint_entry

    def resolve_match(
        self,
        req: Request,
        tenant_id: str,
        cache_enabled: bool,
        savepoint_resume_key,
        savepoint_entry,
        *,
        retain_enabled: bool | None = None,
        readmit: bool = False,
        page_budget_cap: int | None = None,
    ) -> tuple[int, object | None, object | None]:
        """Run the radix ``add_request`` + savepoint reconciliation.

        Registers the request with the match CAPPED at the savepoint's
        coverage — at zero on a hybrid with no savepoint, so a match is never
        taken only to be discarded — and, when the radix reaches fewer pages
        than the savepoint covers, falls back to the deepest SHALLOWER
        savepoint on the same path rather than to a full re-prefill. The hit
        is counted once, for the match served.

        ``retain_enabled`` is the request's OTHER cache flag — may its own
        pages be kept — and it is carried UNTOUCHED through every retry. That refusal is about what this request may
        READ; the pages it writes are its own and correctly computed, so
        revoking retention with the match was a conflation, and the one that
        made a warm prefix cost a hybrid request its park. ``None`` follows
        ``cache_enabled``, which is what the privacy opt-out means.

        ``readmit`` routes the registration through
        :meth:`RadixPageTable.readmit_preempted` instead of ``add_request``
        — the preempt path, where the request is ALREADY registered and the
        seam has to free its pages and carry its cache identity across the
        drop. Everything downstream (the coverage cross-check, the fallback)
        is identical, which is the point of routing it here
        rather than restating the reconciliation at the preempt site.

        ``page_budget_cap`` is a second, independent cap on the match, in
        tokens, MIN-ed with the recurrent-coverage cap. Preemption sets it
        to the part of the victim it must genuinely give back (a re-matched
        page is ref-ed up and stops being evictable, so an uncapped
        re-match frees nothing for the request the preemption was for);
        ``None`` on the ordinary admission path, which has no such budget.

        Returns the FINAL ``(match_len, savepoint_entry, savepoint_resume_key)``.
        The caller (:meth:`Scheduler._add_inner`) consumes ``match_len``
        to credit ``prompt_consumed`` inline — that ``prompt_consumed``
        write (the documented off-by-one site) stays in the scheduler.
        """
        sched = self._sched
        # #797 — RECURRENT-COVERAGE CAP (the other half of the cross-check
        # below). On a hybrid model the radix match and the savepoint are two
        # INDEPENDENTLY-EVICTED caches over the same prefix: the radix holds
        # the KV, the savepoint holds the recurrent (GDN / Mamba / ShortConv)
        # state. ``prompt_consumed`` is a SINGLE number — it skips prefill for
        # BOTH — so it is only sound at a token both caches reach.
        #
        # The savepoint store is a bounded LRU and ``best_match_hashes`` is
        # longest-first-hit, so under load it happily returns a SHORT savepoint
        # (say chunk 0 / 512 tokens) for a prompt whose radix pages still cover
        # 14 848. Crediting the full page-aligned match then skips the
        # recurrent layers over ``[coverage, match_len)`` — those tokens never
        # pass through GDN at all — while the attention layers read the aliased
        # KV. Cap the match at the savepoint's coverage so both caches resume
        # from the SAME token. The cap floors to a page, so a non-page-aligned
        # coverage lands below it and the shortfall below falls back.
        hybrid = sched._has_recurrent_state()
        # A table that counts hits apart from the walk counts the one served.
        count = getattr(sched.page_table, "count_prefix_hit", None)
        hit_kw = {"count_hit": False} if count is not None else {}
        while True:
            # A hybrid resumes ONLY at a savepoint, so with none the match is
            # capped at zero rather than taken and then discarded.
            cap = (
                (int(savepoint_entry.num_tokens_covered) if savepoint_entry else 0)
                if hybrid
                else None
            )
            max_match_len = resume_match_limit(req, cap, page_budget_cap)
            if readmit:
                match_len = sched.page_table.readmit_preempted(
                    req.request_id,
                    req.cache_token_ids(),
                    max_match_len=max_match_len,
                    **hit_kw,
                )
            else:
                match_len = sched.page_table.add_request(
                    req.request_id,
                    prompt_token_ids=req.cache_token_ids(),
                    tenant_id=tenant_id,
                    cache_enabled=cache_enabled,
                    retain_enabled=retain_enabled,
                    max_match_len=max_match_len,
                    **hit_kw,
                )
            # A retry re-registers through the seam that carries the identity
            # (tenant, both cache flags) of the registration just made.
            readmit = True
            if savepoint_entry is None or match_len >= savepoint_entry.num_tokens_covered:
                break
            # Task #143 — KV-COVERAGE SHORTFALL: the radix reached fewer pages
            # than the savepoint covers (a tier page not restored, the preempt
            # re-bind's page budget). Positions past ``match_len`` have no KV,
            # so this savepoint cannot be used — but a SHALLOWER one on the
            # same path usually can, and the match falls back to it instead of
            # being discarded whole.
            cache_metrics.counter_inc(
                "arbi_serve.savepoint.kv_coverage_shortfall_total",
                labels={"tenant": tenant_id or "_global"},
            )
            savepoint_resume_key, savepoint_entry = live_resume_at_or_below(
                self, req, tenant_id, int(match_len)
            )
            if savepoint_entry is not None:
                cache_metrics.counter_inc(
                    "arbi_serve.savepoint.resume_fallback_total", labels={"reason": "kv_shortfall"}
                )
            req.savepoint_resume_key = savepoint_resume_key
        # Counted once, for the match actually SERVED (never before a cut).
        if count is not None:
            count(tenant_id, int(match_len))
        return match_len, savepoint_entry, savepoint_resume_key

    def queue_resume(
        self,
        req: Request,
        tenant_id: str,
        savepoint_entry,
        match_len: int,
    ) -> None:
        """Queue the resolved savepoint restore + bump ``prompt_consumed``.

        Order-critical: the caller invokes this AFTER
        ``alloc_recurrent_state`` (the slab row must exist before we can
        write into it) and BEFORE the request enters ``Scheduler.waiting``
        (so the next start-of-step flush sees the queue entry). The only
        ``prompt_consumed`` mutation here is the savepoint-coverage bump
        (savepoint-specific, not the radix off-by-one).
        """
        sched = self._sched
        queue_resume = getattr(sched.pool, "queue_savepoint_resume", None)
        if queue_resume is not None:
            queue_resume(req.request_id, savepoint_entry.tensors)
        _LOG.debug(
            "savepoint resume: req=%s tenant=%s coverage=%s match_len=%s",
            req.request_id,
            tenant_id or "_global",
            savepoint_entry.num_tokens_covered,
            match_len,
        )
        # INVARIANT (#797): the KV credit and the recurrent state MUST resume
        # from the same token.
        #
        # This used to be a permissive ``if coverage > prompt_consumed:
        # prompt_consumed = coverage`` — a one-sided max() that raised the
        # credit when the savepoint ran AHEAD of the radix but silently
        # accepted the far more common opposite skew (radix ahead of the
        # savepoint), leaving ``prompt_consumed = match_len`` while the
        # recurrent state sat at ``coverage``. Tokens ``[coverage, match_len)``
        # then bypassed the recurrent layers entirely.
        #
        # ``resolve_match`` now caps the radix match at ``coverage`` and drops
        # the savepoint on any shortfall, so the two are EQUAL here by
        # construction. Assert it rather than paper over it: if a future change
        # reintroduces the skew this must fail loudly, not corrupt output.
        coverage = int(savepoint_entry.num_tokens_covered)
        if coverage != req.prompt_consumed:
            raise RuntimeError(
                f"savepoint resume invariant violated (#797): req "
                f"{req.request_id} credited prompt_consumed="
                f"{req.prompt_consumed} (radix match_len={match_len}) but the "
                f"restored recurrent savepoint only covers {coverage} tokens. "
                f"Tokens [{min(coverage, req.prompt_consumed)}, "
                f"{max(coverage, req.prompt_consumed)}) would skip the "
                f"recurrent layers. resolve_match must cap the radix match at "
                f"the savepoint's coverage."
            )
        cache_metrics.counter_inc(
            "arbi_serve.savepoint.resume_total",
            labels={"tenant": tenant_id or "_global"},
        )

    def snapshot_decode_boundary(self, req: Request, snapshot_fn) -> None:
        """Write a savepoint DURING generation, at a KV-page boundary.

        Without this, the deepest savepoint a turn leaves stops at its
        PROMPT's end, so the next turn re-prefills the whole reply before it
        reaches a new token. The KV for those tokens is already cached —
        ``Scheduler.finished`` commits ``cache_token_ids() + output_token_ids``
        for exactly that reason — so it is the recurrent half alone that
        forces the re-read, and this closes it.

        WHICH LENGTH THE SLAB IS AT
        ===========================
        Called from the DECODE branch of ``commit_state``, before this step's
        sampled token is appended (``commit_output``). At that point the slab
        has absorbed the prompt and every ALREADY-APPENDED output token, so
        the absorbed length is exactly ``len(ids) + len(output_token_ids)``
        and the key digests the very stream those tokens came from.

        That correspondence holds only while the optimistic advances are at
        rest. ``_mtp_optimistic_len`` (an assume-all-accepted verify advance)
        and ``_async_optimistic_len`` (a host commit deferred one tick) both
        move ``total_length`` ahead of the ids that exist, so a boundary read
        during either would name a length whose tokens cannot be hashed. Both
        are refused BY NAME rather than approximated: a savepoint keyed one
        token off is a wrong state under a right key, which is the one
        failure this machinery may never produce.
        """
        sched = self._sched
        from arbi_serve.runtime_flags import runtime_flags

        if not runtime_flags().savepoint_decode_write:
            _DECODE_WRITE.refuse("savepoint_decode_write off")
            return
        if not bool(getattr(req.sampling, "cache_enabled", True)):
            _DECODE_WRITE.refuse("cache disabled for this request")
            return
        # A think block is STREAMED to the client and STRIPPED from the
        # transcript the next turn sends, so every decode position of a
        # reasoning turn holds a state that absorbed tokens no later prefix
        # contains — unless the client replays the turn as it was served.
        # Writing anyway spends a ring slot on an entry whose stream cannot
        # recur, and ring slots are what retention is made of.
        #
        # The flag is read off THIS request, which describes how the client
        # rendered the LAST turn. That is the only evidence available at write
        # time, and replay is a client-level convention rather than a per-turn
        # choice, so it predicts the next turn. Being wrong costs a slot, never
        # a wrong state: reachability is decided by content match, so an entry
        # whose stream never recurs is simply never returned.
        #
        # A NON-reasoning turn needs no replay at all — its output IS the
        # content the next turn echoes — so the flag is inert there, which is
        # why this is a conjunction and not a bare check on the flag.
        if int(getattr(req, "reasoning_tokens", 0) or 0) and not bool(
            getattr(req.sampling, "replay_reasoning", False)
        ):
            _DECODE_WRITE.refuse("reasoning turn whose client does not replay it")
            return
        if int(getattr(req, "_mtp_optimistic_len", 0) or 0):
            _DECODE_WRITE.refuse("mtp verify advance in flight — ids trail the slab")
            return
        if int(getattr(req, "_async_optimistic_len", 0) or 0):
            _DECODE_WRITE.refuse("async output deferred — ids trail the slab")
            return
        if int(getattr(req, "context_consumed", 0) or 0):
            # Injected context occupies KV slots but never enters
            # ``output_token_ids``, so the stream the key would digest is not
            # the stream the slab absorbed.
            _DECODE_WRITE.refuse("injected context is not in the keyed stream")
            return
        if getattr(req, "fold_history_off_grid", False):
            # Sticky for the request: one off-grid prefill chunk leaves every
            # later position holding a state no uncut prefill produces, and a
            # decode boundary after it would be page-aligned, pass every
            # positional check, and name a state it does not hold.
            _DECODE_WRITE.refuse("this request's fold history left the grid")
            return
        prompt_ids = req.cache_token_ids()
        absorbed = len(prompt_ids) + len(req.output_token_ids)
        block = int(sched.cache_cfg.block_size)
        if absorbed <= 0 or absorbed % block != 0:
            # Not ON the grid. Under speculative decoding a step commits
            # several accepted tokens at once, so the length STRIDES over the
            # grid instead of landing on it, and an equality test almost never
            # holds. Named so the distinction between "did not run" and "ran
            # and declined" is readable from the counter alone.
            _DECODE_WRITE.refuse("length strode past the resume grid")
            return
        if absorbed == self._last_decode_boundary.get(req.request_id):
            return  # this row was committed again without advancing
        self._last_decode_boundary[req.request_id] = absorbed
        _DECODE_WRITE.fired = 1
        self.snapshot_at_boundary(
            req=req,
            tenant_id=sched._tenant_id_for(req),
            snapshot_fn=snapshot_fn,
            boundary=absorbed,
            ids=prompt_ids + list(req.output_token_ids),
            from_decode=True,
        )

    def snapshot_at_boundary(
        self,
        *,
        req: Request,
        tenant_id: str,
        snapshot_fn,
        boundary: int,
        staged=None,
        ids: list[int] | None = None,
        from_decode: bool = False,
        shared: bool = False,
        off_trail: bool = False,
    ) -> None:
        """Take a recurrent-state snapshot of the state after ``boundary`` tokens.

        ``shared`` marks a state at a context several conversations continue
        (a fork of the radix tree): no one sibling's later turn dominates it.
        ``off_trail`` keeps it out of the request's own write trail, which its
        prompt-end write would otherwise supersede — the fork is not a point on
        the way to this request's prompt end, it is where the others branch.

        ``ids`` is the token stream the key digests, defaulting to the
        request's prompt. A boundary that reaches past the prompt — a
        savepoint written during generation — passes prompt + output, which
        is the same stream ``Scheduler.finished`` already keys the KV half on.

        Called from :meth:`snapshot_crossed_boundaries` for the step that
        just ended at ``boundary``. Looks up the request's slab row,
        clones each per-(layer_idx, attribute) tensor slice into host
        RAM, digests the ``boundary``-token prefix, and ``put``s the
        resulting :class:`SavepointEntry` into the store.

        ASYNC D2H.
        ==========
        The snapshot is issued via ``snapshot_recurrent_row(async_copy=True)``
        + ``snapshot_recurrent_event()``. This issues one
        ``non_blocking=True`` D2H per (layer × attr) into a pinned
        host buffer and records a single CUDA event on the current
        stream. The commit critical path returns BEFORE the D2H is
        complete on the host. The event is attached to the
        :class:`SavepointEntry`; the store's ``get`` / eviction paths
        call ``entry.synchronize()`` to barrier on it before reading
        or freeing the host buffers.

        Why this is correct without a chunk-N stream sync:

          * The engine's slab writes (recurrent kernels in chunk N's
            forward) and our D2H copy are on the SAME stream
            (``torch.cuda.current_stream(pool.device)``). CUDA
            stream-ordering guarantees the writes happen-before the
            D2H — we don't need a host-side fence between them.
          * Chunk N+1's forward is also on the same stream and
            happens-after the D2H in stream order, so the slab is
            free to be overwritten without affecting the D2H source
            (the GPU will not start chunk N+1's writes until the
            D2H read of chunk N's content has been queued).
          * The host bytes are guaranteed to be present only after
            ``cudaEventSynchronize`` — which the consumer side
            (admission-time restore, eviction) performs.

        Falls back to synchronous on CPU-only pools (test fixtures);
        ``snapshot_recurrent_event`` returns ``None`` and the entry's
        ``pending_event`` stays ``None``.

        Returns silently on a no-recurrent-pool model (``snapshot_fn``
        returning an empty dict — we don't ``put`` empty entries).
        """
        from arbi_serve.cache.recurrent_savepoint import (
            ChainPrefixHasher,
            SavepointEntry,
            SavepointKey,
            hash_token_prefix,
        )

        sched = self._sched
        if sched._savepoint_store is None:
            return  # caller already gated, defensive
        if staged is not None:
            # MID-step route: the buffers were filled by the forward between
            # the two segments of its split fold, so there is nothing left to
            # copy — only the fence to record and the entry to build. The
            # provenance stamp came from the ring hand-out at open time, for
            # the same reason it does below: the store must be able to refuse
            # this entry once its slot is reused.
            host_tensors = staged.tensors
            stamp = staged.stamp
            ring = staged.ring
        else:
            # Async-copy keyword. The pool falls back to synchronous on
            # non-CUDA backends (test fixtures with device='cpu') so this
            # is always safe to pass.
            #
            # The reclaim hint is passed only when there IS one, so a
            # ``snapshot_fn`` that predates it — the offload manager's, a test
            # double — is called exactly as before rather than having to grow a
            # parameter it would ignore.
            reuse = (
                None
                if off_trail
                else self._reclaimable.get((int(req.request_id), bool(from_decode)))
            )
            host_tensors = (
                snapshot_fn(req.request_id, async_copy=True, reuse_stamp=reuse)
                if reuse is not None
                else snapshot_fn(req.request_id, async_copy=True)
            )
        if not host_tensors:
            # Pure-attention model that happened to expose
            # ``snapshot_recurrent_row`` but has no recurrent views
            # registered — skip.
            return
        if staged is not None and getattr(staged, "fence", None) is not None:
            # The boundary snapshot's copies rode the spill stream one layer
            # at a time; its own fence is the last of them, and an event
            # recorded on the current stream here would fence nothing.
            pending_event = staged.fence
        else:
            # Record the fence event on the same stream the D2H copies
            # were issued on. ``None`` when CUDA is unavailable (test
            # fixtures) — the entry's ``pending_event`` stays ``None``
            # and ``synchronize()`` is a no-op.
            event_fn = getattr(sched.pool, "snapshot_recurrent_event", None)
            pending_event = event_fn() if event_fn is not None else None
        if staged is None:
            # On-device ring provenance, read exactly like the fence above: the
            # snapshot just landed in a ring slot, and the entry must carry
            # which hand-out owns it so the store can refuse it once the slot
            # is reused.
            stamp_fn = getattr(sched.pool, "savepoint_ring_stamp", None)
            stamp = stamp_fn() if stamp_fn is not None else None
            ring = sched.pool.savepoint_ring() if hasattr(sched.pool, "savepoint_ring") else None
        ids = req.cache_token_ids() if ids is None else ids
        chain_bs = sched._savepoint_chain_bs
        if chain_bs is not None:
            # Chain mode: fold only the NEW pages since the previous
            # snapshot into the request's running Merkle chain —
            # O(prompt) per request total, and byte-identical to the
            # radix node's ``phash`` for the same (tenant, prefix) once
            # ``commit_full_pages`` creates it (same pure function).
            hasher = req.savepoint_chain
            if hasher is None:
                hasher = ChainPrefixHasher(tenant_id, chain_bs)
                req.savepoint_chain = hasher
            prefix_hash = hasher.digest_at(ids, boundary)
        else:
            prefix_hash = hash_token_prefix(ids, boundary)
        key = SavepointKey(
            tenant_id=tenant_id,
            prefix_hash=prefix_hash,
            num_tokens=boundary,
        )
        entry = SavepointEntry(
            tensors=host_tensors,
            num_tokens_covered=boundary,
            pending_event=pending_event,
            from_decode=bool(from_decode),
            prompt_end=not (from_decode or off_trail)
            and boundary >= len(req.cache_token_ids()) - _page_of(sched) + 1,
            ring=ring if stamp is not None else None,
            ring_slot=stamp[0] if stamp is not None else -1,
            ring_gen=stamp[1] if stamp is not None else 0,
        )
        admitted = sched._savepoint_store.put(key, entry)
        if admitted:
            # The pair's write half: only an ADMITTED savepoint lets this
            # request's KV be published to its depth (radix_pagetable_savepoints).
            note = getattr(getattr(sched, "page_table", None), "note_savepoint", None)
            if note is not None:
                note(req.request_id, boundary, key)
        if admitted and shared:
            self.note_shared(key)
        if admitted and off_trail:
            window = self.retention
            if window is not None:
                self._trail_of_req[int(req.request_id)] = window.note_write(
                    key, trail_id=self._trail_of_req.get(int(req.request_id))
                )
            cache_metrics.counter_inc(
                "arbi_serve.savepoint.snapshot_total",
                labels={"tenant": tenant_id or "_global"},
            )
        elif admitted:
            # This request's OWN earlier snapshots are strict prefixes of
            # this one and are now unreachable — ``longest_prefix`` takes the
            # deepest match — so they are dominated immediately. The entry
            # this request RESUMED from is deliberately NOT: it stays live
            # until completion, because a request that stops early must leave
            # the previous turn's savepoint as it found it, and every
            # intermediate written on the way to a reply covers a point
            # (half an answer) that no later request will ever ask for.
            trail = req.savepoint_keys
            if trail is None:
                trail = []
                req.savepoint_keys = trail
            # A PROMPT-END write supersedes EVERYTHING older: the prompt is
            # echoed by every client on every turn, so an entry covering it is
            # reachable under any convention and strictly dominates the
            # shallower ones.
            #
            # A decode write supersedes only older DECODE entries of the same
            # request. It must never demote the prompt-end entry, whose
            # reachability does not depend on how the next turn renders the
            # assistant turn — doing so put the usable entry at the front of
            # the eviction queue, a measured regression. But its own shallower
            # decode entries ARE strictly dominated for a linear continuation:
            # any prompt that reaches page N also reaches page N+1 of the same
            # reply. They stay live (a regeneration or a branch from mid-reply
            # still asks for them) and simply sort for eviction first.
            decode_trail = req.savepoint_decode_keys
            if decode_trail is None:
                decode_trail = []
                req.savepoint_decode_keys = decode_trail
            superseded = record_savepoint_write(trail, decode_trail, key, from_decode=from_decode)
            for older in superseded:
                sched._savepoint_store.mark_dominated(older)
            # This entry is now the newest one the request's NEXT write on this
            # side will supersede, so it is the slot that write may overwrite in
            # place. Recorded only on an admitted put: a refused one dominated
            # nothing, and pointing the hint at it would reclaim a slot whose
            # entry is still the one to beat. A prompt-end write cleared the
            # decode trail, so its decode hint goes with it — exactly as
            # ``record_savepoint_write`` clears the list.
            rid = int(req.request_id)
            if stamp is not None:
                self._reclaimable[(rid, bool(from_decode))] = (int(stamp[0]), int(stamp[1]))
            else:
                self._reclaimable.pop((rid, bool(from_decode)), None)
            if not from_decode:
                self._reclaimable.pop((rid, True), None)
            # The recency window reads the SAME trail: this key joins the
            # conversation the request resumed from (or opens one), and the
            # entries it supersedes stop paying for resident bytes, which is
            # the denominator of how many conversations the window holds.
            window = self.retention
            if window is not None:
                self._trail_of_req[int(req.request_id)] = window.note_write(
                    key, trail_id=self._trail_of_req.get(int(req.request_id))
                )
                for older in superseded:
                    window.note_dominated(older)
            cache_metrics.counter_inc(
                "arbi_serve.savepoint.snapshot_total",
                labels={"tenant": tenant_id or "_global"},
            )
            _LOG.debug(
                "savepoint snapshot: req=%s tenant=%s boundary=%s nbytes=%s",
                req.request_id,
                tenant_id or "_global",
                boundary,
                entry.nbytes,
            )
# ---- savepoint_arming.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Arming a step's savepoint boundaries for the forward (``Scheduler._arm_fold_split``).

Split from :mod:`arbi_serve.scheduler.scheduler` along the seam between
building the slate and deciding which of its prefill rows' states the
forward must emit. It runs once per ``schedule()``, over the finished slate.

EVERY ROW THAT OWES A WRITE IS ARMED
====================================
A savepoint boundary lies inside a prefill step, where the state exists only
while one kernel sweeps through it, so a boundary the forward is not told to
emit is lost for good. Several rows of one step can owe one: concurrent
chats whose prompts complete together each need their prompt-end state (the
one their next turn resumes from), and a row passing a shared context's end
owes the state there too. Each (row, boundary) is armed into its own staging
slot and its own ring slot; the forward emits them in the one launch.

When a step owes more than the pool can stage (its
``boundary_snapshot_capacity``), prompt-end writes go first — each is a
conversation's only resumable state — then shared contexts' ends, then
governor crossings; the rest are refused by name.
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING

from arbi_serve.cache import _metrics as cache_metrics
from arbi_serve.cache.recurrent_savepoint import FoldSplitUnaligned, savepoint_fold_split
from arbi_serve.flag_truth import FiringWindow, path_counter
from arbi_serve.scheduler.savepoint_trail import boundary_already_stored

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request

_LOG = logging.getLogger("arbi_serve.scheduler")

#: Whether this step armed the forward's fold split, and when it did not,
#: WHY. The window is SERVE: it moves on every ``schedule()`` call that reaches
#: the arming site, so a zero on BOTH halves means the site never ran — an
#: earlier and different failure from "no step had a boundary", which reads as a
#: nonzero ``refused`` with the reason attached. Nothing else can distinguish
#: those two, because the observable they share is "no snapshot was written".
_FOLD_SPLIT_ARMED = path_counter("savepoint_fold_split_armed", FiringWindow.SERVE)

#: Arming priority: a prompt's end, a shared context's end, a crossing.
_PROMPT_END, _BRANCH, _CROSSING = 0, 1, 2


class _FoldSplitArmingMixin:
    """``_arm_fold_split`` and the crossing predicate it shares with the commit."""

    _fold_split_armed: tuple[int, int, int] | None = None
    _fold_splits_armed: tuple = ()

    def _arm_fold_split(self, slate: list[tuple[Request, int]]) -> None:
        """Arm the forward's fold split for every prefill row boundary this step owes.

        Called ONCE per ``schedule()``, over the finished slate, because the
        numbers it needs are the step's final ones: a row's chunk start
        (``prompt_consumed``) and the width the budget and the fold-grid cut
        left it. Deciding earlier would key on a width three later caps can
        still narrow.

        :func:`~arbi_serve.cache.recurrent_savepoint.savepoint_fold_split`
        answers WHERE a row's primary write lands, and it is the same call
        :meth:`~arbi_serve.scheduler.savepoint_boundary_commit._BoundaryCommitMixin.
        snapshot_crossed_boundaries` makes at commit — the forward and the
        label must never come from two derivations; a shared context's end is
        the snapshotter's record of the row's radix walk, read by both sides
        the same way. Arming opens the host buffers the forward stages into
        (:meth:`~arbi_serve.cache._boundary_snapshots.BoundarySnapshotMixin.
        open_boundary_snapshot`) with the token offset the emit lands at.

        Every refusal is named and counted on ``savepoint_fold_split_armed``.
        """
        self._fold_split_armed = None
        self._fold_splits_armed = ()
        _discard_outlived_snapshots(self.pool)
        if self._savepoint_store is None or self._savepoint_page_bs <= 0:
            _FOLD_SPLIT_ARMED.refuse("no savepoint store: nothing would read a boundary")
            return
        prefills = [(req, n) for req, n in slate if req.is_prefill and n > 0]
        if not prefills:
            _FOLD_SPLIT_ARMED.refuse("no prefill row in the slate")
            return
        pool = self.pool
        capacity_fn = getattr(pool, "boundary_snapshot_capacity", None)
        capacity = max(1, int(capacity_fn())) if capacity_fn is not None else 1
        by_row = getattr(pool, "closes_by_row", None)
        # A fork's state is labelled by the commit that takes the row's own
        # snapshots; a pool whose commit takes one snapshot lazily cannot.
        snapshotter = self._savepoint_snapshotter if by_row is not None and by_row() else None
        wants: list[tuple[int, int, Request, int, int]] = []
        forks_this_step: set = set()
        for order, (req, n) in enumerate(prefills):
            if not bool(getattr(req.sampling, "cache_enabled", True)):
                # The commit labels no savepoint for a request whose cache is
                # off, so a snapshot armed for it would never be closed.
                _FOLD_SPLIT_ARMED.refuse("this request's cache is off: its commit writes nothing")
                continue
            if req.fold_history_off_grid:
                # A chunk of this request already ended off the fold grid, so
                # every position from there on holds a state no uncut prefill
                # produces. The next crossing will still be page-aligned and
                # will still pass every positional check — which is exactly
                # why this has to be refused HERE, by history, rather than
                # left to a check that can only see the position.
                _FOLD_SPLIT_ARMED.refuse("this request's fold history left the grid")
                continue
            pc_before = int(req.prompt_consumed)
            pc_after = pc_before + int(n)
            # The step that absorbs the prompt's last token writes even when
            # it crosses no governor line: its boundary is the deepest state
            # the prompt's next admission can resume from.
            completes = pc_after >= len(req.prompt_token_ids)
            try:
                boundary = savepoint_fold_split(
                    pc_before=pc_before,
                    pc_after=pc_after,
                    chunk_size=self._savepoint_chunk_size,
                    resume_grid=self._savepoint_page_bs,
                    fold_grid=max(1, self._savepoint_fold_grid),
                    completes_prompt=completes,
                    crossings=self._crossings_wanted(req),
                )
            except FoldSplitUnaligned as exc:
                # The scheduler's own fold-grid cut is what makes this
                # unreachable; reaching it means that cut stopped running, so
                # it is logged in full rather than counted away.
                _LOG.warning("savepoint fold split refused: %s", exc)
                _FOLD_SPLIT_ARMED.refuse("offset off the fold grid")
                continue
            primary = boundary
            if boundary is None:
                _FOLD_SPLIT_ARMED.refuse(
                    "no resume-grid boundary inside this step"
                    if self._crossings_wanted(req)
                    else "no boundary this tenant writes: crossings unarmed, prompt not completed"
                )
            elif boundary == pc_before and boundary_already_stored(req, boundary):
                # The prompt's last page boundary is exactly where this step
                # begins, and the step before wrote that state as its own
                # end. Arming would spend a ring hand-out on bytes the store
                # already holds; the commit asks the same predicate and counts
                # the skip by name.
                _FOLD_SPLIT_ARMED.refuse("the state at the step's start is already stored")
            else:
                wants.append(
                    (_PROMPT_END if completes else _CROSSING, order, req, pc_before, boundary)
                )
            branch = (
                snapshotter.branch_boundary_in(req, pc_before, pc_after)
                if snapshotter is not None
                else None
            )
            if branch is None or branch == primary:
                continue
            fork = snapshotter.branch_key_of(req)
            if fork in forks_this_step:
                # Siblings prefilling side by side reach the same fork; one
                # state serves them all.
                snapshotter.clear_branch_point(req)
                _FOLD_SPLIT_ARMED.refuse("another row of this step writes the same fork")
                continue
            forks_this_step.add(fork)
            wants.append((_BRANCH, order, req, pc_before, branch))
        wants.sort(key=lambda w: (w[0], w[1]))
        open_fn = getattr(pool, "open_boundary_snapshot", None)
        armed: list[tuple[int, int, int]] = []
        for _prio, _order, req, pc_before, boundary in wants:
            if len(armed) >= capacity:
                _FOLD_SPLIT_ARMED.refuse("every boundary slot of this step is taken")
                continue
            if open_fn is None:
                _FOLD_SPLIT_ARMED.refuse("pool cannot open a boundary snapshot")
                continue
            # A boundary at the step's END is armed like any other: the kernel
            # emits the state after its last chunk and the layers spill it
            # while the forward is still running. The step's first open
            # replaces whatever an earlier step left open, so a snapshot never
            # outlives the step it was laid out for.
            snap = (
                open_fn(req.request_id, boundary, boundary - pc_before)
                if not armed
                else open_fn(req.request_id, boundary, boundary - pc_before, append=True)
            )
            if snap is None:
                _FOLD_SPLIT_ARMED.refuse("no recurrent row to snapshot")
                continue
            armed.append((req.request_id, boundary - pc_before, boundary))
            _FOLD_SPLIT_ARMED.fired = 1
        if armed:
            self._fold_split_armed = armed[0]
            self._fold_splits_armed = tuple(armed)

    def _crossings_wanted(self, req: Request) -> bool:
        """Does this request's tenant write savepoints at governor crossings?

        The commit seam asks the snapshotter the same question for the same
        step (:meth:`~arbi_serve.scheduler.savepoint_admission.
        SavepointSnapshotter.crossings_wanted`), which is what keeps the
        forward from emitting a state the commit then declines to label.
        """
        snapshotter = self._savepoint_snapshotter
        if snapshotter is None:
            return True
        return bool(snapshotter.crossings_wanted(self._tenant_id_for(req)))


def _discard_outlived_snapshots(pool) -> None:
    """Drop any boundary snapshot an earlier step left open, before this step arms.

    The commit takes each row's snapshots, so one still open here belongs to a
    row whose commit labelled nothing. Left in place, the next forward would
    stage it again (state of a later step, under the earlier step's boundary)
    and resolve the slab row of a request that may have finished since —
    ``KeyError: no row for request N`` on a step that armed nothing itself.
    An open with ``append=False`` already discards; a step that arms nothing
    never opens, so the discard has to happen here.
    """
    plans_fn = getattr(pool, "boundary_plans", None)
    stale = plans_fn() if plans_fn is not None else ()
    if not isinstance(stale, tuple) or not stale:
        return
    pool.discard_boundary_snapshots()
    cache_metrics.counter_inc(
        "arbi_serve.savepoint.snapshot_skipped_total",
        labels={"reason": "outlived_its_step"},
        value=len(stale),
    )


__all__ = ["_FOLD_SPLIT_ARMED", "_FoldSplitArmingMixin"]
# ---- savepoint_boundary_commit.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The commit side of a prefill step's savepoint writes: which boundaries, which states.

Split from :mod:`arbi_serve.scheduler.savepoint_admission` along the line
between the admission-side resume and the commit-side write. Everything here
runs once per prefill row per step, after ``prompt_consumed`` has moved
(the off-by-one accounting stays in the scheduler), and labels the states the
forward staged for that row.

A ROW CAN OWE TWO WRITES IN ONE STEP
====================================
Its PRIMARY boundary — the prompt-completing write or a governor crossing,
decided by :func:`~arbi_serve.cache.recurrent_savepoint.savepoint_fold_split`
— and its BRANCH boundary: the end of a context the radix tree already holds
under another continuation (:mod:`arbi_serve.scheduler.savepoint_trail`).
Each was armed into its own staging slot; the row's commit takes the row's
own snapshots from the pool (``close_boundary_snapshots``) and matches each
to the boundary it was armed for, so the order rows commit in never hands one
row's state to another.
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING

from arbi_serve.cache import _metrics as cache_metrics
from arbi_serve.cache.recurrent_savepoint import FoldSplitUnaligned, savepoint_fold_split
from arbi_serve.flag_truth import FiringWindow, path_counter
from arbi_serve.scheduler.savepoint_trail import boundary_already_stored

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request

_LOG = logging.getLogger("arbi_serve.scheduler")

#: The prompt-completing step's savepoint write — the one the ``chunk_size``
#: governor would otherwise skip (:func:`~arbi_serve.cache.recurrent_savepoint.
#: savepoint_fold_split`). Fires when such a step's boundary snapshot is
#: stored; refused by name when the flag is off. A completing step that ALSO
#: crossed the governor's grid is an ordinary write and moves neither count.
_PROMPT_END_WRITE = path_counter("savepoint_prompt_end_write", FiringWindow.SERVE)
#: The write at a shared context's end: a row whose radix walk stopped where
#: the tree forks, past every savepoint it could resume from, stored the
#: state at the fork so its siblings resume there. Refused by name when the
#: row's step did not stage it.
_BRANCH_WRITE = path_counter("savepoint_branch_write", FiringWindow.SERVE)
#: Every governor crossing a prefill step reached, by what the policy did
#: with it: ``written`` (with the policy that wanted it) or
#: ``skipped_unarmed`` (the tenant had shown no demand).
_CROSSING_WRITE_TOTAL = "arbi_serve.savepoint.crossing_write_total"

_SKIPPED = "arbi_serve.savepoint.snapshot_skipped_total"


class _BoundaryCommitMixin:
    """The snapshotter's commit-side writes (mixed into ``SavepointSnapshotter``)."""

    def _take_row_snapshots(self, req: Request) -> list | None:
        """This row's open boundary snapshots, taken off the pool; ``None`` on a
        pool that only offers the one-snapshot close (the caller then closes
        lazily, as before)."""
        pool = self._sched.pool
        close_rows = getattr(pool, "close_boundary_snapshots", None)
        by_row = getattr(pool, "closes_by_row", None)
        if close_rows is None or by_row is None or not by_row():
            return None
        return list(close_rows(req.request_id))

    def snapshot_crossed_boundaries(
        self,
        req: Request,
        pc_before: int,
        pc_after: int,
        chunk_size: int,
        snapshot_fn,
        *,
        completes_prompt: bool = False,
    ) -> None:
        """Store the savepoints this step's prefill row owed, from what the forward staged.

        Called from the prefill branch of :meth:`Scheduler.commit` AFTER
        the ``prompt_consumed`` accounting (the off-by-one site, which
        stays in the scheduler) has produced ``pc_before`` / ``pc_after``.
        A snapshot failure is opportunistic and MUST NOT break the prefill
        commit — the store's ``put`` already returned False and bumped the
        metric.

        THE ONLY STATE THE SLAB HOLDS IS THE STATE AT ``pc_after``
        ===========================================================
        The recurrence for the whole chunk is swept inside a single fused
        kernel, so a boundary anywhere else exists only as the state the
        forward EMITTED at it (the in-forward route, from inside its launch,
        spilled per layer while later layers compute). The whole-row snapshot
        — the slab row copied after the step — is kept only as a fallback for
        a step that ENDED on its boundary and staged nothing, because its
        transfer is fenced in front of the next step's first slab write;
        ``snapshot_route_total`` says which route a boot is on.

        WHICH ``pc_after`` IS WORTH A WRITE
        ===================================
        ``chunk_size`` is the write-rate governor, not an address: the step
        that carries ``prompt_consumed`` across a multiple of it writes one
        snapshot at the deepest page boundary it reached, and so does the step
        that completes the prompt (``completes_prompt``; see
        :func:`~arbi_serve.cache.recurrent_savepoint.savepoint_fold_split`).
        Only a page-aligned position can be restored: a resume credits
        ``prompt_consumed`` against KV the radix tree aliases in whole pages.
        A shared context's end (the branch write) is page-aligned by
        construction — it is the radix walk's own reach.

        EVERY DROP IS COUNTED AND SIZED
        ===============================
        ``arbi_serve.savepoint.snapshot_skipped_total`` records why a step
        wrote nothing, and for a step that crossed the grid but landed off
        the page grid, the chunk's width and where it landed (bucketed, so
        the label cardinality stays bounded).
        """
        if pc_after <= pc_before:
            cache_metrics.counter_inc(_SKIPPED, labels={"reason": "no_progress"})
            return
        sched = self._sched
        snaps = self._take_row_snapshots(req)
        branch = self.branch_boundary_in(req, pc_before, pc_after)
        crossed = pc_before // chunk_size != pc_after // chunk_size
        # A crossing is written only for a tenant whose crossings are wanted
        # (``ARBI_SAVEPOINT_CROSSING_WRITES``; by default, armed by evidence
        # in ``note_prefix_reach``). The scheduler asked the same predicate
        # when it armed the forward, so an unwanted crossing emitted nothing.
        wanted = self.crossings_wanted(sched._tenant_id_for(req))
        crossing_write = crossed and wanted
        if crossed:
            cache_metrics.counter_inc(
                _CROSSING_WRITE_TOTAL,
                labels=(
                    {"decision": "written", "policy": self.crossing_policy}
                    if wanted
                    else {"decision": "skipped_unarmed"}
                ),
            )
        completes = bool(completes_prompt)
        prompt_end_write = completes and not crossing_write
        boundary = None
        if crossing_write or prompt_end_write:
            try:
                boundary = savepoint_fold_split(
                    pc_before=pc_before,
                    pc_after=pc_after,
                    chunk_size=chunk_size,
                    resume_grid=max(1, sched._savepoint_page_bs),
                    fold_grid=max(1, sched._savepoint_fold_grid),
                    completes_prompt=completes,
                    crossings=wanted,
                )
            except FoldSplitUnaligned:
                boundary = None
        if branch is not None and branch != boundary:
            self._write_branch(req, branch, pc_after, snaps, snapshot_fn)
        try:
            self._write_primary(
                req,
                pc_before,
                pc_after,
                chunk_size,
                snapshot_fn,
                boundary=boundary,
                crossed=crossed,
                crossing_write=crossing_write,
                prompt_end_write=prompt_end_write,
                completes=completes,
                snaps=snaps,
                shared=branch is not None and branch == boundary,
            )
        finally:
            for leftover in snaps or ():
                # Armed for this row at a boundary no write here claimed: the
                # label and the state would not be the same decision's.
                cache_metrics.counter_inc(_SKIPPED, labels={"reason": "fold_split_mismatch"})
                _LOG.warning(
                    "savepoint boundary snapshot discarded: staged req=%s boundary=%s but "
                    "this commit over [%s, %s) wrote nothing there.",
                    leftover.req_id,
                    leftover.boundary,
                    pc_before,
                    pc_after,
                )

    def _write_primary(
        self,
        req: Request,
        pc_before: int,
        pc_after: int,
        chunk_size: int,
        snapshot_fn,
        *,
        boundary: int | None,
        crossed: bool,
        crossing_write: bool,
        prompt_end_write: bool,
        completes: bool,
        snaps: list | None,
        shared: bool,
    ) -> None:
        sched = self._sched
        if not crossing_write and not prompt_end_write:
            # Nothing to write: the step stayed inside one ``chunk_size``
            # span, or crossed one this tenant does not write.
            cache_metrics.counter_inc(
                _SKIPPED, labels={"reason": "crossing_unarmed" if crossed else "no_crossing"}
            )
            return
        if (
            boundary is not None
            and boundary == pc_before
            and boundary_already_stored(req, boundary)
        ):
            # The completing step began exactly on the prompt's last page
            # boundary and the step before wrote that state as its own end.
            # The scheduler declined to arm for the same reason, through the
            # same predicate; nothing is missing from the store.
            cache_metrics.counter_inc(_SKIPPED, labels={"reason": "start_already_stored"})
            if prompt_end_write:
                _PROMPT_END_WRITE.fired = 1
            return

        # THE IN-FORWARD ROUTE FIRST, WHEREVER THE STEP ENDED; the whole-row
        # snapshot below is the FALLBACK for a step that ended on the resume
        # grid but staged nothing. Both routes are counted.
        def _stored() -> None:
            cache_metrics.counter_inc(
                "arbi_serve.savepoint.snapshot_route_total", labels={"route": "in_forward"}
            )
            if prompt_end_write:
                _PROMPT_END_WRITE.fired = 1

        stored = self._snapshot_boundary_state(
            req,
            pc_before,
            pc_after,
            completes_prompt=completes,
            snaps=snaps,
            boundary=boundary,
            shared=shared,
        )
        if stored:
            _stored()
            return
        page_bs = sched._savepoint_page_bs
        if page_bs > 0 and pc_after % page_bs != 0:
            # The step did not END on the resume grid, so the slab holds no
            # state a resume could splice; the staged route was the only one
            # and it declined (its reason is already counted).
            width = pc_after - pc_before
            cache_metrics.counter_inc(
                _SKIPPED,
                labels={
                    "reason": "off_page",
                    "width": (
                        "full"
                        if width >= chunk_size
                        else f"lt_{min(8, (width * 8) // max(1, chunk_size)) + 1}_8ths"
                    ),
                    "residue": str(min(8, (pc_after % chunk_size) * 8 // max(1, chunk_size))),
                },
            )
            return
        cache_metrics.counter_inc(
            "arbi_serve.savepoint.snapshot_route_total", labels={"route": "whole_row"}
        )
        try:
            self.snapshot_at_boundary(
                req=req,
                tenant_id=sched._tenant_id_for(req),
                snapshot_fn=snapshot_fn,
                boundary=pc_after,
                shared=shared and boundary == pc_after,
            )
        except Exception:  # noqa: BLE001 — snapshot is opportunistic
            # A snapshot failure (e.g. budget refused under "refuse"
            # overflow policy) MUST NOT break the prefill commit.
            cache_metrics.counter_inc("arbi_serve.savepoint.snapshot_error_total", labels={})
            return
        if prompt_end_write:
            _PROMPT_END_WRITE.fired = 1

    def _write_branch(self, req: Request, branch: int, pc_after: int, snaps, snapshot_fn) -> None:
        """Store the state at a shared context's end, which this step passed."""
        sched = self._sched
        self.clear_branch_point(req)
        snap = _pop_boundary(snaps, branch)
        if snap is not None and snap.complete:
            try:
                self.snapshot_at_boundary(
                    req=req,
                    tenant_id=sched._tenant_id_for(req),
                    snapshot_fn=None,
                    boundary=int(snap.boundary),
                    staged=snap,
                    shared=True,
                    off_trail=True,
                )
            except Exception:  # noqa: BLE001 — snapshot is opportunistic
                cache_metrics.counter_inc("arbi_serve.savepoint.snapshot_error_total", labels={})
                return
            _BRANCH_WRITE.fired = 1
            return
        if snap is None and branch == pc_after and snaps is not None:
            # The step ENDED at the fork and nothing was staged for it: the
            # slab row after the step is that state.
            try:
                self.snapshot_at_boundary(
                    req=req,
                    tenant_id=sched._tenant_id_for(req),
                    snapshot_fn=snapshot_fn,
                    boundary=pc_after,
                    shared=True,
                    off_trail=True,
                )
            except Exception:  # noqa: BLE001 — snapshot is opportunistic
                cache_metrics.counter_inc("arbi_serve.savepoint.snapshot_error_total", labels={})
                return
            _BRANCH_WRITE.fired = 1
            return
        _BRANCH_WRITE.refuse(
            "the step staged no state at the shared context's end"
            if snap is None
            else "the staged branch state is incomplete"
        )

    def _snapshot_boundary_state(
        self,
        req: Request,
        pc_before: int,
        pc_after: int,
        *,
        completes_prompt: bool = False,
        snaps: list | None = None,
        boundary: int | None = None,
        shared: bool = False,
    ):
        """Store the MID-step boundary snapshot, if the forward staged one.

        Returns True when a snapshot was stored — the caller then counts no
        drop. False means the write did not happen, and every path to False
        names itself in ``arbi_serve.savepoint.snapshot_skipped_total{reason=...}``.
        :data:`DEFERRED` means the pool's close is still waiting on the peer
        pipeline stage's half: the write is queued (:attr:`deferred_writes`),
        every check below runs when the half arrives, and ``on_stored`` is
        called if it is stored.

        THE LABEL AND THE STATE COME FROM THE SAME DECISION
        ===================================================
        The boundary is recomputed with
        :func:`~arbi_serve.cache.recurrent_savepoint.savepoint_fold_split`
        from THIS step's own ``pc_before``/``pc_after`` — the same call the
        scheduler made when it armed the split — and the snapshot taken is the
        row's own one armed at exactly that boundary. A snapshot for another
        request, or another boundary, is never labelled with this one: that
        would put a coverage label on a state that is not the state at that
        token, which the store's own guard cannot catch, because both halves
        would be consistent and both wrong.

        A snapshot that is not COMPLETE is refused with the attributes nobody
        staged: a partial restore keeps a stale tensor for the layers that
        were missed, which is silently wrong output rather than a miss.
        """
        sched = self._sched
        if boundary is None:
            try:
                boundary = savepoint_fold_split(
                    pc_before=pc_before,
                    pc_after=pc_after,
                    chunk_size=sched._savepoint_chunk_size,
                    resume_grid=sched._savepoint_page_bs,
                    fold_grid=max(1, sched._savepoint_fold_grid),
                    completes_prompt=completes_prompt,
                )
            except FoldSplitUnaligned:
                boundary = None
        if snaps is None:
            close = getattr(sched.pool, "close_boundary_snapshot", None)
            if close is None:
                return False
            snap = close()
            opened = snap is not None
        else:
            opened = bool(snaps)
            snap = _pop_boundary(snaps, boundary) if boundary is not None else None
        return self._store_closed_snapshot(
            req, snap, opened, boundary, pc_before, pc_after, shared=shared
        )

    def _drop_write_bookkeeping(self, req_id: int) -> None:
        """Forget the per-request write state: the reclaim hints and the trail link."""
        self._reclaimable.pop((int(req_id), True), None)
        self._reclaimable.pop((int(req_id), False), None)
        self._trail_of_req.pop(int(req_id), None)

    def _forget_write_trail(self, req_id: int) -> None:
        """The request is gone; a write of its still waiting re-forgets once it lands."""
        self._drop_write_bookkeeping(req_id)

    def _store_closed_snapshot(
        self,
        req: Request,
        snap,
        opened: bool,
        boundary: int | None,
        pc_before: int,
        pc_after: int,
        *,
        shared: bool,
    ) -> bool:
        """The commit's checks on a closed snapshot, then the store write.

        One body for a synchronous close and for a deferred one settled later,
        so the label and completeness rules cannot drift apart.
        """
        sched = self._sched
        if not opened:
            # NOTHING WAS EVER OPENED for this row: the SCHEDULER declined to
            # arm (``Scheduler._arm_fold_split`` names its own reason on
            # ``savepoint_fold_split_armed``). The forward is not involved and
            # cannot be; ``fold_split_not_staged`` below is the forward's.
            cache_metrics.counter_inc(_SKIPPED, labels={"reason": "fold_split_not_opened"})
            return False
        if (
            snap is None
            or boundary is None
            or int(snap.req_id) != int(req.request_id)
            or int(snap.boundary) != int(boundary)
        ):
            cache_metrics.counter_inc(_SKIPPED, labels={"reason": "fold_split_mismatch"})
            if snap is not None:
                _LOG.warning(
                    "savepoint boundary snapshot discarded: staged req=%s boundary=%s but "
                    "this commit is req=%s boundary=%s over [%s, %s). The state and the "
                    "label would not be the same step's.",
                    snap.req_id,
                    snap.boundary,
                    req.request_id,
                    boundary,
                    pc_before,
                    pc_after,
                )
            return False
        if not snap.complete:
            # ZERO staged and PARTIALLY staged are different facts. A GDN
            # prefill that replays a CAPTURED graph cannot stage, and a boot
            # with the emit staging off stages nothing either; both are
            # designed paths (``gdn_fold_split_staged``'s refusals say which).
            # A PARTIAL stage is the dangerous one: a restore would keep a
            # stale tensor for the layers that were missed. It keeps the loud
            # warning and the missing list.
            if not snap.staged:
                cache_metrics.counter_inc(_SKIPPED, labels={"reason": "fold_split_not_staged"})
                _LOG.debug(
                    "savepoint boundary snapshot discarded: the forward staged "
                    "nothing for req=%s boundary=%s (a captured step, or the emit "
                    "staging is off; gdn_fold_split_staged names it).",
                    snap.req_id,
                    snap.boundary,
                )
                return False
            cache_metrics.counter_inc(_SKIPPED, labels={"reason": "fold_split_incomplete"})
            _LOG.warning(
                "savepoint boundary snapshot discarded: %d of %d (layer, attr) staged; "
                "missing %s. A partial restore keeps a stale tensor for those layers.",
                len(snap.staged),
                len(snap.expected),
                snap.missing(),
            )
            return False
        try:
            self.snapshot_at_boundary(
                req=req,
                tenant_id=sched._tenant_id_for(req),
                snapshot_fn=None,
                boundary=int(snap.boundary),
                staged=snap,
                shared=shared,
            )
        except Exception:  # noqa: BLE001 — snapshot is opportunistic
            cache_metrics.counter_inc("arbi_serve.savepoint.snapshot_error_total", labels={})
            return False
        return True


def _pop_boundary(snaps: list | None, boundary: int):
    """Remove and return the snapshot armed at ``boundary`` from ``snaps``, or ``None``."""
    if not snaps:
        return None
    for i, snap in enumerate(snaps):
        if int(snap.boundary) == int(boundary):
            return snaps.pop(i)
    return None


__all__ = ["_BoundaryCommitMixin"]
# ---- savepoint_resume_fallback.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Resolve a hybrid resume to the deepest savepoint that can be SERVED, never to none.

A resume point is the pair (KV pages to depth N, recurrent savepoint at N).
Between the digest probe that names the deepest candidate and the moment the
pair is used, either half can come up short: the entry is gone from the store
(a ring overwrite, an LRU eviction on the promoter thread, a disk blob that
did not read back), or the radix match stops before N (a tier page that could
not be restored, the page budget a preempt re-bind is held to). The old
answer to both was to discard the whole match and re-prefill from token 0 —
``match_discarded_total{reason="no_savepoint"}`` and
``kv_coverage_shortfall_total`` — although a SHALLOWER savepoint on the same
path usually still stood.

Every shortfall here falls back to the next-shallower point instead, through
the same digest walk and the same store probe, until one can be served or
there is none. Each step strictly lowers the bound, so it terminates.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from arbi_serve.cache import _metrics as cache_metrics

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request

#: A resume that fell back to a shallower savepoint, by what the deeper one lacked.
RESUME_FALLBACK_TOTAL = "arbi_serve.savepoint.resume_fallback_total"


def fetch_entry(snap: Any, key: Any) -> Any:
    """``key``'s entry, from RAM, a landed prefetch, or the disk tier; ``None`` if gone."""
    store = snap._sched._savepoint_store
    entry = store.get(key)
    if entry is not None:
        return entry
    # A prefetch that has landed costs a dict lookup; one that has not is
    # never waited on — the synchronous restore below is what it would take.
    claim = getattr(store, "claim_prefetch", None)
    if claim is not None and claim(key):
        entry = store.get(key)
    if entry is None:
        entry = snap._restore_from_disk(key)
    return entry


def _shallower(snap: Any, req: Request, tenant_id: str, hashes: Any, below: int) -> Any:
    """The deepest stored key on ``req``'s stream covering at most ``below`` tokens."""
    sched = snap._sched
    store = sched._savepoint_store
    if below <= 0:
        return None
    bs = sched._savepoint_chain_bs
    if bs is not None and hashes is not None:
        return store.best_match_hashes(tenant_id, hashes[: below // int(bs)])
    return store.best_match(tenant_id, req.cache_token_ids(), max_tokens=below)


def serve_or_fall_back(
    snap: Any, req: Request, tenant_id: str, key: Any, hashes: Any
) -> tuple[Any, Any]:
    """``(key, entry)`` for ``key`` or the deepest shallower point that can be served."""
    while key is not None:
        entry = fetch_entry(snap, key)
        if entry is not None:
            return key, entry
        cache_metrics.counter_inc(RESUME_FALLBACK_TOTAL, labels={"reason": "entry_lost"})
        key = _shallower(snap, req, tenant_id, hashes, int(key.num_tokens) - 1)
    return None, None


def live_resume_at_or_below(
    snap: Any, req: Request, tenant_id: str, limit_tokens: int
) -> tuple[Any, Any]:
    """The deepest servable savepoint covering at most ``limit_tokens`` of ``req``."""
    sched = snap._sched
    if sched._savepoint_store is None or limit_tokens <= 0:
        return None, None
    hashes = None
    if sched._savepoint_chain_bs is not None:
        hashes = sched.page_table.savepoint_page_hashes(
            req.cache_token_ids(), tenant_id=tenant_id, max_match_len=int(limit_tokens)
        )
    key = _shallower(snap, req, tenant_id, hashes, int(limit_tokens))
    return serve_or_fall_back(snap, req, tenant_id, key, hashes)


__all__ = ["RESUME_FALLBACK_TOTAL", "fetch_entry", "live_resume_at_or_below", "serve_or_fall_back"]
# ---- savepoint_trail.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""A request's savepoint trail: what it stored, and what each write replaces.

Pure functions over the trail a request carries (``savepoint_resume_key``,
``savepoint_keys``, ``savepoint_decode_keys``), shared by the snapshot worker
(:mod:`arbi_serve.scheduler.savepoint_admission`) and the scheduler's arming
seam so the two cannot disagree about what a request has already written.
"""

from __future__ import annotations

from collections import OrderedDict
from typing import Any

from arbi_serve.cache import _metrics as cache_metrics
from arbi_serve.flag_truth import FiringWindow, path_counter

#: A request whose radix walk stopped where the tree FORKS — another
#: conversation continues the same context differently — past every
#: savepoint it could resume from. Fires when the fork is noted for a write
#: at it; refused by name for each reason it is not.
_BRANCH_POINT = path_counter("savepoint_branch_point", FiringWindow.SERVE)
#: Shared entries remembered (keys only), newest last. Bounded because the
#: store forgets entries without telling this side; a key that ages out of
#: here only loses its protection from being dominated, never its bytes.
_SHARED_KEYS_CAP = 4096


def boundary_already_stored(req: Any, boundary: int) -> bool:
    """Does this request's own trail already hold the state at ``boundary``?

    Asked by the scheduler before it arms a split at a step's START and by
    the commit before it counts that step's write as skipped — one predicate,
    so the two sides cannot disagree about why nothing was written. The trail
    is the request's: the entry it resumed from covers exactly the point its
    prefill began, and every prompt-side write it made is a key on
    ``savepoint_keys``. Neither is re-checked against the store — an entry
    the ring has since reclaimed reads as stored here, and the cost of that
    is one boundary's coverage, not a wrong state: a resume matches by
    content and simply misses.
    """
    b = int(boundary)
    resume = getattr(req, "savepoint_resume_key", None)
    if resume is not None and int(getattr(resume, "num_tokens", -1)) == b:
        return True
    for key in getattr(req, "savepoint_keys", None) or ():
        if int(getattr(key, "num_tokens", -1)) == b:
            return True
    return False


def wrote_past(req: Any, key: Any) -> bool:
    """Did ``req`` write a PROMPT-side savepoint deeper than ``key``?

    Decode writes do not count: a decode entry never supersedes a prompt-end
    one (:func:`record_savepoint_write`), so it cannot replace the entry the
    request resumed from either.
    """
    depth = int(getattr(key, "num_tokens", -1))
    decode = {id(k) for k in (getattr(req, "savepoint_decode_keys", None) or ())}
    return any(
        id(k) not in decode and int(getattr(k, "num_tokens", -1)) > depth
        for k in (getattr(req, "savepoint_keys", None) or ())
    )


def record_savepoint_write(trail: list, decode_trail: list, key, *, from_decode: bool) -> list:
    """Update a request's savepoint trails, and return what the new write supersedes.

    A PROMPT-END write supersedes EVERYTHING older the request wrote: the
    prompt is echoed by every client on every turn, so an entry covering it is
    reachable under any convention and strictly dominates the shallower ones.

    A DECODE write supersedes only the request's older DECODE entries. It must
    never demote the prompt-end entry, whose reachability does not depend on
    how the next turn renders the assistant turn — demoting it put the usable
    entry at the front of the eviction queue, a measured regression. Its own
    shallower decode entries ARE dominated for a linear continuation, since
    any prompt reaching page N of a reply also reaches page N+1.

    Superseding is a RANK, not a delete: a regeneration, or a branch from
    mid-reply, still asks for the shallower entry. It only sorts for eviction
    first.
    """
    superseded = list(decode_trail) if from_decode else list(trail)
    trail.append(key)
    if from_decode:
        decode_trail.append(key)
    else:
        # The prompt-end write dominated them, so none of the decode entries
        # recorded so far is still the one to beat.
        decode_trail.clear()
    return superseded


class BranchPoints:
    """Where a context several conversations continue ends, and the states stored there.

    THE FORK IS VISIBLE AT ADMISSION, AND ONLY THERE
    ================================================
    Siblings of one context — the same RAG documents with different
    questions, an edited or regenerated last message — share every token up
    to where they diverge, and a GDN hybrid can resume one only at a stored
    recurrent state. The prompt-end write of the first sibling lies past the
    divergence (it covers that sibling's own question), and a governor
    crossing lands wherever the crossing step reached. The divergence itself
    is known the moment a second sibling's radix walk stops at a node that
    has another child: the walk's reach IS the shared context's end, page
    aligned, and the digest for it is already in hand. This request's prefill
    passes that point, so it writes the state there (``_BRANCH_WRITE``), and
    every later sibling resumes at the fork rather than re-prefilling the
    shared context from the nearest grid line.

    A walk that stops because the tree simply ENDS (a conversation extending
    its own history) is not a fork: no other continuation exists, and the
    request's own prompt-end write serves its next turn. That case writes
    nothing here.

    A SHARED ENTRY IS NEVER ONE SIBLING'S TO DOMINATE
    =================================================
    A conversation's entry is dominated when its next turn completes a
    deeper write, because the conversation will never ask for it again. A
    fork is asked for by every sibling, so a sibling finishing its turn says
    nothing about it: :meth:`is_shared` keeps it off that path and it ages
    only by recency.
    """

    @property
    def _branch_of_req(self) -> dict[int, tuple[int, Any]]:
        """request id -> (boundary, key) of the fork its prefill must write.

        Built on first use, so a snapshotter made without ``__init__`` (the
        seam's unit tests build one over a stub scheduler) has one too.
        """
        return self.__dict__.setdefault("_branch_points", {})

    @property
    def _shared_keys(self) -> OrderedDict[Any, None]:
        return self.__dict__.setdefault("_shared_key_set", OrderedDict())

    def note_branch_point(self, req: Any, tenant_id: str, page_hashes, usable: int) -> bool:
        """Record the fork this request's walk stopped at, if it owes a write there.

        True when the request will write the fork's state (so a governor
        crossing need not be armed to approach it).
        """
        from arbi_serve.cache.recurrent_savepoint import SavepointKey

        sched = self._sched
        bs = int(getattr(sched, "_savepoint_chain_bs", 0) or 0)
        page = int(getattr(sched, "_savepoint_page_bs", 0) or 0)
        reach = len(page_hashes) * bs
        if bs <= 0 or page <= 0 or reach <= 0 or reach <= int(usable):
            return False
        n = len(req.cache_token_ids())
        if reach % page != 0 or reach > ((n - 1) // page) * page:
            # Past the prompt's own last resume point: its prompt-end write,
            # at or before the fork, already covers what a sibling can use.
            return False
        forks = getattr(getattr(sched, "page_table", None), "savepoint_walk_forks", None)
        if forks is None or not forks(req.cache_token_ids(), tenant_id=tenant_id):
            return False
        if not bool(getattr(getattr(req, "sampling", None), "cache_enabled", True)):
            _BRANCH_POINT.refuse("cache disabled for this request")
            return False
        # A live entry at the fork would have been the resume (``usable``);
        # reaching here means there is none this request can use.
        key = SavepointKey(tenant_id=tenant_id, prefix_hash=page_hashes[-1], num_tokens=reach)
        self._branch_of_req[int(req.request_id)] = (reach, key)
        # The retention family: routed to OTEL by prefix, with ``resumes_from_fork``.
        cache_metrics.counter_inc("arbi_serve.savepoint.retention.forks_noted")
        _BRANCH_POINT.fired = 1
        return True

    def branch_boundary_in(self, req: Any, pc_before: int, pc_after: int) -> int | None:
        """The fork this request must write inside ``[pc_before, pc_after]``, or ``None``."""
        got = self._branch_of_req.get(int(req.request_id))
        if got is None:
            return None
        boundary = int(got[0])
        if boundary < int(pc_before):
            # Passed without a write (a preempted prefill that restarted past
            # it): the point is lost for this request, not deferred.
            self._branch_of_req.pop(int(req.request_id), None)
            return None
        return boundary if boundary <= int(pc_after) else None

    def branch_key_of(self, req: Any) -> Any | None:
        got = self._branch_of_req.get(int(req.request_id))
        return None if got is None else got[1]

    def clear_branch_point(self, req: Any) -> None:
        self._branch_of_req.pop(int(req.request_id), None)

    def forget_branch_point(self, req_id: int) -> None:
        self._branch_of_req.pop(int(req_id), None)

    def note_shared(self, key: Any) -> None:
        self._shared_keys[key] = None
        self._shared_keys.move_to_end(key)
        while len(self._shared_keys) > _SHARED_KEYS_CAP:
            self._shared_keys.popitem(last=False)

    def is_shared(self, key: Any) -> bool:
        return key in self._shared_keys


__all__ = ["BranchPoints", "boundary_already_stored", "record_savepoint_write", "wrote_past"]
# ---- scheduler.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Continuous-batching scheduler with chunked prefill.

Talks to :class:`MultiStatePool` exclusively — never reaches into a
specific :class:`StatePoolView` impl. The scheduler uses the
multi-pool ``free_pages(StateKind)`` and
``bytes_per_token_total()`` API; the page table handles per-pool
alloc / free internally.

Per step:
  1. Drain a batch from running (decoding) requests, capped at
     ``max_batch`` and ``max_batched_tokens``.
  2. Top up from waiting (prefilling) requests, contributing
     ``min(remaining_prompt, chunk_prefill, budget_left)`` tokens
     each.
  3. Hand the engine a list of ``(request, num_tokens)`` tuples; the
     engine materializes the :class:`ScheduledBatch` and runs
     forward.
  4. After forward, the engine calls :meth:`commit` to advance per-
     request state.

Preemption: when a decode-phase request needs a new page and the
PAGED_KV pool is full, the most recently-admitted decode request is
bumped back to WAITING (its pages free, its prompt + so-far-decoded
tokens become the new prompt).
"""

from __future__ import annotations

import logging
import time
from collections import deque
from collections.abc import Callable
from typing import TYPE_CHECKING

from arbi_serve.cache._state_pool_common import (
    pool_carries_recurrent_state,
    prefix_cache_can_serve,
    prefix_retention_serves,
    savepoints_serve_here,
)
from arbi_serve.config import BatchConfig, CacheConfig
from arbi_serve.engine.request import Request, RequestState, set_state
from arbi_serve.models.layer_spec import StateKind
from arbi_serve.scheduler import partial_prefill_first as _pf
from arbi_serve.scheduler.activation_budget import StepActivationModel as ActivationModel
from arbi_serve.scheduler.admission_burst import _AdmissionBurstMixin
from arbi_serve.scheduler.coadmit_pacing import CoadmitPacer
from arbi_serve.scheduler.flex_drain import flex_prefill_yields
from arbi_serve.scheduler.mtp_bucketing import MtpBucketer
from arbi_serve.scheduler.offload_manager import OffloadManager
from arbi_serve.scheduler.preemption import Preemptor
from arbi_serve.scheduler.prefix_grouping import (
    build_grouper_from_env,
    grouping_enabled,
    refresh_grouper_window,
)
from arbi_serve.scheduler.quota_filter import QuotaFilter
from arbi_serve.scheduler.savepoint_admission import SavepointSnapshotter
from arbi_serve.scheduler.scheduler_admission import _AdmissionMixin
from arbi_serve.scheduler.scheduler_allocation import _AllocationMixin
from arbi_serve.scheduler.scheduler_commit import _CommitMixin, prefix_publish_grid
from arbi_serve.scheduler.scheduler_counters import SpmdPreempt, _CounterMixin
from arbi_serve.scheduler.scheduler_offload import _OffloadMixin
from arbi_serve.scheduler.scheduler_quota import _QuotaMixin
from arbi_serve.scheduler.scheduler_selection import _SelectionMixin
from arbi_serve.scheduler.step_budget import compute_step_budget
from arbi_serve.tenant.quota import QuotaTracker

_LOG = logging.getLogger("arbi_serve.scheduler")

# Flag-truth counters. The flags here are boot constants read once at
# import, so the refusal is recorded HERE (once, at import) and the fire
# sits on the flag's own per-step action.
from arbi_serve.flag_truth import FiringWindow, path_counter  # noqa: E402

#: Rows the activation gate held back for a later step. Fires only when the
#: modelled slate demand crosses the step's measured free-VRAM budget, which on
#: a card that can hold the widest admissible slate never happens — a non-zero
#: read means the card is tighter than the step limits assume and names it
#: before the forward does.
_ACTIVATION_DEFERRED = path_counter("activation_budget_deferred_row", FiringWindow.SERVE)

#: Prefill chunks the activation gate narrowed to fit the step's budget. The
#: sibling of the deferred counter for the term that can be narrowed instead of
#: refused: a non-zero read means long prompts are advancing in shorter chunks
#: because the card's free VRAM is below a full-width one.
_ACTIVATION_NARROWED = path_counter("activation_budget_narrowed_chunk", FiringWindow.SERVE)

from arbi_serve.scheduler.savepoint_arming import (  # noqa: E402
    _FOLD_SPLIT_ARMED as _FOLD_SPLIT_ARMED,
)
from arbi_serve.scheduler.savepoint_arming import _FoldSplitArmingMixin  # noqa: E402

#: Whether a prefill chunk that COULD be cut onto the fold grid was, and when
#: it was not, the lengths that decided it. The refusal is the interesting
#: half: it says a cut would have bought a whole extra step, and it is also
#: the moment a request's fold history leaves the grid. Steps the cut does not
#: apply to at all (already aligned, too short, prompt-completing) move
#: neither half, so a zero on both means the gate never ran rather than that
#: every step declined.
_FOLD_CUT = path_counter("savepoint_fold_align_cut", FiringWindow.SERVE)

__all__ = [
    "Scheduler",
]


if TYPE_CHECKING:
    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
    from arbi_serve.distributed.pp_handoff_policy import PpHandoffPolicy
    from arbi_serve.scheduler.prefix_grouping import PrefixGrouper
    from arbi_serve.server.metrics import Metrics


class Scheduler(
    _AdmissionBurstMixin,
    _FoldSplitArmingMixin,
    _AdmissionMixin,
    _CommitMixin,
    _OffloadMixin,
    _AllocationMixin,
    _SelectionMixin,
    _QuotaMixin,
    _CounterMixin,
):
    """FCFS continuous-batch scheduler with chunked prefill.

    Pool-aware via the :class:`MultiStatePool` interface only.

    The scheduler owns the page-table for exactly one paged state kind —
    the model's "primary paged" kind. For Qwen3-style dense / hybrid
    models that's :attr:`StateKind.PAGED_KV`; for DeepSeek MLA models
    it's :attr:`StateKind.MLA_SHARED`. The kind is wired in at
    construction (``primary_paged_kind=pool.primary_paged_kind``); the
    scheduler never branches on which kind it has.
    """

    def __init__(
        self,
        page_table: FlatPageTable | RadixPageTable,
        pool: MultiStatePool,
        cache_cfg: CacheConfig,
        batch_cfg: BatchConfig,
        *,
        grouper: PrefixGrouper | None = None,
        primary_paged_kind: StateKind | None = None,
        metrics: Metrics | None = None,
        quota_tracker: QuotaTracker | None = None,
        savepoint_store: RecurrentSavepointStore | None = None,
        parking_enabled: bool = False,
    ) -> None:
        self.page_table = page_table
        self.pool = pool
        self.batch_cfg = batch_cfg
        self.cache_cfg = cache_cfg
        # Cache the bound ``commit_full_pages`` method (or ``None`` for
        # FlatPageTable) once — the page-table type is fixed for the
        # engine's life, so the per-step ``commit`` path is one truthy
        # compare instead of a getattr × every step.
        self._commit_full_pages = getattr(page_table, "commit_full_pages", None)
        # Experimental cross-request sharing of completed in-flight prefill
        # pages. Snapshot once at scheduler construction: this is a boot-time
        # policy and must not change halfway through a request.
        from arbi_serve.runtime_flags import runtime_flags as _rf_pub

        self._prefix_incremental_publish = _rf_pub().prefix_incremental_publish
        # ARBI_MTP_FUSED_MIXED: an MTP-opted decode row's verify tokens ride
        # the SAME forward as the co-admitted chunk, so they debit the step's
        # token allowance (see :meth:`_decode_row_step_tokens`). Snapshotted
        # rather than read per row, and re-snapshotted on a live override by
        # :meth:`refresh_runtime_flag_snapshots`.
        self._snapshot_live_flags(_rf_pub())
        # SPMD rank-0 deferred-release hook (see
        # :meth:`set_spmd_deferred_release`). ``None`` = single-process
        # behaviour (immediate page release; commit from the Request's own
        # token lists in ``finished``; no commit in ``remove``).
        self._spmd_deferred_release: Callable[[int], None] | None = None
        # ARBI_PP_KV_REPLICATE_DECODE_HANDOFF hook (see
        # :meth:`set_pp_kv_handoff` / :mod:`arbi_serve.distributed.pp_kv_handoff`).
        # Wired by ``DistributedEngineDriver.build()`` on the PP coordinator
        # rank only when both that flag and ``pp_replicate_weights`` are on;
        # ``None`` everywhere else — a complete no-op, matching every other
        # optional hook on this class.
        self._pp_kv_handoff: PpHandoffPolicy | None = None
        # Preemptions this scheduler has performed since the SPMD driver
        # last drained the log, in Preemptor order:
        # ``(request_id, new_prompt_len)``. RECORDED AT THE PREEMPT, not
        # inferred afterwards from request state — a victim bumped back to
        # WAITING lands at the HEAD of ``waiting`` and the same
        # ``schedule()`` call can re-admit it onto the very slate the
        # preempt made room for, at which point no post-hoc "still alive,
        # not on this slate, state reset" scan can see it (see
        # :meth:`DistributedEngineDriver._spmd_preempt_rows`).
        self._spmd_preempted: list[SpmdPreempt] = []
        # Requests preempted during the CURRENT ``schedule()`` call whose
        # prefix re-bind has not fired yet. ``Preemptor`` arms an id here;
        # the waiting-admit pass consumes it the moment the victim goes
        # onto the slate the preempt made room for
        # (``_rebind_preempted_prefix``); ``schedule()`` clears whatever is
        # left at the end of the call. Never non-empty across calls.
        self._preempt_rebind_ids: set[int] = set()
        # Queued requests whose prefix hold was given back to the pool
        # (``_release_waiting_prefix_hold``) and that have not been admitted
        # since. Same consumer as ``_preempt_rebind_ids`` and the same
        # per-step page budget, but NOT cleared per call: a released row is
        # admitted once the row it made way for has finished, which is
        # never the step that released it. Drained by the re-bind and by
        # ``remove``; bounded by the waiting queue, since only a queued
        # request can be armed and only a match it still holds arms it.
        self._released_hold_ids: set[int] = set()
        # Armed by the SPMD rank-0 driver (:meth:`enable_spmd_preempt_log`),
        # the only thing that drains the log.
        self._spmd_preempt_log: bool = False
        # Paged kind this scheduler manages. ``None`` falls back to
        # ``pool.primary_paged_kind``; mock pools without the property
        # degrade to ``PAGED_KV`` (the legacy default).
        self.primary_paged_kind: StateKind = (
            primary_paged_kind
            if primary_paged_kind is not None
            else getattr(pool, "primary_paged_kind", StateKind.PAGED_KV)
        )
        # WAITING queue (un-started or preempted). The optional prefix policy
        # serializes only colliding active prefixes; unrelated FCFS requests
        # take its memoized first-page dictionary-miss path.
        self.grouper = grouper
        # Metrics handle for the Grafana batch-shape view. None is fine —
        # the helper-method calls all early-out on None.
        self._metrics: Metrics | None = metrics
        self.waiting: deque[Request] = deque()
        # RUNNING set (PREFILLING or DECODING); a deque so preemption pops
        # from the right (most recent admit).
        self.running: deque[Request] = deque()
        # Second dimension of the admission tally: the forward-ACTIVATION
        # bytes the slate under construction will allocate, against the bytes
        # the serving floor reserved for one step. ``None`` until the boot
        # calibrates it (:meth:`set_activation_model`) — and permanently on a
        # test double or any engine without an activation profile, where the
        # gate is inert and the page tally alone governs, exactly as before.
        self._activation_model: ActivationModel | None = None
        # One-shot latch for the "this row does not fit the budget alone"
        # warning, so a long chat cannot turn the boot log into a firehose.
        self._activation_solo_warned: bool = False
        # ── O(1) admission counters ──────────────────────────────────
        # Running integer tallies of queue/running membership split by
        # priority class, so the HTTP-thread admission gate
        # (:func:`arbi_serve.engine.admission.check_admission`) reads
        # O(1) ints instead of re-scanning ``waiting`` + ``running`` with
        # a per-element ``getattr`` on every arriving request (at c64 the
        # burst-window cost was 64 × ~128 PyObject ops AND a concurrent
        # read of lists the engine thread is mutating).
        #
        # These are maintained EXCLUSIVELY on the engine/loop thread at
        # the add / remove / preempt / offload / completion sites (every
        # site that moves a request into or out of ``waiting`` / ``running``
        # via the :meth:`_waiting_add` / :meth:`_waiting_remove` /
        # :meth:`_running_add` / :meth:`_running_remove` helpers below) and
        # READ on the HTTP loop thread by admission. Plain ``int`` reads
        # and writes are atomic under the CPython GIL (a single bytecode
        # for LOAD/STORE of an int attribute), so the cross-thread access
        # needs no lock — a stale read can at worst be off by the handful
        # of mutations the engine thread applies during the read, which is
        # the same race the previous list-scan had and is harmless to the
        # watermark gate. ``is_flex`` is immutable for a
        # request's lifetime, so the priority key used at the add site
        # matches the one at the remove site — the counters can never drift
        # for a request that flips state (PREFILL↔DECODE never moves a
        # request between ``waiting``/``running``).
        self._n_waiting_interactive: int = 0
        self._n_running_interactive: int = 0
        # Batch-priority running tally — lets admission short-circuit the
        # batch-page-discount walk (``check_admission``) entirely in the
        # common all-interactive case (no batch resident ⇒ nothing to
        # discount ⇒ skip the ``list(running)`` scan).
        self._n_running_batch: int = 0
        # Per-tenant rate-limit + concurrency-cap admission filter. Owns
        # the :class:`QuotaTracker` + per-reason deferral counters; the
        # policy lives in :mod:`arbi_serve.scheduler.quota_filter`. Zero
        # cost when no :class:`TenantContext` is attached / budget is
        # :data:`UNLIMITED`.
        self._quota_filter = QuotaFilter(self._tenant_for, quota_tracker)
        # Recurrent-state savepoint store (host-RAM checkpoints of the
        # per-request recurrent state). Optional — ``None`` (default)
        # makes :meth:`add` force-disable the radix cache for hybrid
        # models; when wired the admission/commit savepoint flow lives in
        # :mod:`arbi_serve.scheduler.savepoint_admission`.
        #
        # ``_savepoint_chunk_size`` is the snapshot WRITE-RATE governor:
        # the commit side writes one snapshot per ``chunk_prefill`` tokens
        # of prompt (at the step that crosses a multiple of it), wherever
        # that step lands. It is not part of the key — the key is the
        # exact token count — so it can change between boots freely.
        #
        # NOT THIS STORE UNDER TENSOR PARALLELISM. The recurrent slab is
        # sharded along heads (``RecurrentStatePool``'s ``num_v_heads_local
        # = num_v_heads // tp_size``), so this store would hold ONE RANK'S
        # SHARD — rank 0's, the only rank with a scheduler — while the match
        # it credits rides the wire to every rank, which would then resume
        # from a zero-cleared row (the #129 trap, on the ranks this store
        # never reaches). Broadcasting cannot fix it: rank 0 does not HOLD
        # the other shards. Each rank keeps its own shard instead, in slots a
        # rank-0 index names on the delta
        # (:mod:`arbi_serve.distributed.rank_local_savepoints`); the SPMD
        # driver installs that index on this scheduler after the boot
        # (``install_member``). Until it does — and on any topology it does
        # not cover — ``savepoints_serve_here`` refuses and a hybrid match is
        # force-disabled, so the request re-derives its whole prompt on every
        # rank. Recompute is a throughput cost; the alternative is a wrong
        # answer. Single-rank deployments are untouched.
        # The engine asks the same question before it builds a store at all, so
        # the condition lives in one function both read rather than in two
        # derivations that can come apart.
        if savepoint_store is not None:
            _ok, _why = savepoints_serve_here(pool)
            if not _ok:
                _LOG.warning("recurrent savepoints DISABLED: %s", _why)
                savepoint_store = None
        self._savepoint_store: RecurrentSavepointStore | None = savepoint_store
        # Complete prefix state and restoration are boot properties. A NO
        # means the radix tree's retention and matching have no consumer:
        # every match would be discarded by ``resolve_match`` and re-prefilled
        # from token 0. Registering those admissions cache-OFF stops the walk,
        # the chain-digest commit and the retention they feed, while leaving
        # the radix table as the ALLOCATOR it also is — its refcount-0 reclaim
        # is what lets admission seat a row on a warm server.
        self._prefix_cache_serves, self._prefix_cache_inert_why = prefix_cache_can_serve(
            has_recurrent_view=pool_carries_recurrent_state(pool),
            savepoint_store_wired=savepoint_store is not None,
            pool=pool,
        )
        # And the OTHER half, which the match answer does not decide. A park
        # reads no one else's prefix — it pins its OWN and comes back to it,
        # carrying its recurrent row in the park chain — so retention
        # has a consumer wherever this boot parks, matching or not. Held as a
        # second field because admission registers the two separately: one
        # flag answering both is what let a warm hit revoke a park.
        # ``parks_here`` is the RESOLVED parking answer this scheduler was
        # handed, not a second derivation of it.
        self._prefix_retention_serves, self._prefix_retention_inert_why = prefix_retention_serves(
            prefix_cache_serves=self._prefix_cache_serves,
            parks_here=bool(parking_enabled),
        )
        self._savepoint_chunk_size: int = int(batch_cfg.chunk_prefill)
        # Whether a governor crossing inside the prompt is written at all —
        # by default only once a tenant has shown it would use one. Read once
        # at construction: the flag is a boot decision, and the arming seam
        # and the commit seam must answer the same way for the same step; the
        # per-tenant arming state lives on the snapshotter, which both ask.
        from arbi_serve.runtime_flags import runtime_flags as _rf_sp
        from arbi_serve.scheduler.savepoint_admission import crossing_policy_from_flag

        self._savepoint_crossing_writes: str = crossing_policy_from_flag(
            _rf_sp().savepoint_crossing_writes
        )
        # The page grid a savepoint's resume point lies on. A resume credits
        # ``prompt_consumed`` for exactly the tokens the restored slab state
        # absorbed, against KV the radix tree aliases in whole pages, so a
        # snapshot is only ever taken at a multiple of this. 0 when no store
        # is wired.
        self._savepoint_page_bs: int = (
            int(getattr(page_table, "block_size", 0) or 0) if savepoint_store is not None else 0
        )
        # The recurrent kernel's OWN reduction grid, and the grid ``schedule``
        # cuts a truncated hybrid prefill chunk onto (see
        # :meth:`_fold_align_prefill_end`). It is not the page grid: the
        # snapshot no longer has to be taken where the step ENDS, because the
        # forward splits the fold at the page boundary inside the step
        # (:func:`~arbi_serve.cache.recurrent_savepoint.savepoint_fold_split`),
        # so the only thing the chunk's end still has to satisfy is the
        # bit-identity precondition every later boundary inherits — a cut on
        # the fold grid. That is 64 where the page grid is 256, so the cut
        # gives up at most 63 tokens instead of at most 255.
        from arbi_serve.cache.recurrent_savepoint import recurrent_fold_grid

        self._savepoint_fold_grid: int = (
            recurrent_fold_grid(pool, self._savepoint_page_bs) if self._savepoint_page_bs > 0 else 0
        )
        # Radix-Merkle savepoint keys ("chain mode"). Every snapshot lands
        # on a page boundary, i.e. exactly on a radix node, so the savepoint
        # key is READ off the tree's per-node rolling hash
        # (``_RadixNode.phash`` / ``ChainPrefixHasher``) instead of hashing
        # the prefix. Holds the radix block_size when active; ``None`` falls
        # back to ``hash_token_prefix`` on a page table without the chain.
        # Pinned at construction — all three key sites (snapshot / match /
        # invalidate) must run the SAME scheme or keys never agree; the
        # eviction-listener wiring in ``engine/active.py`` runs chain mode
        # on the same page table.
        self._savepoint_chain_bs: int | None = (
            self._savepoint_page_bs
            if self._savepoint_page_bs > 0 and hasattr(page_table, "savepoint_page_hashes")
            else None
        )
        # Pair the tree with the store: a hybrid's KV boundary is published,
        # kept and offered only together with its savepoint
        # (:mod:`arbi_serve.cache.radix_pagetable_savepoints`).
        _pair = getattr(page_table, "attach_savepoint_pairing", None)
        if (
            _pair is not None
            and self._savepoint_chain_bs is not None
            and pool_carries_recurrent_state(pool)
        ):
            _pair(savepoint_store)
        # ── Suspended-job KV offload (batch-backlog parking) ──────────
        # When wired, a SUSPENDED batch decode job's paged-KV pages (and
        # recurrent state if hybrid) are snapshotted GPU→host→(disk) and
        # its GPU pages freed. ``None`` (default) keeps the legacy
        # "suspend = skip the row, keep pages resident" behaviour. The
        # per-step suspend/resume policy lives in
        # :mod:`arbi_serve.scheduler.offload_manager`; the parked-job
        # deques (:attr:`suspended`, :attr:`_dropped_suspended`) stay here.
        # Whether this deployment PARKS. Parking is prefix tiering reached
        # from the scheduler's side — a parked request's KV is pinned in the
        # prefix tier and its pages go back to the allocator — so the store
        # is the page table's, not a second one held here, and the only thing
        # this class carries is whether the deployment asked for it.
        self._parking_enabled: bool = bool(parking_enabled)
        # Whether to offload the per-request recurrent state (GDN / Mamba)
        # on hybrid models. OFF by default — paged-KV offload is correct,
        # but bit-identical recurrent-state restore needs more hardening,
        # so hybrid jobs are not parked unless this is enabled (capacity is
        # then handled by graceful recurrent-row backpressure instead).
        self._offload_recurrent: bool = bool(getattr(cache_cfg, "kv_offload_recurrent", False))
        self.suspended: deque[Request] = deque()
        # Jobs whose resume FAILED irrecoverably (snapshot evicted / TTL /
        # corrupt) and must be finished by the engine. The run loop drains
        # this via :meth:`drain_dropped_suspended` and runs the terminal
        # path (finish_reason already stamped). Never blocks scheduling.
        self._dropped_suspended: list[Request] = []
        # ── Admission-time offload self-heal deferral ────────────────
        # On hybrid models the recurrent-row pool can exhaust at
        # admission. The self-heal parks a resident batch decode job to
        # free a row (``_suspend_to_offload``), but that does CUDA work
        # (D2H snapshot + page free) — which MUST NOT run while a model
        # forward is in flight on the executor thread (the forward reads
        # the very pages the suspend frees + reuses, corrupting the
        # in-flight slate and tripping a device-side index assert). The
        # run loop ``await``s the forward off the event loop, so an
        # admission coroutine (``add``) can land mid-forward. When it
        # does, we DEFER the request here and re-admit it at the top of
        # the next :meth:`schedule` — which runs on the loop thread
        # strictly BETWEEN forwards, where the suspend is safe.
        #
        # ``_forward_in_flight_fn`` is injected by the engine build path
        # (a 0-arg predicate reading the engine's in-flight flag).
        # Defaults to "never in flight" so unit-test schedulers that
        # never set it keep the eager inline self-heal.
        self._forward_in_flight_fn: Callable[[], bool] = lambda: False
        self._deferred_admits: deque[Request] = deque()
        # O(1) interactive tally of ``_deferred_admits`` membership, read by
        # the HTTP-thread admission depth gate (so an over-capacity burst
        # that defers into the holding pen still counts toward
        # ``queue_depth_max`` and a SUSTAINED overload backs off cleanly
        # instead of growing the deferred queue without bound). Maintained
        # on the loop thread at the defer / drain sites; lock-free
        # cross-thread int read, same discipline as ``_n_waiting_interactive``.
        self._n_deferred_interactive: int = 0
        # ── Bolt-on policy collaborators ─────────────────────────────
        # The step core (schedule / commit / add) stays here; the bolt-on
        # policy subsystems are small objects constructed with ``self`` (or
        # their config) so they read the live scheduler state by reference.
        # The thin delegating methods below preserve every call site.
        self._mtp_bucketer = MtpBucketer(batch_cfg)
        # ``skip_counts`` is shared by identity so the test reach-in
        # ``sched._mtp_k_skip_counts`` observes the bucketer's live state.
        self._mtp_k_skip_counts: dict[int, int] = self._mtp_bucketer.skip_counts
        self._preemptor = Preemptor(self)
        self._offload_manager = OffloadManager(self)
        self._savepoint_snapshotter = SavepointSnapshotter(self)
        # ── Duplex-lane scheduling clock ───────────────────────────────
        # The frame deadline is per session, on ``Request.next_duplex_deadline``.
        # Monotone "has any duplex-lane request EVER been admitted here"
        # latch, set in ``_add_inner`` — the O(1) fast-out that keeps
        # :meth:`duplex_tick_due` free for every ordinary deployment.
        self._duplex_ever_admitted: bool = False
        # Consecutive steps the duplex exclusivity gate below has taken.
        # Reset to 0 by every step that serves an ordinary slate, so it
        # only ever climbs while a session is due on back-to-back
        # iterations — which only an UNPACED one is. Read by
        # ``duplex_lane_should_yield``.
        self._duplex_consecutive_ticks: int = 0
        #: ARBI_PP_COADMIT_PREFILL_EVERY_N — the pacing decision for a solo
        #: prefill co-admitted with a decode, and the tick-clock measurement
        #: behind it. See :mod:`arbi_serve.scheduler.coadmit_pacing`.
        self._coadmit_pacer = CoadmitPacer(_rf_pub().pp_coadmit_prefill_every_n)

    @property
    def activation_model(self) -> ActivationModel | None:
        """The armed activation gate, or ``None`` while it is inert.

        Readable so the engine can re-arm the SAME model against a re-measured
        budget when the card contradicts the one it was armed with
        (:func:`~arbi_serve.engine.activation_admission.rearm_step_budget`),
        rather than a second copy of the calibration being kept somewhere else
        to read the first one back from.
        """
        return self._activation_model

    def set_activation_model(self, model: ActivationModel | None) -> None:
        """Arm (or clear, with ``None``) the admission-time activation gate.

        Called from the boot seam that finalizes the serving floor, so the
        budget admission enforces and the bytes the floor reserved are the same
        number — and again from the memory-pressure seam, which re-arms the same
        calibration against a freshly measured budget after an OOM proved the
        boot's reading stale. Until it is called the gate is inert: the page
        tally alone governs admission, which is the behaviour every engine had
        before.
        """
        self._activation_model = model
        self._activation_solo_warned = False

    def _gather_charge(self, req: Request, want: int) -> int:
        """KV tokens tkv's padded gather can materialize for this prefill row.

        ``req.total_length`` is the row's accumulated KV before this chunk and
        ``want`` its query tokens, so their sum is the ``S_kv`` the gather
        would span — clamped by the model to the ceiling past which tkv takes
        the zero-copy varlen route and stages nothing context-scaled. Two int
        reads and a min; zero when no model is armed or the engine has no
        paged tkv backend.
        """
        model = self._activation_model
        if model is None:
            return 0
        return model.gather_charge_tokens(req.total_length + int(want))

    def refresh_runtime_flag_snapshots(self) -> None:
        """Re-read the live-applicable runtime flags into the cached attrs.

        The engine calls this on every flag-overlay install, beside the model
        runner's method of the same name
        (:mod:`arbi_serve.engine.config_variant`). A flag the runner
        re-snapshots and the scheduler does not is a HALF-flipped arm:
        ``ARBI_MTP_FUSED_MIXED`` decides both how a mixed step is forwarded
        (the runner's side) and what an MTP-opted decode row debits from the
        step's token allowance (this side), and an override that moved only
        the first would change the composition of a step while leaving
        admission sized for the other path — which is neither arm.
        """
        from arbi_serve.runtime_flags import runtime_flags

        self._snapshot_live_flags(runtime_flags())

    def _snapshot_live_flags(self, rf) -> None:
        """Snapshot the live-refreshable runtime flags into cached attrs.

        Single source of truth for the two snapshot sites — construction and
        the live re-snapshot — so they cannot drift. Only a flag whose effect
        is a pure per-step admission decision belongs here: nothing allocated
        is keyed to one, so flipping it between steps changes what the NEXT
        slate admits and nothing already in flight.
        """
        self._mtp_fused_mixed = bool(rf.mtp_fused_mixed)
        # ``getattr``: a caller may hand a partial flags double (the fused-mixed
        # override test builds one carrying only the field it exercises), and a
        # snapshot that hard-required every field would make adding one to this
        # method break every such test rather than the code it guards.
        self._coadmit_prefill_max_tokens = max(
            0, int(getattr(rf, "coadmit_prefill_max_tokens", 0) or 0)
        )
        _pf.set_partial_prefill_first(self, bool(getattr(rf, "partial_prefill_first", False)))

    def _decode_row_step_tokens(self, req: Request) -> int:
        """Flat tokens this decode row takes from the step's token allowance.

        ``1`` — its committed tail — on a boot that serves a mixed step as
        two forwards, where the verify rows' ``K`` drafts run in a forward of
        their own and never share the chunk's width. With
        ``ARBI_MTP_FUSED_MIXED`` armed the verify rows and the chunk are ONE
        forward, whose width must stay inside the step width the activation
        profile measured (:mod:`arbi_serve.runtime.fused_mixed_step`), so the
        row debits its whole ``1 + K`` and the co-admitted chunk is sized
        against what is left. The same read of ``K`` the page side makes
        (:meth:`~arbi_serve.scheduler.scheduler_allocation._AllocationMixin.row_draft_depth`)
        — an upper bound the step can collapse below, never exceed.
        """
        if not self._mtp_fused_mixed:
            return 1
        return 1 + self.row_draft_depth(req)

    def _query_charge(self, req: Request) -> int:
        """EXTRA query tokens this decode row's step will run beyond its tail.

        ``K`` for an MTP-opted row, 0 otherwise. A served verify step stages
        ``K + 1`` flat tokens for the row (:func:`~arbi_serve.spec_decode.
        mtp_verify_plan.build_verify_plan`); the ``+1`` is the committed tail
        every decode row already pays for through the model's per-row term, so
        the charge is the ``K`` drafts beside it.

        THE SAME READ THE PAGE SIDE MAKES, literally — both halves of one step's
        reservation call :meth:`~arbi_serve.scheduler.scheduler_allocation.
        _AllocationMixin.row_draft_depth`, so they cannot come to disagree about
        which rows speculate or how deep. The only thing this adds is the gate's
        own precondition: an unarmed model charges nothing, while the pages are
        reserved either way.

        A ZERO SLOPE SKIPS THE READ, and that is an identity rather than a
        shortcut: ``demand_bytes`` multiplies this by ``per_query_token_bytes``
        and ``max_prefill_tokens`` subtracts the same product, so at a zero
        slope every caller's answer is unchanged whatever this returns. The
        slope is zero for every boot that does not speculate — the profile emits
        no verify shape and the calibration has no residual to fit — so a
        non-MTP decode step pays one attribute compare per row and not a
        ``getattr`` chain, and only the traffic the term exists for pays for it.
        """
        model = self._activation_model
        if model is None or model.per_query_token_bytes <= 0:
            return 0
        return self.row_draft_depth(req)

    def _fold_align_prefill_end(self, req: Request, want: int, can_defer: bool = False) -> int:
        """Trim a truncated hybrid prefill chunk so it ends on the fold grid.

        THE GRID IS THE KERNEL'S, NOT THE PAGE TABLE'S
        ==============================================
        A recurrent savepoint is restorable only where the state it names is
        the state an uncut prefill would hold at that token. The recurrent
        kernel reduces over its own fixed chunk width (``GDN_CHUNK_SIZE``),
        so any decomposition whose every cut is a multiple of that width
        yields the same state, and one whose cuts are not yields a state no
        uncut prefill produces — the precondition
        :func:`~arbi_serve.cache.recurrent_savepoint.savepoint_resume_grid`
        already states, applied to the chunk cuts that create the boundaries
        rather than to the boundary alone. Because each chunk starts where
        the last one stopped, ONE off-grid cut puts every later position of
        that prefill off the grid for good.

        This used to trim onto the KV PAGE grid, because the snapshot could
        only be taken where the step ended. It no longer has to be: the
        forward splits the fold at the page boundary INSIDE the step and the
        snapshot is taken there (see
        :func:`~arbi_serve.cache.recurrent_savepoint.savepoint_fold_split`).
        What is left for the chunk's end to satisfy is only the bit-identity
        precondition above — the fold grid, which the page grid is a
        multiple of. The cut therefore gives up at most ``fold_grid - 1``
        tokens instead of at most ``page_bs - 1``.

        GOING BACK TO THE PAGE GRID IS NOT THE ANSWER, AND IT WAS MEASURED
        =================================================================
        While the mid-step emit did not run on the COMPILED prefill path
        (arbicity/arbi-serve#2238, before the ops read the plan host-side —
        :mod:`arbi_serve.cache._fold_emit_staging`), "cut onto the page grid
        so the end-of-step snapshot can take the crossing" looked like the
        obvious workaround. It is worse, and stays worse with the emit
        working (served A/B on the 27B, multi-turn cached share; the counters
        are ``off_page``, ``no_crossing`` and ``savepoint_fold_split_armed``):
        giving up to ``page_bs - 1`` tokens narrows the step below the
        ``chunk_size`` governor often enough that crossings are LOST, and the
        page trim is refused as costing a step far more often, which forfeits
        the grid for the whole request.

        A step too narrow to reach the next grid line (a budget's leftover) is
        off the grid all the same, and every later boundary of the row would be
        refused. With ``can_defer`` (other rows fill the step) the row waits a
        step, giving up less than one fold chunk; alone, it keeps its width and
        is marked off the grid. Never trims the prompt-completing chunk.

        AND ONLY WHEN THE TRIM COSTS NO STEP
        ====================================
        The trim gives up ``want % grid`` tokens, and those tokens are free
        exactly when the prefill still finishes in the number of steps it
        would have taken uncut. The predicate is that, evaluated on this
        step's own numbers::

            1 + ceil((remaining - aligned) / want) <= ceil(remaining / want)

        — take the narrower step now, then full ones, and see whether the
        total is still the uncut total. When it is, the trim is free and
        better than free (a narrower step is a shorter step, and it occupies
        the same number of GEMM tiles because the GEMM pads M to whole ones).
        When it is not, the trim buys a whole extra step, which is hundreds
        of milliseconds against the few the narrower step saves, so it is
        refused.

        WHY THE PREDICATE LOOKS AHEAD RATHER THAN AT THE WHOLE PROMPT
        =============================================================
        The obvious form — cut only when ``ceil(remaining / aligned) ==
        ceil(remaining / want)``, i.e. only when cutting EVERY remaining step
        is free — declines on the FIRST step of any prefill whose length does
        not permit it, and a decline is not local: it sets
        :attr:`Request.fold_history_off_grid`, which forfeits every later
        savepoint of the request. Declining early therefore throws away the
        savepoints of a whole prefill to save a step at its end. The
        look-ahead form declines as LATE as possible instead, which costs the
        same number of steps and keeps substantially more savepoints
        (simulated over the served widths; figures on
        arbicity/arbi-serve#2189).

        Nothing here is a constant: ``want`` is what the step's budget left
        after the rows ahead of it, and ``grid`` is the kernel's own reduction
        width read through ``recurrent_fold_grid``.

        The caller charges the step the UNTRIMMED width. Handing the trimmed
        tokens to the next prefill row would turn the depth-first FCFS slate
        (one prefill row advancing at full width, see ``schedule``) into two
        rows sharing the step: measured on the served 27B at c=8 that moved
        TTFT p50 up by more than half while p95 fell — a redistribution, not
        a saving. Charging the full width keeps the slate's shape.

        There is no flag. The cut was a flag while it was a TRADE — TTFT for
        the savepoint hit rate — and the predicate above is what ended the
        trade, so a switch would only offer an operator the losing side of a
        decision already made from the step's own numbers. What replaces it is
        the invariant it was standing in for, asserted directly:
        ``test_the_cut_never_costs_a_step_at_any_length``.

        0 (no store, or a pure-attention model) leaves ``want`` untouched. It
        costs nothing at c=1 in any case: a prefill running alone takes the
        whole ``max_batched_tokens`` chunk, which is a multiple of both grids
        already, so ``end % grid`` is 0 and nothing is trimmed.
        """
        grid = self._savepoint_fold_grid
        if grid <= 1 or want >= req.num_remaining_prompt or not self._has_recurrent_state():
            return want
        end = req.prompt_consumed + want
        aligned = end - end % grid - req.prompt_consumed
        if aligned == want or req.fold_history_off_grid:
            return want  # already on the grid, or nothing left to keep there
        remaining = req.num_remaining_prompt
        if aligned < grid:
            if can_defer:
                _FOLD_CUT.fired = 1
                return 0
            _FOLD_CUT.refuse(f"a row alone cannot reach the fold grid: {want} of {grid}")
        elif 1 + -(-(remaining - aligned) // want) <= -(-remaining // want):
            _FOLD_CUT.fired = 1
            return aligned
        else:
            # A whole extra step is hundreds of milliseconds against the few
            # the narrower step saves: keep the width, leave the grid.
            _FOLD_CUT.refuse(f"a cut here costs a step: {remaining} left, {aligned} vs {want}")
        req.fold_history_off_grid = True
        return want

    def _activation_chunk_cap(
        self,
        req: Request,
        want: int,
        *,
        act_prefill_tokens: int,
        act_rows: int,
        act_gather_tokens: int,
        act_query_tokens: int,
        slate_is_empty: bool,
    ) -> int:
        """Bound the next prefill quantum by media policy and the measured memory model."""
        from arbi_serve.scheduler.prefill_chunk import activation_chunk_cap

        return activation_chunk_cap(
            self,
            req,
            want,
            act_prefill_tokens=act_prefill_tokens,
            act_rows=act_rows,
            act_gather_tokens=act_gather_tokens,
            act_query_tokens=act_query_tokens,
            slate_is_empty=slate_is_empty,
        )

    def _activation_admits(
        self,
        *,
        prefill_tokens: int,
        rows: int,
        gather_kv_tokens: int,
        query_tokens: int = 0,
        slate_is_empty: bool,
    ) -> bool:
        """Whether this slate shape fits the step's activation budget.

        Mirrors :meth:`_can_allocate_reserved`, one dimension over: the caller
        passes the tally INCLUDING the row it is about to append, and a False
        return means the same thing a page-gate refusal means — leave the row
        for a later step.

        The one asymmetry is the solo case. A row that does not fit the budget
        even alone can never fit, so refusing it would starve it forever; it is
        admitted with a bounded warning instead. A prefill row reaches that case
        only after :meth:`_activation_chunk_cap` has already narrowed its token
        count as far as the budget allows, so what remains is a row whose cost
        does not live in its tokens. That is the honest boundary of what
        admission can enforce: it bounds CO-RESIDENT demand exactly, narrows the
        one term it can narrow, and names a single row that exceeds the budget
        by itself rather than letting the forward discover it as an OOM.
        """
        model = self._activation_model
        if model is None:
            return True
        if model.admits(
            prefill_tokens=prefill_tokens,
            rows=rows,
            gather_kv_tokens=gather_kv_tokens,
            query_tokens=query_tokens,
        ):
            return True
        if slate_is_empty:
            if not self._activation_solo_warned:
                self._activation_solo_warned = True
                _LOG.warning(
                    "activation budget: a single row's forward needs ~%d MiB but the "
                    "card has %d MiB free for one step — admitting it anyway (one row "
                    "is the minimum unit of progress), but this step can OOM the card "
                    "after the layout freeze. A prefill row is narrowed to fit before "
                    "it reaches here, so this names a row whose cost is not in its "
                    "token count. Lower --max-batch, lower --gpu-memory-utilization, "
                    "or shorten the context.",
                    model.demand_bytes(
                        prefill_tokens=prefill_tokens,
                        rows=rows,
                        gather_kv_tokens=gather_kv_tokens,
                        query_tokens=query_tokens,
                    )
                    // (1024 * 1024),
                    model.budget_bytes // (1024 * 1024),
                )
            return True
        _ACTIVATION_DEFERRED.fired = 1
        return False

    def schedule(self, *, _now: float | None = None) -> list[tuple[Request, int]]:
        """Return ``[(req, num_tokens_this_step), ...]`` for one step.

        ``_now`` — explicit clock injection for the duplex-lane deadline
        check below (mirrors the ``_now`` convention already used by
        :mod:`arbi_serve.scheduler.multi_group`). Two real callers now:
        a test injecting a synthetic clock, and ``run_forever``'s
        duplex pre-schedule hook, which must evaluate
        :meth:`duplex_tick_due` and then call this method against the SAME
        clock reading — otherwise the deadline could cross between the two
        calls and the hook would prepare a frame for a tick that does not
        fire (or, worse, not prepare one for a tick that does). Ordinary
        callers omit it.

        The default clock is :func:`time.monotonic`, NOT :func:`time.time`:
        the duplex frame grid is a real-time media cadence, and the wall
        clock is steerable. ``Request.next_duplex_deadline`` is an absolute
        instant on this clock, so an NTP step backwards parks every live
        duplex session for the size of the step (every deadline is suddenly
        in the future, and only a timer can fire the lane), while a step
        forwards resyncs the grid. Neither is hypothetical on a session
        whose configured ceiling is ``duplex_max_session_s`` and on hosts
        where chrony slews continuously. Every reader of that field must
        use the same clock; ``run_forever``'s idle-park cap is the only
        other one. Design doc §7.18.
        """
        if self._admission_burst is not None and not self._admission_burst.allow(self):
            return []
        # ── Duplex-lane exclusivity gate ────────────────────────────────
        # "A tick either serves the duplex lane exclusively, or serves
        # everything else exclusively -- never both" (design doc §2.2) --
        # the readiness/deadline predicate itself lives in
        # :meth:`duplex_tick_due` so ``run_forever``'s pre-schedule hook
        # can ask the SAME question, against the SAME clock reading,
        # before this call (design doc §7.9).
        now = _now if _now is not None else time.monotonic()
        if self.duplex_tick_due(now) and not self.duplex_lane_should_yield():
            # Fairness / no mid-flight preemption (design doc §6 decision
            # point 1, recommended default): a due duplex deadline gets
            # first pick of the NEXT tick, never interrupts an in-progress
            # ordinary batch -- so checking this at the very top of
            # ``schedule()``, before any ordinary slate work begins, is
            # itself the whole mechanism. Bounded by one tick's wall time.
            #
            # ``duplex_lane_should_yield`` is the bound on the OTHER
            # direction (design doc §7.21): exclusivity is a scoped trade
            # for a paced session, which takes a small minority of steps,
            # and unbounded starvation for an unpaced one, which is due on
            # every iteration. After
            # ``batch_cfg.duplex_lane_max_consecutive_ticks`` back-to-back
            # duplex steps, one step goes to ordinary traffic — but only
            # when there is ordinary traffic to give it to, so a lone
            # duplex session's grid is untouched.
            self._duplex_consecutive_ticks += 1
            # This tick is the duplex lane's, exclusively, so the wall time
            # either side of it prices neither pacing term.
            self._coadmit_pacer.break_interval()
            self._publish_step_page_hold(0)
            return self._build_duplex_slate(now)
        self._duplex_consecutive_ticks = 0
        begin = getattr(self.page_table, "begin_step", None)
        if begin is not None:
            # Before this tick allocates anything: the sliding-window pool is
            # sized for each live window plus one step's writes.
            begin()
        # Closes the previous tick's wall interval on the SAME clock reading
        # the duplex deadline above already took, and opens this one. A duplex
        # tick is deliberately not sampled: it serves its lane exclusively, so
        # its interval describes neither term of the pacing ratio.
        self._coadmit_pacer.open_tick(now)
        if self._task_queues is not None:
            self._task_queues.begin_step()

        slate: list[tuple[Request, int]] = []
        token_budget = min(self.batch_cfg.max_batched_tokens, self.step_token_cap)
        # The OTHER card's per-tick token budget, for a prefill row that runs
        # unsharded on the PEER PP rank (``ARBI_PP_PREFILL_SOLO_BESIDE_
        # DECODE``, host == peer): that chunk is a forward on the other GPU,
        # so charging it to this rank's ``token_budget`` — one scalar every
        # row draws from — let a 2048-token chunk of a long prompt here
        # consume the whole budget every tick and hold a co-admitted short
        # prompt bound for the peer out of the slate until the long prefill
        # ended (live: a 25 s first token for an 80-token prompt beside a
        # 128k one). See :meth:`_prefill_runs_on_peer`.
        peer_token_budget = self.batch_cfg.max_batched_tokens
        batch_left = self.batch_cfg.max_batch
        bs = self.cache_cfg.block_size
        # Per-step page-commit tally. Every row appended to the slate will
        # allocate its pages LATER (``allocate_slots`` inside the forward),
        # so the page table's free count is static across this whole
        # ``schedule()`` call. Without the tally, N rows that each cross a
        # page boundary all pass ``can_allocate`` against the SAME free
        # count and the step dies in ``allocate_slots`` ("pool exhausted").
        # Every admission gate below checks
        # ``available_pages() - pages_committed >= pages_needed`` (via
        # :meth:`_can_allocate_reserved`) and increments the tally as its
        # row is appended — over-commit becomes admission backpressure
        # (preempt / defer), never a crash. Prefill rows reserve
        # ``ceil(want / bs)`` pages — a mid-page continuation may need one
        # page fewer, so the tally is conservative by at most one page per
        # prefill row (backpressure, never under-reservation).
        pages_committed = 0
        # Per-step forward-ACTIVATION tally, the sibling of ``pages_committed``
        # (:mod:`arbi_serve.scheduler.activation_budget`). Rows and prefill
        # tokens accumulate; the gather is a MAX, not a sum, because tkv's
        # padded gather needs ``B == 1`` — a second prefill row on the slate
        # removes it rather than doubling it, so the largest single row bounds
        # the step. Inert (all three stay at zero's cost) until a boot arms the
        # model.
        act_prefill_tokens = 0
        act_rows = 0
        act_gather_tokens = 0
        # The step's EXTRA decode-row query tokens: the ``K`` drafts each
        # MTP-opted row's verify pass runs beside its committed tail. A SUM, not
        # a max — every opted row on the slate runs its drafts through the same
        # forward — and the sibling of the ``1 + K`` page extension
        # :meth:`_decode_page_commit` already commits for the same rows.
        act_query_tokens = 0

        # Frozen flex rows retake their recurrent rows before deferred flex
        # admits can. Then the deferred pen, between forwards (its self-heal
        # does CUDA work), and before manage() so a re-admit is visible now.
        if self.suspended and not self.parking_enabled:
            self._resume_frozen_without_parking()
        if self._deferred_admits:
            self._drain_deferred_admits()

        # Suspended-job KV offload management. Decide BEFORE building the
        # slate so the suspend frees pages + the resume re-populates running.
        if self.parking_enabled:
            self._offload_manager.manage()

        # Per-step slate-sizing knobs (depth-first chunk_prefill
        # cap, interactive-present gate, batch-only step caps) — pure
        # host-side arithmetic, see
        # :func:`arbi_serve.scheduler.step_budget.compute_step_budget`.
        # Unpacked into locals so the loop bodies (which mutate
        # ``batch_rows_left`` / ``batch_tokens_left``) stay byte-identical.
        budget = compute_step_budget(self)
        chunk_cap_this_step = budget.chunk_cap_this_step
        interactive_present = budget.interactive_present
        batch_rows_left = budget.batch_rows_left
        batch_tokens_left = budget.batch_tokens_left
        batch_prefill_cap = budget.batch_prefill_cap

        # Recurrent (GDN/Mamba/ShortConv) prefill is CHUNKED like every
        # other model: ``chunk_prefill`` is a LIVE per-row cap for
        # recurrent rows too, so ``want = min(remaining, chunk_prefill,
        # token_budget)`` everywhere. Rationale (c64 long-context profiling
        # dive): the former ``_no_chunk_recurrent`` bypass sized the row at
        # ``min(remaining, max_batched_tokens)`` — ONE giant eager varlen
        # forward per 16k prompt, whose per-token prefill speed is WORSE
        # than the chunk=2048 Turbo-prefill/split-D optimum. Chunking keeps the
        # per-token efficiency at the chunk_prefill optimum while a big
        # ``max_batched_tokens`` still packs MANY requests' chunks into
        # one step to drain the c64 backlog — the per-row cap and the
        # per-step aggregate budget are independent knobs. (The earlier
        # "chunking regressed c64 TTFT" result was the LEGACY hatch below,
        # which ALSO caps the per-step aggregate to one 2048 rung — that
        # aggregate cap, not the per-row chunking, lost the 16384-packed
        # multi-request prefill throughput.)
        #
        # Recurrent-state correctness across chunks: the state threads
        # chunk-to-chunk through the EXISTING GDN/Mamba slab seam — the
        # prefill forward gathers the row's conv + recurrent slab state
        # (``index_select``), runs the chunk kernel with
        # ``initial_state``, and scatters the final state back
        # (``index_copy_`` / ``_scatter_recurrent``) EVERY forward (see
        # ``_gdn_fla.py::_forward_prefill_fla``). Savepoint-resume and the
        # legacy hatch already exercise exactly this mid-prompt
        # continuation path.
        recur_step_cap: int | None = None
        # A prefill chunk sharing its step with a DECODING row is that row's
        # inter-token time — it advances one step per chunk.
        if budget.coadmit_prefill_cap is not None:
            chunk_cap_this_step = min(chunk_cap_this_step, budget.coadmit_prefill_cap)
        pf = _pf.partial_first_step(self, chunk_cap_this_step, interactive_present)
        # Remaining PREFILL-token headroom for this step, bounded so the
        # aggregate num_tokens (prefill chunks + 1-per-decode-row) never
        # exceeds the captured top rung — pad-up then lifts it onto that rung.
        # We RESERVE one slot per running-DECODING row UP FRONT (subtract
        # their count from the cap) rather than decrementing as decode rows
        # are appended: a prefill row processed BEFORE a decode row in the
        # ``running`` order would otherwise grab the full cap and a later
        # decode push the total to ``top_rung + 1`` (the 2049-token off-rung
        # miss). With the reservation, prefill is capped to ``top_rung −
        # n_running_decode`` and decode rows fill the reserved slots, so the
        # sum is ``<= top_rung`` by construction. Full-cached admits (1
        # decode token each) still decrement explicitly below — they're new
        # decode rows not in the reservation. Decode rows already reserved
        # do NOT decrement again.
        recur_step_left: int | None = None
        if recur_step_cap is not None:
            # Reserve one slot per running-DECODING row up front (so a prefill
            # row processed before a decode row in ``running`` order can't
            # grab the full cap and let the decode push num_tokens to
            # ``top_rung + 1``). Plus a ``max_batch`` SAFETY CUSHION for the
            # decode rows that materialize DURING this slate build — running-
            # PREFILLING rows that finish their last chunk and flip to decode,
            # and fresh full-cached (radix-hit) admits. Both emit a decode
            # token this step but aren't in the running-DECODING count taken
            # here; without the cushion they push num_tokens off-rung (the
            # 2049-token miss). Over-reserving only shrinks the prefill chunk
            # by a bounded amount — harmless to the cudagraph win, and the
            # guarantee (num_tokens <= top_rung) is what the strict miss=0
            # acceptance needs.
            n_running_decode = sum(1 for r in self.running if r.state == RequestState.DECODING)
            cushion = min(int(self.batch_cfg.max_batch), batch_left)
            recur_step_left = max(0, recur_step_cap - n_running_decode - cushion)

        # 1+2: continue running. ``slate_req_ids`` tracks ids already on
        # the in-progress slate; threaded into ``_preempt_for_space`` so it
        # never evicts a request whose slate row points at the same live
        # ``Request`` (preempting in-place would stale the prompt slice or
        # empty ``prompt_token_ids`` — the chunk_prefill=256 IndexError).
        slate_req_ids: set[int] = set()
        for req in pf.running_rows(self.running) if pf is not None else list(self.running):
            if batch_left <= 0 or (token_budget <= 0 and peer_token_budget <= 0):
                break
            if req.is_duplex_frame:
                # Duplex-lane exclusivity gate (see the top of
                # ``schedule()``): this is an ORDINARY tick, so any
                # duplex-lane row is excluded outright, not merely
                # deprioritized -- it stays in ``self.running`` with its
                # KV/Mamba state intact and is served only on a duplex
                # tick. Mirrors the batch-suspended-while-interactive-
                # present skip immediately below, one priority tier up.
                continue
            if req.is_flex:
                if interactive_present and flex_prefill_yields(self, req, budget.flex_drain_row):
                    continue
                # Batch-only step: enforce the small-step caps so an
                # interactive request that arrives mid-step waits at most
                # one SMALL batch forward.
                if batch_rows_left is not None and batch_rows_left <= 0:
                    continue
                if batch_tokens_left is not None and batch_tokens_left <= 0:
                    continue
            if req.state == RequestState.DECODING:
                if token_budget <= 0:
                    # This rank's budget is spent; only a peer-bound prefill
                    # row can still go this tick (the loop guard above).
                    continue
                # Pages this decode token will grab in ``allocate_slots``
                # (0 or 1). Read from the page-table length via
                # :meth:`_decode_page_commit`, NOT ``req.total_length`` —
                # see that method for the c64×16k off-by-one that made the
                # old ``total_length % bs`` predicate miss every crossing.
                dec_pages = self._decode_page_commit(req)
                # ``slate_req_ids | {req.request_id}``: exclude the row being
                # built from the victim pool. ``req`` is not on the slate yet
                # when the preemptor runs, so the slate-exclusion alone let
                # the preemptor pick ``req`` ITSELF as victim (most-recent-
                # first ordering) — rebuilding its prompt / resetting its
                # decode state while this branch then appended the stale row.
                # That self-preempt is the origin of the SPMD TP2 crash
                # chain (see ``finished``'s waiting-purge note).
                # Gate on the row's FULL page demand (``dec_pages * bs``
                # tokens ceil-divides to exactly ``dec_pages`` pages) — an
                # MTP verify row can need >1 page (tail + K drafts crossing
                # a boundary), and the old flat ``1``-token check passed on a
                # single free page while ``allocate_draft_slots`` demanded two.
                if (
                    dec_pages > 0
                    and not self._can_allocate_reserved(dec_pages * bs, pages_committed)
                    and not self._preempt_until_allocatable(
                        dec_pages * bs,
                        slate_req_ids | {req.request_id},
                        admitting_is_batch=req.is_flex,
                        reserved_pages=pages_committed,
                    )
                ):
                    if slate or not self._end_sole_row_at_ceiling(req, dec_pages, slate_req_ids):
                        break
                    continue
                row_query = self._query_charge(req)
                if not self._activation_admits(
                    prefill_tokens=act_prefill_tokens,
                    rows=act_rows + 1,
                    gather_kv_tokens=act_gather_tokens,
                    query_tokens=act_query_tokens + row_query,
                    slate_is_empty=not slate,
                ):
                    break
                slate.append((req, 1))
                slate_req_ids.add(req.request_id)
                act_rows += 1
                act_query_tokens += row_query
                # This decode row grabs ``dec_pages`` fresh pages in
                # ``allocate_slots`` — commit them so later rows this step
                # see the reduced availability.
                pages_committed += dec_pages
                token_budget -= self._decode_row_step_tokens(req)
                batch_left -= 1
                # Running-decode rows are pre-reserved in ``recur_step_left``
                # (subtracted up front from the cap) so we do NOT decrement
                # again here — that would double-count and starve prefill.
                if req.is_flex:
                    if batch_rows_left is not None:
                        batch_rows_left -= 1
                    if batch_tokens_left is not None:
                        batch_tokens_left -= 1
            elif req.state == RequestState.PREFILLING:
                if pf is not None and pf.defer(req):
                    continue  # revisited after the decode rows (partial_prefill_first)
                if self._solo_prefill_paced_out(req):
                    # ARBI_PP_COADMIT_PREFILL_EVERY_N. Same shape as the two
                    # skips above: the row stays in ``self.running`` with its
                    # state intact and is served on a later tick.
                    continue
                on_peer = self._prefill_runs_on_peer(req)
                row_budget = peer_token_budget if on_peer else token_budget
                if pf is not None and not on_peer:
                    row_budget = pf.row_budget(req, row_budget)
                if row_budget <= 0:
                    continue
                want = min(
                    req.num_remaining_prompt,
                    chunk_cap_this_step,
                    row_budget,
                )
                # Recurrent step-aggregate cap (cudagraph coverage): bound
                # this step's total tokens to the captured piecewise top rung
                # so num_tokens stays pad-up-able onto a graph. A peer-bound
                # chunk is not part of this rank's forward and is not capped.
                # ``recur_step_left`` is the remaining headroom this step;
                # stop adding prefill once it is exhausted.
                if recur_step_left is not None and not on_peer:
                    if recur_step_left <= 0:
                        continue
                    want = min(want, recur_step_left)
                # Batch-only prefill chunks are also bounded by the
                # batch step-token cap so a long batch prefill can't
                # inflate the one-step interactive wait. Pillar A applies
                # the TIGHTER ``batch_prefill_cap`` to prefill chunks
                # specifically (decode rows are unaffected).
                if req.is_flex:
                    if batch_tokens_left is not None:
                        want = min(want, batch_tokens_left)
                    if batch_prefill_cap is not None:
                        want = min(want, batch_prefill_cap)
                want = self._activation_chunk_cap(
                    req,
                    want,
                    act_prefill_tokens=act_prefill_tokens,
                    act_rows=act_rows,
                    act_gather_tokens=act_gather_tokens,
                    act_query_tokens=act_query_tokens,
                    slate_is_empty=not slate,
                )
                # The step is charged the UNTRIMMED width: the tokens the
                # fold-grid trim gives up do not start another prefill row.
                step_take = want
                want = self._fold_align_prefill_end(req, want, can_defer=bool(slate))
                want = self._prefill_handoff_cap(req, want)
                if want <= 0:
                    continue
                # Self-exclusion + loop-until-allocatable — same rationale as
                # the decode-boundary branch above. THIS branch is where the
                # ab_main_spmd1 crash started: want=2047 (a mid-prefill
                # continuation), one preempt attempt picked the continuation
                # request ITSELF as victim (it was not yet on the slate),
                # rebuilt its prompt to the 1 consumed token, and the stale
                # (req, 2047) row was appended anyway with no re-check —
                # ``allocate_slots`` then raised "pool exhausted (after
                # eviction)" and the SPMD step refused the slate.
                if not self._can_allocate_reserved(
                    want, pages_committed
                ) and not self._preempt_until_allocatable(
                    want,
                    slate_req_ids | {req.request_id},
                    admitting_is_batch=req.is_flex,
                    reserved_pages=pages_committed,
                ):
                    break
                row_gather = self._gather_charge(req, want)
                if not self._activation_admits(
                    prefill_tokens=act_prefill_tokens + want,
                    rows=act_rows + 1,
                    gather_kv_tokens=max(act_gather_tokens, row_gather),
                    # A PREFILL row runs no drafts of its own
                    # (``_bucket_mtp_k_uniform`` skips ``is_prefill`` rows), but
                    # the decode rows already on this slate do, in the same
                    # forward — so the standing tally is carried, not reset.
                    query_tokens=act_query_tokens,
                    slate_is_empty=not slate,
                ):
                    break
                slate.append((req, want))
                if getattr(req, "_pp_prefill_solo", False):
                    self._coadmit_pacer.note_solo_chunk_slated()
                slate_req_ids.add(req.request_id)
                act_rows += 1
                act_prefill_tokens += want
                act_gather_tokens = max(act_gather_tokens, row_gather)
                pages_committed += -(-want // bs)
                if on_peer:
                    peer_token_budget -= step_take
                else:
                    token_budget -= step_take
                batch_left -= 1
                if recur_step_left is not None and not on_peer:
                    recur_step_left -= step_take
                if req.is_flex:
                    if batch_rows_left is not None:
                        batch_rows_left -= 1
                    if batch_tokens_left is not None:
                        batch_tokens_left -= step_take

        # 3: admit new requests from the waiting queue. Use
        # ``num_remaining_prompt`` (not ``len(prompt_token_ids)``) so a
        # radix-cache hit at admission doesn't re-prefill cached tokens;
        # ``num_remaining_prompt == 0`` (full prompt cached) skips prefill
        # entirely and admits directly into decode with one token of work.
        #
        # Priority-aware admission (opportunistic batch). The waiting queue
        # is FCFS within a priority class; interactive is head-of-queue
        # first. Low-priority ``"flex"`` requests start prefill ONLY once
        # the interactive backlog has drained to at/below
        # ``batch_admit_waiting_watermark`` (default 0) AND budget remains,
        # keeping interactive TTFT independent of the batch backlog. The
        # all-interactive default path skips the priority bookkeeping
        # entirely (``any_batch_waiting`` is False), so it stays
        # byte-identical to the pre-priority scheduler.
        any_batch_waiting = self.any_batch_waiting()
        prefix_context = None
        prefix_policy_enabled = False
        # ``_prefix_cache_serves`` gates the policy too: grouping holds
        # followers behind a leader so they can hit the prefix the leader
        # publishes, and where no prefix can be served that is a head-of-line
        # wait for nothing.
        if self._prefix_incremental_publish and self._prefix_cache_serves and grouping_enabled():
            # ``prefix_grouping`` is scope="runtime", fresh-read per step
            # (see config_overrides.py) — a live admin flip must engage the
            # grouper on the NEXT step, with no member rebuild. ``self.grouper``
            # is lazily built here the first time the flag reads on: it can
            # still be ``None`` at this point if the process booted (or last
            # rebuilt a member) with the flag off, in which case
            # ``build_grouper_from_env`` was never called again to notice a
            # later flip (the root cause this lazy build fixes). Once built,
            # the SAME object is reused (never rebuilt) across an on/off/on
            # flip so its cross-step ``blocked_possible`` hint survives; only
            # ``window`` is re-resolved fresh every step, off the same
            # fresh-read flag that carries the mode.
            if self.grouper is None:
                self.grouper = build_grouper_from_env(block_size=bs)
            else:
                refresh_grouper_window(self.grouper)
            prefix_policy_enabled = self.grouper is not None
        if prefix_policy_enabled:
            leaders = tuple(
                req
                for req, _n in slate
                if req.state == RequestState.PREFILLING
                and bool(getattr(req.sampling, "cache_enabled", True))
            )
            blocked_waiting = False
            if not leaders and self.grouper.blocked_possible:
                # Only a workload that previously found a real collision
                # enters this scan. Cache-off traffic never does.
                blocked_waiting = any(
                    bool(getattr(req, "_prefix_serial_blocked", False)) for req in self.waiting
                )
                self.grouper.blocked_possible = blocked_waiting
            if leaders or blocked_waiting:
                publish_granularity = prefix_publish_grid(self, bs)
                prefix_context = self.grouper.serial_context(
                    leaders,
                    publish_granularity=publish_granularity,
                )
        # Pageless whole prompts (:meth:`set_pageless_whole_prompts_fn`) never
        # share a slate with a paged row: the cache-free ops serve a step only
        # when EVERY row is a whole prompt.
        pageless_ok = not slate and bool((self._pageless_whole_prompts_fn or bool)())
        pageless_rows = 0
        while self.waiting and batch_left > 0 and (token_budget > 0 or peer_token_budget > 0):
            # ARBI_PARTIAL_PREFILL_FIRST: the oldest waiting partial prefill first.
            req = pf.next_partial(token_budget, prefix_context) if pf is not None else None
            if req is None:
                req = self._next_waiting_candidate(any_batch_waiting, prefix_context)
            if req is None:
                # Only batch requests remain but the interactive backlog
                # / budget gate refuses them this step — stop admitting.
                break
            # A candidate pinned to prefill solo on the PEER draws the other
            # card's budget (see ``peer_token_budget`` above); its host was
            # pinned at admission, before it entered ``waiting``.
            on_peer = self._prefill_runs_on_peer(req)
            if (peer_token_budget if on_peer else token_budget) <= 0:
                break
            if prefix_context is not None and bool(getattr(req, "_prefix_serial_refresh", False)):
                if not self._refresh_waiting_prefix(req):
                    # Rebinding can defer on recurrent-row pressure. The
                    # total admission wrapper has already moved the request
                    # to the appropriate holding queue or terminal path.
                    continue
                req._prefix_serial_refresh = False
                req._prefix_serial_blocked = False
            if req.is_flex:
                # Interactive-always-priority gate: a batch request is
                # admitted ONLY when NO interactive request is present
                # anywhere (admission starts with a prefill chunk, the
                # compute interactive owns). ``interactive_present`` also covers
                # running interactive that the waiting-only scan can't see.
                if interactive_present:
                    break
                # Batch-only admission honours the small-step caps so the
                # one-step interactive wait stays bounded.
                if batch_rows_left is not None and batch_rows_left <= 0:
                    break
                if batch_tokens_left is not None and batch_tokens_left <= 0:
                    break
            lost = getattr(self.page_table, "swa_window_lost", None)
            if lost is not None and lost(req.request_id):
                # Under SPMD a queued match holds no sliding window, so the one
                # it resumes from can be reclaimed while it waits. Give the
                # match back; the re-bind below re-claims what is still
                # resident, which is what every rank's tree will resolve.
                self._release_waiting_prefix_hold(req)
            remaining = req.num_remaining_prompt
            if remaining == 0:
                # Full cached match — every prompt page is aliased from the
                # radix tree; no prefill compute needed. Admit directly into
                # decode WITH 1 token of work this step (recompute logits at
                # the last prompt position, harmlessly rewriting that slot's
                # K/V) so the sampler can pick the first output token.
                # Producing the row this step (vs promote-and-pick-up-next)
                # avoids a 0-row slate → the 500 ms ``_wakeup`` first-token
                # penalty. Mirrors the running-DECODING page-boundary gate.
                # Pages this full-cached admit's first decode token grabs
                # (see :meth:`_decode_page_commit`). A radix full-hit's KV
                # is entirely shared, so the recompute-logits token opens a
                # fresh PRIVATE page regardless of prompt-length alignment —
                # ``pages_needed`` credits the shared prefix and returns the
                # right count where the old ``total_length % bs`` predicate
                # under-reserved on an unaligned prompt length.
                adm_pages = self._decode_page_commit(req)
                # Loop-until-allocatable (see ``_preempt_until_allocatable``):
                # one victim's freed pages may not cover even a single new
                # page when its pages are radix-shared. ``req`` is WAITING
                # here (never a preempt victim), so no self-exclusion needed.
                if (
                    adm_pages > 0
                    and not self._can_allocate_reserved(adm_pages * bs, pages_committed)
                    and not self._preempt_until_allocatable(
                        adm_pages * bs,
                        slate_req_ids,
                        reserved_pages=pages_committed,
                        admitting=req,
                    )
                ):
                    break
                row_query = self._query_charge(req)
                if not self._activation_admits(
                    prefill_tokens=act_prefill_tokens,
                    rows=act_rows + 1,
                    gather_kv_tokens=act_gather_tokens,
                    query_tokens=act_query_tokens + row_query,
                    slate_is_empty=not slate,
                ):
                    break
                self._waiting_remove(req)
                set_state(req, RequestState.DECODING)
                if prefix_policy_enabled and bool(getattr(req.sampling, "cache_enabled", True)):
                    req._prefix_serial_started = True
                self._running_add(req)
                if self._metrics is not None:
                    self._metrics.queue_dec()
                    self._metrics.decode_inc()
                    self._metrics.prefix_cache_full_hit_inc()
                slate.append((req, 1))
                slate_req_ids.add(req.request_id)
                act_rows += 1
                # A full-cached admit enters DECODING with one token of work,
                # and ``_bucket_mtp_k_uniform`` sees it as a decode row on this
                # very slate — so it can verify this step and is charged its
                # drafts like any other, exactly as its page commit above is.
                act_query_tokens += row_query
                pages_committed += adm_pages
                token_budget -= self._decode_row_step_tokens(req)
                batch_left -= 1
                # Full-cached admit produces 1 decode token — count it
                # against the recurrent step cap (see the running-decode
                # branch).
                if recur_step_left is not None:
                    recur_step_left -= 1
                if req.is_flex:
                    if batch_rows_left is not None:
                        batch_rows_left -= 1
                    if batch_tokens_left is not None:
                        batch_tokens_left -= 1
                continue
            want = min(
                remaining,
                chunk_cap_this_step,
                peer_token_budget if on_peer else token_budget,
            )
            # Recurrent step-aggregate cap (cudagraph coverage) — see the
            # running-prefill branch above. Stop admitting fresh prefill
            # once this step's token headroom is spent so num_tokens stays
            # pad-up-able onto a captured piecewise rung.
            if recur_step_left is not None and not on_peer:
                if recur_step_left <= 0:
                    break
                want = min(want, recur_step_left)
            if req.is_flex:
                if batch_tokens_left is not None:
                    want = min(want, batch_tokens_left)
                if batch_prefill_cap is not None:
                    want = min(want, batch_prefill_cap)
            want = self._activation_chunk_cap(
                req,
                want,
                act_prefill_tokens=act_prefill_tokens,
                act_rows=act_rows,
                act_gather_tokens=act_gather_tokens,
                act_query_tokens=act_query_tokens,
                slate_is_empty=not slate,
            )
            step_take = want
            want = self._fold_align_prefill_end(req, want, can_defer=bool(slate))
            want = self._prefill_handoff_cap(req, want)
            if want <= 0:
                break
            pageless = pageless_ok and self._pageless_whole_prompt(req, want)
            if not pageless and (pageless_rows or self._windowless_defers()):
                break
            if (
                not pageless
                and not self._can_allocate_reserved(want, pages_committed)
                and not self._reclaim_idle_prefix_holds(
                    want, pages_committed, slate_req_ids | {req.request_id}
                )
            ):
                # Same order the running branch takes: a queued row's idle
                # prefix hold is reclaimed before a running row is preempted
                # (:meth:`_reclaim_idle_prefix_holds`). This candidate's own
                # hold is excluded — it is about to use it.
                if not self._preempt_to_admit(slate_req_ids, req):
                    break
                continue
            row_gather = self._gather_charge(req, want)
            if not self._activation_admits(
                prefill_tokens=act_prefill_tokens + want,
                rows=act_rows + 1,
                gather_kv_tokens=max(act_gather_tokens, row_gather),
                # See the running-prefill branch: a prefill row runs no drafts,
                # the decode rows beside it in this forward do.
                query_tokens=act_query_tokens,
                slate_is_empty=not slate,
            ):
                break
            if (
                req.request_id in self._preempt_rebind_ids
                or req.request_id in self._released_hold_ids
            ):
                # This request gave its pages back — preempted earlier in
                # THIS ``schedule()`` call, or a queued prefix hold released
                # to the pool in an earlier one — and is now going onto the
                # slate that release made room for. Re-query the prefix
                # cache before it re-prefills a single token: its own pages
                # are still in the tree at ref 0. Deliberately here and not at the preempt —
                # the match ref-s those pages back up, which is only safe
                # for a request that is being admitted, never for one left
                # in ``waiting`` (see ``_rebind_preempted_prefix``).
                #
                # ``want`` was sized against the UN-matched remainder, so
                # it can now overshoot the prompt; clamp it. Everything the
                # row is charged for below reads the clamped value, and the
                # allocation + activation gates above passed against the
                # larger one, so the reservation is conservative in the
                # only direction that is safe.
                #
                # ``max_new_pages`` is this step's genuine headroom: a
                # matched page leaves ``available_pages()``, so the re-bind
                # must not take one that a row already on the slate has
                # been promised, nor the ones this row is about to
                # allocate. The gate above guarantees the difference is
                # non-negative.
                avail_fn = getattr(self.page_table, "available_pages", None)
                self._rebind_preempted_prefix(
                    req,
                    max_new_pages=(
                        None
                        if avail_fn is None
                        else int(avail_fn()) - pages_committed - -(-want // bs)
                    ),
                )
                want = min(want, req.num_remaining_prompt)
                step_take = min(step_take, want)
                if want <= 0:
                    # Unreachable: the re-bind caps its match one token
                    # below the rebuilt prompt precisely so a row remains.
                    raise RuntimeError(
                        f"Scheduler: preempt re-bind left request "
                        f"{req.request_id} with no prompt to feed "
                        f"(prompt_consumed={req.prompt_consumed}, "
                        f"prompt_len={len(req.prompt_token_ids)})."
                    )
                # The re-bind moved ``prompt_consumed``; re-trim so the
                # chunk still ends on the fold grid.
                want = self._prefill_handoff_cap(req, self._fold_align_prefill_end(req, want))
            self._waiting_remove(req)
            set_state(req, RequestState.PREFILLING)
            cache_enabled = bool(getattr(req.sampling, "cache_enabled", True))
            if prefix_policy_enabled and cache_enabled:
                req._prefix_serial_started = True
            self._running_add(req)
            if prefix_context is None and cache_enabled and prefix_policy_enabled:
                publish_granularity = prefix_publish_grid(self, bs)
                prefix_context = self.grouper.serial_context(
                    (), publish_granularity=publish_granularity
                )
            if prefix_context is not None and cache_enabled:
                prefix_context.add_leader(req)
            # Stamp the queued→prefill boundary (first scheduled step):
            # once-only, feeds the per-request ``queued`` / ``prefill``
            # span split + queue-wait metric.
            if req.timing is not None:
                req.timing.stamp_first_scheduled_step()
            if self._metrics is not None:
                self._metrics.queue_dec()
                self._metrics.prefill_inc()
            slate.append((req, want))
            slate_req_ids.add(req.request_id)
            act_rows += 1
            act_prefill_tokens += want
            act_gather_tokens = max(act_gather_tokens, row_gather)
            req.kv_pageless = pageless
            if pageless:
                pageless_rows += 1
            else:
                pageless_ok = False
                pages_committed += -(-want // bs)
            if on_peer:
                peer_token_budget -= step_take
            else:
                token_budget -= step_take
            batch_left -= 1
            if recur_step_left is not None and not on_peer:
                recur_step_left -= step_take
            if req.is_flex:
                if batch_rows_left is not None:
                    batch_rows_left -= 1
                if batch_tokens_left is not None:
                    batch_tokens_left -= step_take

        if pf is not None:
            pf.note_stop()
        # Per-tenant rate-limit + concurrency-cap admission filter.
        # Drops slate rows whose tenant has exhausted its quota; those
        # requests stay queued (waiting / running) and retry next step.
        # Zero-cost when every request is anon / UNLIMITED.
        slate = self._apply_tenant_quota(slate)

        # Admission-time MTP K-bucketing. The verify pass requires a
        # single uniform K every step; mixed-K slates are filtered HERE
        # so a K=7 request isn't throttled by a K=1 request sharing the
        # slate. See :meth:`_bucket_mtp_k_uniform` for the policy.
        bucketed = self._bucket_mtp_k_uniform(slate)
        # The preempt prefix re-bind is scoped to ONE ``schedule()`` call.
        # A victim this pass did not reach simply re-prefills: its pages
        # stay in the tree, so nothing is lost that a later admission's own
        # match could not recover. The scoping is what keeps the SPMD
        # amendment sound — the delta is built from the preempt log AFTER
        # this returns, so a re-bind that reached into the next tick would
        # move rank 0's page table with no row to carry it. (A ``schedule``
        # that RAISES leaves ids armed, and that is still sound for the
        # same reason: no delta was built, so nothing was drained, and the
        # entry the next call amends is the one that is still queued.)
        self._preempt_rebind_ids.clear()
        self._arm_fold_split(bucketed)
        # Open the prefill-rate interval for the step this slate becomes. The
        # third input to the disk tier's break-even is what a prefill costs
        # per token, and this call plus the one at the end of ``commit_state``
        # bracket exactly the work a resume would have skipped. Guarded for
        # the same reason its partner is: the snapshotter is None until the
        # scheduler finishes constructing.
        if self._savepoint_snapshotter is not None:
            self._savepoint_snapshotter.note_slate_dispatched(bucketed)
        # What this tick will spend its interval on, for the pacing ratio's
        # denominator. Inert once a value is pinned or derived.
        self._coadmit_pacer.note_slate(bucketed)
        pp_kv_handoff = getattr(self, "_pp_kv_handoff", None)
        if pp_kv_handoff is not None:
            pp_kv_handoff.note_slate(bucketed)
        self._publish_step_page_hold(pages_committed)
        return bucketed
# ---- scheduler_admission.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Pool-aware admission mixin (add / remove / recurrent-row self-heal).

Owns the request-lifecycle entry / exit points: :meth:`add` (total,
never raises), the recurrent-row deferral self-heal, and
:meth:`remove`.

Shared attributes are declared as class-level annotations (mirrors
:mod:`arbi_serve.cache._pool_base`) — the real values are set in
:meth:`Scheduler.__init__`.
"""

from __future__ import annotations

import contextlib
import logging
import time
from typing import TYPE_CHECKING

from arbi_serve.cache import _metrics as cache_metrics
from arbi_serve.cache import savepoint_resume_hash
from arbi_serve.cache._state_pool_common import pool_carries_recurrent_state
from arbi_serve.cache.radix_pagetable_offload import release_park_pins
from arbi_serve.engine.request import Request, RequestState, set_state
from arbi_serve.models.layer_spec import StateKind
from arbi_serve.scheduler._request_state_reach import (
    _max_reachable_context as _max_reachable_context,
)
from arbi_serve.scheduler.scheduler_counters import _discard_by_identity

_LOG = logging.getLogger("arbi_serve.scheduler")

if TYPE_CHECKING:
    from collections import deque
    from collections.abc import Callable

    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.config import CacheConfig
    from arbi_serve.kvtier.gate import RemoteGate
    from arbi_serve.scheduler.savepoint_admission import SavepointSnapshotter
    from arbi_serve.server.metrics import Metrics


class _DeferAdmission(Exception):
    """Internal signal: re-admit this request at the next ``schedule``.

    Raised by :meth:`Scheduler._add_inner` when the recurrent-row
    self-heal would need to park a resident batch job while a model
    forward is in flight (unsafe CUDA mutation). Caught by
    :meth:`Scheduler.add`, which re-queues the request for between-
    forwards re-admission. Never escapes the scheduler.
    """

    def __init__(self, req: Request) -> None:
        super().__init__(f"admission deferred for req {req.request_id}")
        self.req = req


class _AdmissionMixin:
    """Request-lifecycle admission entry / exit + recurrent-row self-heal."""

    #: The disk tier's admission gate (``kvtier.gate``), set at boot when the prefix tier
    #: has a disk arm. None everywhere else, and then admission is exactly what it was.
    _remote_gate: RemoteGate | None = None

    # ── Shared scheduler state (set in ``Scheduler.__init__``) ────────
    page_table: FlatPageTable | RadixPageTable
    pool: MultiStatePool
    primary_paged_kind: StateKind
    waiting: deque[Request]
    running: deque[Request]
    suspended: deque[Request]
    _deferred_admits: deque[Request]
    _dropped_suspended: list[Request]
    _n_deferred_interactive: int
    _metrics: Metrics | None
    _forward_in_flight_fn: Callable[[], bool]
    _spmd_deferred_release: Callable[[int], None] | None
    _savepoint_snapshotter: SavepointSnapshotter
    _preempt_rebind_ids: set[int]
    _released_hold_ids: set[int]
    cache_cfg: CacheConfig
    _prefix_cache_serves: bool
    _prefix_retention_serves: bool

    # ── Pool-aware admission ─────────────────────────────────────────

    def _has_recurrent_state(self) -> bool:
        """True iff the bound pool exposes a recurrent / short-conv view.

        Cached lazily on first call (admission is hot); defaults to False
        on mock pools without the predicate. Includes ShortConv (LFM2) as
        recurrent for the radix-cache gate — it carries the same
        per-request slab-row state GDN/Mamba do, which the token-id-only
        radix key can't capture.
        """
        cached = getattr(self, "_has_recurrent_state_cached", None)
        if cached is not None:
            return cached
        flag = pool_carries_recurrent_state(self.pool)
        self._has_recurrent_state_cached = flag
        return flag

    def add(self, req: Request) -> None:
        """Enqueue a freshly-arrived request.

        Wrapper over :meth:`_add_inner` that is **total** — it NEVER lets
        an exception escape. Two failure classes are handled:

        * :class:`_DeferAdmission` — the recurrent-row pool is full and a
          row cannot be reclaimed THIS instant (no parkable batch job, or a
          forward is in flight so the self-heal's CUDA suspend is unsafe).
          The rolled-back request (holds no GPU state) is re-queued on
          ``_deferred_admits`` and re-attempted at the top of a later
          :meth:`schedule` — strictly between forwards — once a running
          request finishes and frees a row. This is the
          queue-fairly-and-resume path for a burst whose concurrency
          exceeds the recurrent-row budget (``max_num_seqs`` on a hybrid
          GDN / Mamba model). The deferred admit is counted by the
          admission depth gate, so a SUSTAINED overload still backs off
          with a clean 429 at ``queue_depth_max`` instead of growing the
          deferred queue without bound.

        * Any OTHER exception (e.g. a savepoint best_match→get eviction
          race, an unexpected pool error) — finished cleanly via the
          dropped-job terminal path the run loop drains
          (``run_step.drain_dropped_suspended`` → ``on_finished``). Without
          this, the exception escapes into the cross-loop intake
          trampoline (``engine.loop_bridge.invoke_isolated``) which SWALLOWS
          it: the request would never finish, never stream a token, and the
          client would hang until its own (~300 s) timeout. Admission must
          never hang a request.
        """
        was_waiting_for_row = getattr(req, "_deferred_for_row", False)
        req._deferred_for_row = False
        if any(
            getattr(r, "_deferred_for_row", False)
            and (req.is_flex or not r.is_flex)  # interactive overtakes batch
            for r in self._deferred_admits
        ):
            # FCFS: a request is already waiting for a recurrent row. A newcomer taking the row a
            # finishing request just freed would starve it for as long as clients resubmit
            # instantly (eight looping short streams held a 43k-token prompt out for 11 minutes).
            self._deferred_admits.append(req)
            if not req.is_flex:
                self._n_deferred_interactive += 1
            return
        try:
            self._add_inner(req)
        except _DeferAdmission:
            self._deferred_admits.append(req)
            if not req.is_flex:
                self._n_deferred_interactive += 1
            if req._deferred_for_row and not was_waiting_for_row:
                # Once per request, not per drain: the holding queue's arrivals, by tier.
                cache_metrics.counter_inc(
                    "arbi_serve.scheduler.preempt_row_wait_total",
                    labels={"service_tier": "flex" if req.is_flex else "default"},
                )
            _LOG.debug("admission deferred (awaiting recurrent row) req=%s", req.request_id)
        except Exception:  # noqa: BLE001 — admission MUST NOT hang a request
            _LOG.exception("admission failed for req=%s; finishing as overloaded", req.request_id)
            # Best-effort cleanup of a partial admit (page refs / row /
            # queue membership) so the dropped request leaks nothing.
            with contextlib.suppress(Exception):
                self._waiting_remove(req)
            with contextlib.suppress(Exception):
                self._rollback_partial_admit(req)
            req.finish_reason = req.finish_reason or "overloaded"
            self._dropped_suspended.append(req)

    def _interactive_present(self) -> bool:
        """True iff any interactive request is queued, running, or deferred.

        Mirrors the slate-admission gate's notion of interactive presence
        so the row layer and the scheduling layer agree on when batch may
        make progress. Deferred admits count: an interactive request that
        rolled back for want of a row is still interactive demand.
        """
        if self._n_deferred_interactive > 0:
            return True
        # O(1) counters on the real Scheduler; the scan is for schedulers
        # that fabricate ``waiting`` / ``running`` without them.
        n_waiting = getattr(self, "_n_waiting_interactive", None)
        n_running = getattr(self, "_n_running_interactive", None)
        if isinstance(n_waiting, int) and isinstance(n_running, int):
            return (n_waiting + n_running) > 0
        return any(not r.is_flex for r in self.waiting) or any(not r.is_flex for r in self.running)

    def _rollback_partial_admit(self, req: Request) -> None:
        """Undo the page-table + per-request side effects of a partial
        :meth:`_add_inner` so the request can be cleanly re-admitted.

        Mirrors :meth:`remove` minus the queue removals (the request was
        never queued yet): releases radix refs + private pages, clears the
        state-handle pointer, resets prefill credit, restores ``WAITING``.
        """
        self.page_table.remove_request(req.request_id)
        req.state_handles.pop(self.primary_paged_kind, None)
        # The recurrent alloc FAILED (why we're deferring) so there's no
        # row to free; defensive in case a future caller defers post-alloc.
        free_recurrent = getattr(self.pool, "free_recurrent_state", None)
        if free_recurrent is not None:
            free_recurrent(req.request_id)
        req.prompt_consumed = 0
        req.cached_prefix_tokens = 0
        set_state(req, RequestState.WAITING)

    def _refresh_waiting_prefix(self, req: Request) -> bool:
        """Rebind a never-scheduled request to newly published prefix pages.

        Prefix-serial followers were registered when they arrived, before an
        active leader published its chunks. Re-running the ordinary admission
        transaction here refreshes both radix pages and recurrent savepoints.
        This happens between forwards and before the request's first slate, so
        SPMD's one-time AdmitRow observes only the refreshed state.
        """

        if not any(item is req for item in self.waiting):
            return False
        # This IS the ordinary admission transaction, radix match included,
        # so a preempt re-bind armed for the same request would re-run the
        # match a second time — a wasted free-and-re-register, and a second
        # count against the same tokens. Disarm.
        self._preempt_rebind_ids.discard(req.request_id)
        self._released_hold_ids.discard(req.request_id)
        self._waiting_remove(req)
        if self._metrics is not None:
            self._metrics.queue_dec()
        self._rollback_partial_admit(req)
        self.add(req)
        return any(item is req for item in self.waiting)

    def _release_waiting_prefix_hold(self, req: Request) -> int:
        """Give a WAITING request's matched prefix pages back to the pool.

        A prefix match ref-s the pages it aliases, so they leave
        ``available_pages()`` and stop being LRU-evictable. ``_add_inner``
        takes that match the moment a request ARRIVES, while it is still
        queued — so a queued request with a long cached prefix holds KV it
        cannot use against every request that could actually run, and the
        scheduler has no lever against it: preemption's victims are running
        rows, and this one is not running. When the held prefix is a large
        fraction of the pool, the row that IS running cannot reach the end
        of its own prompt, is dropped from the slate, is preempted for the
        next queued request, and restarts — the same prefix chunks forwarded
        forever with nothing finishing.

        :meth:`Preemptor.preempt_for_space` already states the invariant this
        restores: only rows that are running hold pages. It keeps it for a
        preempt victim by going page-less in ``waiting`` and claiming the
        match again at admission; this does the same for a queued request
        whose hold admission cannot honour — the pages drop to ref 0 (still
        in the tree, still matchable, now reclaimable by whoever needs them
        first) and the request re-claims what survives when it is admitted,
        through the same re-bind seam and the same per-step page budget.

        Returns the tokens released (0 when the request holds no match).
        """
        rid = req.request_id
        held = int(getattr(req, "cached_prefix_tokens", 0) or 0)
        if held <= 0 or req.state != RequestState.WAITING:
            return 0
        # Cache identity off the TABLE where it has one: the savepoint
        # admission's hybrid force-disable re-registers with the cache OFF,
        # and the Request does not carry that resolution.
        tenant_fn = getattr(self.page_table, "tenant_id_for", None)
        tenant_id = str(tenant_fn(rid)) if tenant_fn is not None else ""
        if not tenant_id:
            tenant_id = self._tenant_id_for(req)
        flag_fn = getattr(self.page_table, "cache_enabled_for", None)
        cache_enabled = (
            bool(flag_fn(rid))
            if flag_fn is not None
            else bool(getattr(req.sampling, "cache_enabled", True))
        )
        # BOTH flags, off the table. Carrying only the match flag here would
        # re-register a parkable request as unparkable the first time it
        # released a hold — the same conflation, one seam further along.
        retain_fn = getattr(self.page_table, "retain_enabled_for", None)
        retain_enabled = bool(retain_fn(rid)) if retain_fn is not None else cache_enabled
        # Releases the radix refs and the recurrent slab row — and the row
        # free is what cancels the queued savepoint restore keyed on the
        # match being dropped, so the KV credit and the recurrent state stay
        # resumed from the same token (#797).
        self._rollback_partial_admit(req)
        # Re-register PAGE-LESS: no prompt argument, so no match and no refs.
        self.page_table.add_request(
            rid,
            tenant_id=tenant_id,
            cache_enabled=cache_enabled,
            retain_enabled=retain_enabled,
        )
        req.state_handles[self.primary_paged_kind] = self.page_table.page_ids(rid)
        alloc_recurrent = getattr(self.pool, "alloc_recurrent_state", None)
        if alloc_recurrent is not None:
            # The row this request just gave back; the pool cannot refuse it.
            alloc_recurrent(rid)
        # Arm the admission-time re-bind, as a preempt does — on the set
        # that survives the step, since the row this release made way for
        # has to finish before this one is admitted. SPMD is
        # unaffected either way: the request has never held a slate row, so
        # no ``AdmitRow`` has ridden the wire yet and the one that eventually
        # does reads whatever match is current.
        self._released_hold_ids.add(rid)
        cache_metrics.counter_inc(
            "arbi_serve.scheduler.waiting_prefix_hold_released_total",
            labels={"service_tier": "flex" if req.is_flex else "default"},
        )
        cache_metrics.counter_inc(
            "arbi_serve.scheduler.waiting_prefix_hold_released_tokens",
            value=held,
            labels={"service_tier": "flex" if req.is_flex else "default"},
        )
        _LOG.debug(
            "released waiting prefix hold: req=%s tokens=%s available=%s",
            rid,
            held,
            getattr(self.page_table, "available_pages", lambda: -1)(),
        )
        return held

    def _rebind_preempted_prefix(self, req: Request, *, max_new_pages: int | None = None) -> int:
        """Re-query the prefix cache for a preempted request being admitted.

        ``Preemptor.preempt_for_space`` commits the victim's completed
        pages into the radix tree and then releases them: they stay in the
        tree at ref 0, so at this instant every page the victim is about to
        recompute is still there. Nothing in the waiting-admit path looks —
        the only ``match_prefix`` site is :meth:`_add_inner`, which a
        preempted request never re-enters — so the victim re-prefills from
        token 0 and then dedups its recomputed pages onto the ones it just
        recomputed. Full cost paid, nothing saved.

        Called at the point of ADMISSION, deliberately, not at the preempt:
        the match ref-s the pages back up and they stop being evictable, so
        a victim that took them while still in ``waiting`` would hold the
        pool against every request that could actually run — a state the
        scheduler cannot escape, since preemption is the only lever it has
        and its victims are the ones holding the pages. Here the request
        goes onto this step's slate, so it holds pages exactly like any
        other running row. ``test_a_tight_pool_still_makes_progress``
        (``tests/test_preempt_prefix_reuse.py``) is the regression.

        Runs the SAME transaction a fresh admission does —
        :meth:`SavepointSnapshotter.resolve_resume` /
        :meth:`~SavepointSnapshotter.resolve_match` /
        :meth:`~SavepointSnapshotter.queue_resume` — rather than restating
        any of it, so the hybrid rules hold identically: the match is
        capped at the recurrent savepoint's coverage, a coverage shortfall
        drops the savepoint, and a hybrid match with no savepoint
        force-disables the cache instead of decoding against zero GDN
        state. ``readmit=True`` is the only difference: the request is
        already registered (page-less), so the registration must go through
        the free-and-re-register seam that carries its cache identity.

        Two caps, both measured, neither a constant:

        * one token below the rebuilt prompt, so the row this admission is
          building always has something to feed — a FULL match belongs to
          the ``num_remaining_prompt == 0`` branch, which this call site is
          already past;
        * ``max_new_pages``, the pages this step can still spare. A matched
          page moves from evictable to ref-ed, so it leaves
          ``available_pages()`` — the same quantity every slate row's
          allocation gate reads. The caller computes it as availability
          minus what the rows already on the slate reserved minus what this
          row still needs, so the re-bind can never take a page a slate-mate
          was already promised — without it an earlier decode row reaches
          ``allocate_slots`` to find the pool gone. ``None`` leaves only the
          first cap, for page tables that model no availability.

        Returns the credited ``match_len`` (0 on a miss, on the flat page
        table, or when the request holds no rebuilt prompt).
        """
        rid = req.request_id
        self._preempt_rebind_ids.discard(rid)
        self._released_hold_ids.discard(rid)
        seq = req.cache_token_ids()
        if not seq:
            return 0
        from arbi_serve.scheduler.prefill_cache_limit import resume_match_limit

        cap = resume_match_limit(req, len(seq) - 1)
        if max_new_pages is not None:
            cap = min(cap, max(0, int(max_new_pages)) * self.cache_cfg.block_size)
        # Identity off the TABLE, not off the Request: the table entry is
        # what carries a previous admission's RESOLVED cache flag (the
        # hybrid force-disable), which the Request does not.
        tenant_fn = getattr(self.page_table, "tenant_id_for", None)
        tenant_id = str(tenant_fn(rid)) if tenant_fn is not None else ""
        if not tenant_id:
            tenant_id = self._tenant_id_for(req)
        flag_fn = getattr(self.page_table, "cache_enabled_for", None)
        cache_enabled = bool(flag_fn(rid)) if flag_fn is not None else True
        retain_fn = getattr(self.page_table, "retain_enabled_for", None)
        snap = self._savepoint_snapshotter
        try:
            resume_key, entry = snap.resolve_resume(req, tenant_id, cache_enabled)
        except RuntimeError:
            # ``resolve_resume`` hard-fails when the savepoint store evicted
            # the entry between ``best_match`` and ``get``. On the admission
            # path that is a 5xx because the caller was promised a resume.
            # Here there is no promise to break and no caller to surface it
            # to — we are inside ``schedule()``, where a raise takes the
            # engine loop down — and declining the resume lands the request
            # on the full re-prefill it would have taken anyway. Counted,
            # not swallowed.
            cache_metrics.counter_inc(
                "arbi_serve.savepoint.preempt_resume_race_total",
                labels={"tenant": tenant_id or "_global"},
            )
            resume_key, entry = None, None
        match_len, entry, resume_key = snap.resolve_match(
            req,
            tenant_id,
            cache_enabled,
            resume_key,
            entry,
            readmit=True,
            page_budget_cap=cap,
        )
        try:
            req.state_handles[self.primary_paged_kind] = self.page_table.page_ids(rid)
        except KeyError:
            # Defensive. The seam LEAVES an id the table never registered
            # alone rather than resurrecting it, so a request in that state
            # comes back with no entry and nothing to credit. Returning
            # here keeps a KeyError out of ``schedule()``, where it would
            # take the engine loop down for a request that is simply going
            # to re-prefill.
            return 0
        if match_len:
            if self._has_recurrent_state() and entry is None:
                # The same invariant ``_add_inner`` asserts: on a hybrid
                # model a credited match with no savepoint decodes against
                # zero GDN state (#129). ``resolve_match``'s force-disable
                # makes this unreachable; the raise surfaces a future break
                # instead of corrupting the request's output.
                raise RuntimeError(
                    f"Scheduler: hybrid-model invariant violated — radix "
                    f"re-match match_len={match_len} on preempted request "
                    f"{rid}, whose model carries recurrent state, but no "
                    f"savepoint resume was scheduled; the prompt_consumed "
                    f"credit would skip prefill and decode against zero GDN "
                    f"state (#129)."
                )
            req.prompt_consumed = int(match_len)
            req.cached_prefix_tokens = int(match_len)
            cache_metrics.counter_inc(
                "arbi_serve.scheduler.preempt_prefix_tokens_saved",
                value=int(match_len),
                labels={"service_tier": "flex" if req.is_flex else "default"},
            )
        if entry is not None:
            snap.queue_resume(req, tenant_id, entry, match_len)
        # SPMD: amend the PreemptRow this tick's preempt already logged.
        # The match is rank 0's decision (its cap and its savepoint store
        # are rank-0 state), so it rides the wire exactly like
        # ``AdmitRow.prefix_match_len`` — and it can only be amended in the
        # same ``schedule()`` call, which is what ``_preempt_rebind_ids``
        # being cleared per call guarantees. ``cache_enabled`` is re-read
        # off the table AFTER ``resolve_match``, not reused from above:
        # the hybrid force-disable re-registers the request with the cache
        # OFF, and that resolution is invisible to the flag the worker's
        # re-admit seam would otherwise carry off its own entry.
        shared_fn = getattr(self.page_table, "shared_page_ids", None)
        self.amend_spmd_preempt(
            rid,
            prefix_match_len=int(match_len),
            prefix_page_ids=list(shared_fn(rid)) if shared_fn is not None else [],
            cache_enabled=bool(flag_fn(rid)) if flag_fn is not None else None,
            retain_enabled=bool(retain_fn(rid)) if retain_fn is not None else None,
        )
        return int(match_len)

    def _drain_deferred_admits(self) -> None:
        """Re-admit requests deferred by the offload self-heal.

        Called at the top of :meth:`schedule` (loop thread, strictly
        between forwards) so the recurrent-row self-heal's suspend (CUDA
        D2H + page free) runs with NO forward in flight. A request that
        STILL can't get a row is re-deferred; bounded by the queue snapshot
        so a request deferred this tick isn't retried in the same drain.
        """
        if not self._deferred_admits:
            return
        pending = list(self._deferred_admits)
        # Interactive first (stable, so FCFS holds within each class). The
        # drain clears the deferred counters up front, so a batch re-admit
        # earlier in the snapshot would otherwise see no interactive demand
        # and take the row an interactive request later in the SAME snapshot
        # deferred for.
        pending.sort(key=lambda r: r.is_flex)
        self._deferred_admits.clear()
        # ``add`` re-increments this for any request that defers AGAIN this
        # tick; reset to 0 here so the counter reflects only the requests
        # still deferred AFTER the drain (the ones a row didn't free for).
        self._n_deferred_interactive = 0
        for req in pending:
            # The request may have been cancelled while deferred.
            if req.state == RequestState.FINISHED:
                continue
            # ``add`` is total: a request that still can't get a row
            # re-defers (re-queued + re-counted, retried next drain); an
            # unexpected failure is dropped cleanly to the terminal path.
            # It never raises, so one bad re-admit can't strand the rest of
            # the snapshot or kill the loop. The cleared deque means a
            # re-deferred request lands in a FRESH deque and is retried by
            # the NEXT drain, not this one (bounded progress).
            self.add(req)

    def _add_inner(self, req: Request) -> None:
        """Enqueue a freshly-arrived request.

        With :class:`RadixPageTable`, ``add_request`` returns the
        cached-prefix length matched at admission; we credit those tokens
        by advancing ``prompt_consumed`` so prefill skips them
        (:class:`FlatPageTable` always returns 0 — the credit is a no-op).

        Hybrid models (GDN, Mamba, LFM2 ShortConv) also get a per-request
        recurrent slab row reserved here via
        :meth:`MultiStatePool.alloc_recurrent_state`; without it the
        metadata builder would alias request N's row to request N+1 and a
        radix-cache hit would decode against stale recurrent state.
        Pure-attention models see a no-op.
        """
        if req.state != RequestState.WAITING:
            raise ValueError(f"Scheduler.add: req {req.request_id} not WAITING (got {req.state})")
        # This admission is about to (re-)register the request's page-table
        # entry (``resolve_match`` below, via ``add_request`` or
        # ``readmit_preempted``), which replaces whatever pages it held. Any
        # optimistic advance still parked from an earlier residency was built
        # against those pages: its KV slots stop existing here. Dropping it at
        # the admission seam — rather than at each caller that can route a
        # request back to WAITING — is what keeps the invariant true for
        # re-admission paths that don't go through the preempt site (a
        # deferred admit re-attempt, a savepoint-resume re-registration). A
        # first admission has nothing parked and this is a no-op.
        req.drop_parked_advances()
        if req.is_duplex_frame:
            # Monotone latch: admission is the ONLY way a duplex-lane
            # request can enter this scheduler, so a still-``False`` latch
            # proves no duplex request has ever existed here and lets
            # :meth:`duplex_tick_due` skip its two ``running``/``waiting``
            # scans entirely on every step of every ordinary deployment.
            # Never cleared — a stale ``True`` only costs the scans this
            # gate used to run unconditionally, so it can never be wrong,
            # only conservative.
            self._duplex_ever_admitted = True
        # tenant_id derives from ``req.tenant.tenant_id``, then
        # ``req.tenant_id``, then ``""`` (the global / single-tenant
        # namespace, preserving cross-request sharing). Cache kwargs are
        # no-ops on :class:`FlatPageTable`.
        tenant_id = self._tenant_id_for(req)
        # ``_prefix_cache_serves`` is the boot answer to "can a cached prefix
        # be served here at all" (see
        # :func:`~arbi_serve.cache._state_pool_common.prefix_cache_can_serve`).
        # When it is False every match resolves to a discard below, so the
        # request registers cache-OFF instead: no radix walk, no chain-digest
        # commit, no retained nodes and nothing for the tier to demote. The
        # table carries the resolved flag, so the re-admit seams
        # (:meth:`release_prefix_hold`, the preempt re-bind) read it back and
        # stay consistent without asking again.
        opted_in = bool(getattr(req.sampling, "cache_enabled", True))
        cache_enabled = opted_in and self._prefix_cache_serves
        # The retain half is asked separately and can answer differently: a hybrid
        # without savepoints must not MATCH (the recurrent half of a hit is
        # missing) while its own pages are correct, wanted by its own park and
        # by the next request. The privacy opt-out is the one input that turns
        # both off, because it declined the shared cache in both directions.
        retain_enabled = opted_in and self._prefix_retention_serves

        # Resolve an admission-time savepoint resume (host-RAM checkpoint
        # of the recurrent state for a page-aligned prefix of the request's prompt
        # prefix) and reconcile it with the radix ``add_request``
        # (KV-coverage cross-check + hybrid-model force-disable fallback).
        # On hybrid models a radix cache hit is ONLY safe with a matching
        # savepoint resume — otherwise decode reads zero GDN/Mamba state
        # past the cached pages (the P0 #129 trap). The savepoint admission
        # logic lives in :mod:`arbi_serve.scheduler.savepoint_admission`;
        # only the ``prompt_consumed`` credit below (the documented
        # off-by-one site) stays inline.
        # Bracketed: this is the prefix-cache hit's admission-side cost (radix
        # walk + savepoint match), and it is genuinely host-bound, so a
        # perf_counter measures it honestly. Recorded on the request so the
        # timeline can report a measured number instead of inferring one from
        # the cached-token ratio.
        gate = self._remote_gate
        if gate is not None and cache_enabled and gate.hold(req, tenant_id):
            raise _DeferAdmission(req)  # holds no GPU state yet; retried at the next schedule()
        _lookup_t0 = time.perf_counter()
        savepoint_resume_key, savepoint_entry = self._savepoint_snapshotter.resolve_resume(
            req, tenant_id, cache_enabled
        )
        match_len, savepoint_entry, savepoint_resume_key = (
            self._savepoint_snapshotter.resolve_match(
                req,
                tenant_id,
                cache_enabled,
                savepoint_resume_key,
                savepoint_entry,
                retain_enabled=retain_enabled,
            )
        )
        req.prefix_lookup_s = time.perf_counter() - _lookup_t0
        if match_len:
            # Cached prefix hit — skip prefill on the matched tokens
            # (radix add_request already aliased the pages + bumped the
            # hit metrics). Hybrid-model invariant: match_len > 0 REQUIRES
            # a savepoint resume; the fallback above makes this impossible,
            # so the raise is a defensive guard surfacing any future break.
            if self._has_recurrent_state() and savepoint_entry is None:
                raise RuntimeError(
                    f"Scheduler.add: hybrid-model invariant violated — "
                    f"radix-cache match_len={match_len} on a request "
                    f"whose model carries recurrent state, but no "
                    f"savepoint resume was scheduled; prompt_consumed "
                    f"credit would skip prefill and decode against zero "
                    f"GDN state (#129)."
                )
            req.prompt_consumed = match_len
            # Pin the prefix-cache hit length for finish-time tracing
            # (done-line ``cached=`` / SPMD ``AdmitRow.prefix_match_len``).
            # ``match_len`` is the RADIX ``add_request`` return — the real
            # count of tokens whose pages were reused — so this reflects a
            # plain pure-attention prefix hit (no savepoint), not only a
            # hybrid savepoint match. Must NOT be re-gated behind
            # ``savepoint_entry``: that reports cached=0 on genuine reuse.
            req.cached_prefix_tokens = match_len
        # State-handles: typed pointer to the page-id list.
        req.state_handles[self.primary_paged_kind] = self.page_table.page_ids(req.request_id)
        # Recurrent / short-conv slab-row reservation. No-op on pure-
        # attention models; see :meth:`MultiStatePool.alloc_recurrent_state`
        # for the state-leak (#129) rationale.
        alloc_recurrent = getattr(self.pool, "alloc_recurrent_state", None)
        if alloc_recurrent is not None:
            # Interactive-always-priority, enforced at the ROW as well as at
            # the slate. The slate gate refuses to schedule a batch request
            # while ANY interactive request is present, so a recurrent row
            # handed to batch under those conditions can never be used by
            # its holder — and on a hybrid model the rows are the
            # concurrency bound, so it is exactly the row an interactive
            # request needs. Without this the batch admit parks a row in
            # ``waiting`` that nothing can schedule while the interactive
            # request that wants it sits in ``_deferred_admits``: a priority
            # inversion that serves interactive traffic AFTER the batch
            # backlog it outranks. Defer instead — the request holds no GPU
            # state and ``_drain_deferred_admits`` re-attempts it once the
            # interactive backlog clears.
            if req.is_flex and self._interactive_present():
                self._rollback_partial_admit(req)
                raise _DeferAdmission(req)
            # ``add`` runs on the engine loop and can land WHILE a forward
            # is in flight on the executor thread — that step already ran
            # its start-of-step zero-clear drain, so a clear queued now
            # must go to the pool's DEFERRED bucket (invisible to the
            # in-flight step's GDN metadata-build guard; drained by the
            # next step's flush, before this request can enter a slate).
            # The flag transitions only on this thread, so the read is
            # race-free for the whole admission.
            forward_in_flight = self._forward_in_flight_fn()
            try:
                alloc_recurrent(req.request_id, forward_in_flight=forward_in_flight)
            except RuntimeError:
                # Recurrent slab-row pool exhausted (hybrid GDN / Mamba).
                # Self-heal: park a resident batch decode job to free a row
                # (graceful parking instead of 500-ing), then retry.
                #
                # CRITICAL concurrency guard: the suspend does CUDA work
                # (D2H snapshot + page free). ``add`` runs on the event loop
                # and can land WHILE a model forward is in flight on the
                # executor thread — freeing + reusing the live forward's
                # pages trips a device-side index assert. When a forward is
                # in flight, DEFER: roll back and re-run at the top of the
                # next ``schedule`` (between forwards), where suspend is safe.
                if self._forward_in_flight_fn():
                    self._rollback_partial_admit(req)
                    req._deferred_for_row = True  # the recurrent-row pool is what it waits for
                    raise _DeferAdmission(req) from None
                # An interactive arrival takes a flex row's slot by freezing it, parking or not.
                freed = not req.is_flex and self._yield_row_to_interactive()
                if not freed and self.parking_enabled:
                    for victim in list(self.running):
                        if (
                            victim.is_flex
                            and victim.state == RequestState.DECODING
                            and self._suspend_to_offload(victim)
                        ):
                            freed = True
                            break
                if not freed:
                    # Recurrent-row pool full and no resident batch decode
                    # job to park: this is an over-capacity admission
                    # (concurrency > ``max_num_seqs``). DEFER rather than
                    # raise — a raise here escapes into the cross-loop
                    # intake trampoline, which swallows it and hangs the
                    # request for ~300 s; a drop would 429 a perfectly
                    # serviceable request. Roll back so it holds no GPU
                    # state and re-attempt between forwards once a running
                    # request frees a row (queue-fairly-and-resume). The
                    # admission depth gate counts the deferred admit, so a
                    # SUSTAINED overload still backs off at queue_depth_max.
                    self._rollback_partial_admit(req)
                    req._deferred_for_row = True  # the recurrent-row pool is what it waits for
                    raise _DeferAdmission(req) from None
                alloc_recurrent(req.request_id, forward_in_flight=forward_in_flight)
        # State pools that back their stores on demand (DeepSeek-V4's
        # VA-reserved streams) need the request's REACH — prompt + output
        # budget — before its first forward addresses that far. Declared
        # here, at admission, where the number is known and where the pool
        # can still refuse a request that would run past its reservation;
        # the physical mapping is applied by the start-of-step flush, which
        # is the only point that is both off the engine loop and outside
        # every captured region.
        request_context = getattr(self.pool, "request_state_context", None)
        if request_context is not None:
            request_context(req.request_id, _max_reachable_context(req))
        # Task #143 — queue the savepoint restore IF we resolved a hit.
        # Order-critical: MUST follow ``alloc_recurrent_state`` (the slab
        # row must exist) and MUST precede entering ``self.waiting`` (so
        # the next start-of-step flush sees the queue entry and overlays
        # the restore on the freshly-zeroed row).
        if savepoint_entry is not None:
            self._savepoint_snapshotter.queue_resume(req, tenant_id, savepoint_entry, match_len)
            savepoint_resume_hash.at_queue(self, req, savepoint_entry)
        # ARBI_PP_KV_REPLICATE_DECODE_HANDOFF: pin this request's eventual
        # decode host NOW, not at its last prefill chunk — see
        # PpKvHandoff.pin_decode_host_at_admission for why this is safe
        # (choose_decode_host depends on nothing about prefill progress)
        # and what it unlocks (maybe_ship_chunk's incremental streaming).
        pp_kv_handoff = getattr(self, "_pp_kv_handoff", None)
        if pp_kv_handoff is not None:
            pp_kv_handoff.pin_decode_host_at_admission(req)
        self._waiting_add(req)
        if self._metrics is not None:
            self._metrics.queue_inc()
        if pp_kv_handoff is not None:
            from arbi_serve.distributed.kv_prefix_resume import finish_empty_prefix

            finish_empty_prefix(pp_kv_handoff, req)

    def remove(self, req: Request) -> None:
        """Free pages and drop the request from any queue."""
        # The released-hold arming outlives a ``schedule()`` call, so it is
        # this seam that keeps the set bounded by the live request space.
        self._released_hold_ids.discard(req.request_id)
        was_waiting = was_prefilling = was_decoding = was_suspended = False
        if self._waiting_remove(req):
            was_waiting = True
        if not was_waiting:
            # Snapshot the phase BEFORE the remove (the helper does the
            # deque op + counter delta); ``_running_remove`` keys the
            # counter off ``is_flex`` (immutable), independent
            # of this prefill/decode phase read.
            was_prefilling = req.state == RequestState.PREFILLING
            was_decoding = req.state == RequestState.DECODING
            if not self._running_remove(req):
                was_prefilling = was_decoding = False
        if not was_waiting and not was_prefilling and not was_decoding:
            # May be a parked (offloaded) batch job — give back the retention
            # it claimed. Unconditional and idempotent (the entries stay in the
            # tier as ordinary cache); the terminal path runs it again, which
            # is exactly the property a release of this kind needs.
            # By identity: ``deque.remove`` formats ``repr(req)`` into the ValueError it
            # raises on a miss, and a request's repr walks every field.
            was_suspended = _discard_by_identity(self.suspended, req)
            if was_suspended:
                release_park_pins(self.page_table, getattr(req, "parked_chain", None))
                req.parked_chain = None
            if (
                not was_suspended
                and _discard_by_identity(self._deferred_admits, req)
                and not req.is_flex
            ):
                # Or a request parked in the deferred-admission holding pen
                # (over-capacity admit awaiting a recurrent row). Evict it
                # so a cancel / timeout while deferred cannot be re-admitted
                # by a later :meth:`_drain_deferred_admits`. The holding-pen
                # request holds no GPU state (rolled back at defer time), so
                # only the deque membership + the O(1) tally need clearing.
                self._n_deferred_interactive -= 1
        # A cancel or timeout terminates through here, never ``finished``: the
        # handoff must hear of it too, or an open decode-box session keeps its
        # reservation and a committed request keeps decoding there for nobody.
        pp_kv_handoff = getattr(self, "_pp_kv_handoff", None)
        if pp_kv_handoff is not None:
            pp_kv_handoff.discard_request(req.request_id)
        self.release_device_state(req)
        req.state_handles.pop(self.primary_paged_kind, None)
        if self._metrics is not None:
            if was_waiting:
                self._metrics.queue_dec()
            elif was_prefilling:
                self._metrics.prefill_dec()
            elif was_decoding:
                self._metrics.decode_dec()
# ---- scheduler_allocation.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Page-allocation / preemption reservation-accounting mixin.

Owns the per-step page-commit accounting helpers
(``_decode_page_commit`` / ``_can_allocate_reserved`` /
``_preempt_until_allocatable``) plus the thin ``_preempt_for_space``
delegator to the :class:`~arbi_serve.scheduler.preemption.Preemptor`.

Shared attributes are declared as class-level annotations (mirrors
:mod:`arbi_serve.cache._pool_base`).
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from collections import deque

    from arbi_serve.cache.pagetable import FlatPageTable
    from arbi_serve.cache.radix_pagetable import RadixPageTable
    from arbi_serve.config import CacheConfig
    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.preemption import Preemptor

_LOG = logging.getLogger("arbi_serve.scheduler")


def _pages_spanned(length: int, n_tokens: int, block_size: int) -> int:
    """New pages that extending ``length`` by ``n_tokens`` crosses into.

    The page-table-free fallback for :meth:`_decode_page_commit`. Reduces
    to the ``length % block_size == 0`` predicate at ``n_tokens == 1``.
    """
    if n_tokens <= 0:
        return 0
    return -(-(length + n_tokens) // block_size) - -(-length // block_size)


class _AllocationMixin:
    """Per-step page-commit reservation accounting + preemption gate."""

    # ── Shared scheduler state (set in ``Scheduler.__init__``) ────────
    page_table: FlatPageTable | RadixPageTable
    cache_cfg: CacheConfig
    _preemptor: Preemptor
    waiting: deque[Request]
    running: deque[Request]
    _dropped_suspended: list[Request]

    def _preempt_for_space(
        self,
        slate_req_ids: set[int] | None = None,
        *,
        admitting_is_batch: bool = False,
        spare_running_peers: bool = False,
        ordering: list[Request] | None = None,
    ) -> bool:
        """Bump a running request back to WAITING to free KV pages.

        Thin delegator to :meth:`Preemptor.preempt_for_space` (priority- /
        fairness-aware victim picker in ``scheduler.preemption``).
        """
        return self._preemptor.preempt_for_space(
            slate_req_ids,
            admitting_is_batch=admitting_is_batch,
            spare_running_peers=spare_running_peers,
            ordering=ordering,
        )

    def _preempt_to_admit(self, slate_req_ids: set[int] | None, admitting: Request) -> bool:
        """One preemption for a WAITING request: never a running peer of its class.

        Only while some row is already on this step's slate. With an empty slate
        nothing would run, and a sole row that filled the pool and cannot grow
        would hold it forever against the waiting request, so the preemption is
        what lets the step produce a row at all.
        """
        return self._preempt_for_space(
            slate_req_ids,
            admitting_is_batch=admitting.is_flex,
            spare_running_peers=bool(slate_req_ids),
        )

    def row_draft_depth(self, req: Request) -> int:
        """This row's resolved MTP draft depth ``K``. THE read of it.

        One step's reservation for a speculating row has two halves — the PAGES
        its ``1 + K`` extension will take (:meth:`_decode_page_commit`) and the
        activation BYTES its ``K`` extra query tokens will cost
        (:meth:`~arbi_serve.scheduler.scheduler.Scheduler._query_charge`) — and
        they are reservations for the same tokens in the same forward. Two
        spellings of the same read is how the halves come to disagree about
        which rows speculate, and a slate whose pages are reserved for a verify
        step and whose bytes are not is exactly the over-admission each half
        exists to prevent.

        An UPPER bound by construction: ``_bucket_mtp_k_uniform`` runs after the
        slate is built and can only lower a row's ``K`` (it buckets the step to
        one uniform depth, and the spec valve can zero it outright), so a row
        reserved here at its own ``K`` never runs deeper than it was reserved
        for.
        """
        return max(0, int(getattr(req.sampling, "mtp_k", 0) or 0))

    def _decode_page_commit(self, req: Request, n_tokens: int = 1) -> int:
        """New pages appending this row's ``n_tokens`` will grab.

        ``n_tokens`` defaults to ``1`` — the ordinary decode row, which
        grabs 0 or 1 page. A duplex context-injection row passes its full
        ``injection_row_width`` so the reservation covers every token the
        row's ``allocate_slots`` will take; reserving only the first would
        under-reserve and let the pool hit true exhaustion mid-step.

        A decode row grabs a fresh page iff its incoming token starts a new
        page. ``req.total_length % block_size == 0`` sits ONE tick AHEAD of
        the page-table length: the just-sampled token is appended to
        ``output_token_ids`` at sample time, while its page is not allocated
        until the NEXT step's ``allocate_slots`` in ``_gather_slate``. So
        ``schedule()`` sees ``total_length = page_table.length + 1`` for
        every decode row, one step ahead of the true page-table crossing (at
        ``page_table.length % bs == 0``).

        Ask the page table directly instead: ``pages_needed`` mirrors
        ``allocate_slots``'s arithmetic EXACTLY off the page-table length
        (and correctly credits any radix-shared prefix). Falls back to the
        page-table ``length`` (flat impl / stubs — no radix sharing there,
        so ``length % bs`` is the exact predicate) and finally to the
        ``total_length`` predicate for minimal stubs that expose neither.
        KeyError-safe: a not-yet-registered row estimates 1 page.

        MTP rows reserve the VERIFY-step peak. An MTP-opted decode row's
        step allocates a tail slot PLUS ``mtp_k`` draft slots (``1 + K``
        tokens — ``derive_verify`` / ``build_verify_plan``), not the single
        decode token; committing only the tail's 0-or-1 page UNDER-reserves
        by up to the drafts' page demand per MTP row, so a saturated c8
        slate over-admits and the pool hits TRUE exhaustion mid-step.
        ``draft_pages_needed`` models the ``1 + K``
        extension exactly, on the flat page table and the radix one alike.
        Rejected drafts are trimmed back at ``finalize_draft_slots``, so
        this is a transient peak — reserving it costs at most admission
        backpressure, never a crash.
        """
        bs = self.cache_cfg.block_size
        pt = self.page_table
        mtp_k = self.row_draft_depth(req)
        # Async verify keeps current optimistic draft slots while seeding
        # the next chain. Its measured allocation shape is tail + K + K;
        # reserve those exact tokens, rather than a fixed page/byte buffer.
        overlap = getattr(self, "_draft_seed_overlap", None)
        if mtp_k > 0 and overlap is not None and overlap(req):
            try:
                return pt.pages_needed(
                    req.request_id, self._span_within_context(req, 1 + 2 * mtp_k)
                )
            except KeyError:
                return 1
        pages_needed = getattr(pt, "pages_needed", None)
        if pages_needed is not None:
            # A page table that models page demand models DRAFT page demand
            # too — both implementations define it, off the same tail
            # arithmetic — so the reservation is read directly rather than
            # probed. A probe cannot tell a table that has no answer from one
            # whose answer is the decode tail, and reserving the tail for a
            # row that will take 1 + K tokens over-admits the slate.
            try:
                if mtp_k > 0:
                    return pt.draft_pages_needed(
                        req.request_id, self._span_within_context(req, 1 + mtp_k) - 1
                    )
                return pages_needed(req.request_id, n_tokens)
            except KeyError:
                return 1
        length_fn = getattr(pt, "length", None)
        if length_fn is not None:
            try:
                return _pages_spanned(length_fn(req.request_id), n_tokens, bs)
            except KeyError:
                return 1
        return _pages_spanned(req.total_length, n_tokens, bs)

    def _span_within_context(self, req: Request, span: int) -> int:
        """``span`` capped at the slots ``req`` can still fill under ``max_context`` (at least 1)."""
        try:
            max_context = int(self.cache_cfg.max_context)
            length = int(self.page_table.length(req.request_id))
        except (AttributeError, KeyError, TypeError, ValueError):
            return span
        if max_context <= 0:
            return span
        return max(1, min(span, max_context - length))

    def _end_sole_row_at_ceiling(self, req: Request, pages: int, slate_req_ids: set[int]) -> bool:
        """End ``req`` with ``context`` when nothing else is queued or running and ``pages`` more exceed the KV pool."""
        if self.waiting or any(r is not req for r in self.running):
            return False
        pool = getattr(self.page_table, "pool", None)
        try:
            capacity = int(getattr(pool, "kv_mapped_pages", None) or pool.num_pages) - 1
            held = int(self.page_table.num_pages(req.request_id))
        except (AttributeError, KeyError, TypeError, ValueError):
            return False
        if held + pages <= capacity:
            return False
        slate_req_ids.add(req.request_id)
        if not any(r is req for r in self._dropped_suspended):
            req.finish_reason = req.finish_reason or "context"
            self._dropped_suspended.append(req)
            _LOG.warning(
                "req %s runs alone and its next step needs %d KV pages beyond the %d it holds "
                "in a %d-page pool; finishing it with finish_reason=%s.",
                req.request_id,
                pages,
                held,
                capacity,
                req.finish_reason,
            )
        return True

    def _publish_step_page_hold(self, pages_committed: int) -> None:
        """Hold the pages the slate being returned was admitted against.

        They are allocated later, in the forward; until then a taker outside
        the scheduler (a KV hand-off's landing) must not take them
        (:mod:`arbi_serve.cache.step_page_hold`). The hold is on the pool the
        page table allocates from, which is the one those takers share.
        """
        hold = getattr(getattr(self.page_table, "pool", None), "step_page_hold", None)
        if hold is not None:
            hold.set(pages_committed)

    def _can_allocate_reserved(self, k: int, reserved_pages: int) -> bool:
        """``can_allocate(k)`` minus this step's already-committed pages.

        ``schedule()`` appends N rows per step but ``allocate_slots`` only
        runs later in the forward — so the page table's free count is NOT
        decremented as rows are appended. This helper subtracts
        ``reserved_pages`` (the pages the rows already ON the in-progress
        slate will consume) from the availability check, the same
        running-tally pattern ``token_budget`` / ``batch_left`` use, so a
        row is never admitted against pages a slate-mate already reserved.

        ``reserved_pages <= 0`` delegates to the page table's own
        ``can_allocate`` byte-identically (also keeps minimal test stubs
        without ``available_pages`` working).
        """
        bs = self.cache_cfg.block_size
        if reserved_pages <= 0:
            fits = self.page_table.can_allocate(k)
        else:
            fits = self.page_table.available_pages() - reserved_pages >= -(-k // bs)
        reclaim = getattr(self.page_table, "reclaim_free_pages", None)
        if not fits or reclaim is None or getattr(self, "_spmd_deferred_release", None):
            return fits
        return reclaim(-(-k // bs) + max(0, reserved_pages))

    def _reclaim_idle_prefix_holds(
        self,
        want: int,
        reserved_pages: int,
        exclude_ids: set[int] | None = None,
    ) -> bool:
        """Free pages held by QUEUED rows' prefix matches, until ``want`` fits.

        The cheaper half of the two levers admission has for a full pool.
        Preemption takes pages away from a row that is making progress;
        this takes them from a row that is not running at all — a queued
        request whose admission-time prefix match ref-ed pages it cannot
        use yet (see
        :meth:`~arbi_serve.scheduler.scheduler_admission._AdmissionMixin._release_waiting_prefix_hold`).
        Reclaiming those first is what keeps a long queued prefix from
        starving the row that could actually finish and free the pool.

        Released from the BACK of the queue: the request furthest from its
        own admission gives its hold up first. Returns whether ``want``
        fits after the reclaim — including the no-op case where it already
        did, so a caller can gate on this before reaching for a victim.
        """
        if self._can_allocate_reserved(want, reserved_pages):
            return True
        for req in reversed(list(self.waiting)):
            if exclude_ids is not None and req.request_id in exclude_ids:
                continue
            if not self._release_waiting_prefix_hold(req):
                continue
            if self._can_allocate_reserved(want, reserved_pages):
                return True
        reclaim_loan = getattr(self, "_media_loan_reclaim", None)
        if reclaim_loan is not None and reclaim_loan(exclude_ids or frozenset()):
            return self._can_allocate_reserved(want, reserved_pages)
        return self._can_allocate_reserved(want, reserved_pages)

    def _preempt_until_allocatable(
        self,
        want: int,
        exclude_ids: set[int],
        *,
        admitting_is_batch: bool = False,
        spare_running_peers: bool = False,
        reserved_pages: int = 0,
        admitting: Request | None = None,
    ) -> bool:
        """Preempt victims until ``can_allocate(want)`` holds (or no victim).

        ``admitting`` is the WAITING request this pass is making room for: it
        sets the batch flag from the request and, while ``exclude_ids`` (the
        slate) is non-empty, bars running peers as victims
        (:meth:`_preempt_to_admit`). Left ``None`` the caller is growing a
        running row, which may preempt its newest peer.

        A single ``_preempt_for_space`` attempt is not enough here: one
        victim's freed pages can be far short of ``want`` (a 2047-token
        prefill continuation needs ~8 pages; a radix victim whose pages are
        shared may free none). Loop-and-recheck gives the same guarantee
        the waiting branch gets from its ``continue`` retry: either the
        demand is genuinely allocatable when the row is appended, or the
        caller breaks/defers cleanly. Terminates: every successful preempt
        removes one victim from ``running``.

        ``reserved_pages`` threads the caller's per-step page-commit tally
        (see :meth:`_can_allocate_reserved`) so the loop targets enough
        free pages for BOTH the already-appended slate rows and this one.

        The victim order is built ONCE and consumed across the loop: it is
        stable under the removals the loop itself makes, so rebuilding it
        per victim re-derives the same sequence at a cost quadratic in the
        running set (see :meth:`Preemptor.victim_ordering`).

        :meth:`_reclaim_idle_prefix_holds` runs FIRST: pages held by a row
        that is not running are cheaper to take back than pages held by a
        row that is making progress, and a queued prefix hold large enough
        to starve the running row is the case where preemption has no
        victim to offer at all.
        """
        if self._reclaim_idle_prefix_holds(want, reserved_pages, exclude_ids):
            # A queued row's idle prefix hold covered the demand — no
            # running row loses its KV for it.
            return True
        if admitting is not None:
            admitting_is_batch, spare_running_peers = admitting.is_flex, bool(exclude_ids)
        ordering: list[Request] | None = None
        while not self._can_allocate_reserved(want, reserved_pages):
            if ordering is None:
                ordering = self._preemptor.victim_ordering()
            if not self._preempt_for_space(
                exclude_ids,
                admitting_is_batch=admitting_is_batch,
                spare_running_peers=spare_running_peers,
                ordering=ordering,
            ):
                return False
        return True
# ---- scheduler_commit.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Post-step commit + terminal-finish mixin.

Owns the prefill→decode state advance (:meth:`commit_state`), the
deferrable output append (:meth:`commit_output`), the synchronous
:meth:`commit`, and the terminal :meth:`finished` hook.

Shared attributes are declared as class-level annotations (mirrors
:mod:`arbi_serve.cache._pool_base`).
"""

from __future__ import annotations

from time import perf_counter_ns as _perf_ns
from typing import TYPE_CHECKING

from arbi_serve.cache.radix_pagetable_offload import release_park_pins
from arbi_serve.engine import step_phase_probe as _probe
from arbi_serve.engine.prefill_grouping import note_prefill_step
from arbi_serve.engine.request import Request, RequestState, n_generated, set_state
from arbi_serve.flag_truth import FiringWindow, path_counter
from arbi_serve.runtime_flags import runtime_flags
from arbi_serve.scheduler.scheduler_counters import _discard_by_identity

_PREFIX_INCREMENTAL_PUBLISH = path_counter("prefix_incremental_publish_commit", FiringWindow.SERVE)

#: Fired when :meth:`_CommitMixin.finished` skips the reply-page commit
#: because the served turn is known-unreachable under the template that
#: will render the follow-up (a thinking turn whose think block the
#: template strips and the client does not replay). The tree walk plus
#: insertions it skips are pure overhead there — the pages can never hit.
_FINISHED_COMMIT_SKIPPED_RERENDER = path_counter(
    "finished_commit_skipped_rerender", FiringWindow.SERVE
)


def _served_reply_unreachable_by_rerender(req: Request) -> bool:
    """Whether the reply pages :meth:`finished` would commit can never hit.

    True when THIS turn was served inside a reasoning block
    (``sampling.opens_in_reasoning``, set by the chat route when the
    rendered generation prompt left the model inside an unclosed think
    block) and the client does not replay reasoning traces
    (``sampling.replay_reasoning``): the follow-up turn's template render
    then strips the think block, sends different tokens, and keys
    different pages than the served KV this commit would insert. The
    commit is skipped on that predicate — the single-rank path below.
    (The SPMD deferred-release path keeps committing: its drain runs the
    commit and the page/recurrent frees as one rank-symmetric unit, so a
    skip there is a separate change.)
    """
    sp = req.sampling
    return bool(sp.opens_in_reasoning) and not bool(sp.replay_reasoning)


#: The decode-boundary write's own counter (registered in
#: :mod:`arbi_serve.scheduler.savepoint_admission`); ``path_counter`` is one
#: object per name, so a refusal here reads in the same breakdown as the gates
#: inside ``snapshot_decode_boundary``.
_DECODE_WRITE = path_counter("savepoint_decode_write", FiringWindow.SERVE)


def _decode_row_still_owned(pool: object, req: Request) -> bool:
    """Whether a decode-boundary snapshot of ``req`` may read its slab row now.

    ``commit_state`` runs for a step AFTER that step's forward was launched,
    and under async output only after the PREVIOUS step's deferred commit has
    run — whose ``post_token`` can finish this very request and free its row.
    A disconnect lands in the same window, and a freeze or preemption frees
    a row without finishing the request. The snapshot reads the row by its
    request id after the fact, so it must ask who owns the row at read time:
    a freed row is either gone (the pool raises) or already another
    request's state under this request's key.
    """
    if req.state == RequestState.FINISHED:
        _DECODE_WRITE.refuse("request finished while its step was in flight")
        return False
    holds = getattr(pool, "holds_recurrent_row", None)
    if holds is not None and not holds(req.request_id):
        _DECODE_WRITE.refuse("recurrent row released while its step was in flight")
        return False
    return True


def prefix_publish_grid(sched: object, block_size: int) -> int:
    """The token grid a prefill row's incremental prefix publish lands on.

    The grid every rank of an SPMD group derives alike: the savepoint chunk
    where :meth:`_CommitMixin.commit_state` takes those snapshots (a store and
    recurrent state), and the page everywhere else. A single-rank hybrid's
    tree is PAIRED instead and bounds its own publish at the savepoints the
    store actually admitted (:mod:`arbi_serve.cache.radix_pagetable_savepoints`),
    which no worker rank could know — hence this shared grid for SPMD.

    ONE derivation, because two sides publish and must land the same pages on
    the same step: rank 0's scheduler, and an SPMD rank's replay of it
    (``SpmdRankLoop._commit_prefill_pages``, granularity bound by
    :func:`~arbi_serve.engine.spmd_loop_build.make_rank_loop`). On a coarser
    grid the replaying rank promotes a mid-prefill row's pages later, so it
    keeps the duplicates a dedup onto an existing prefix frees on rank 0 and
    its free list leaves rank 0's. Attention DP is the case that splits them:
    no set keeps a store (TP > 1), yet every set's pool carries row state.
    A plain-TP worker keeps none either, but only because rank 0's store
    ships it the state on admission, so it follows rank 0's grid.
    """
    if not sched._has_recurrent_state():
        return int(block_size)
    if getattr(sched, "_savepoint_store", None) is not None:
        return int(sched._savepoint_chunk_size)
    from arbi_serve.distributed.spmd_state_resume import receives_replicated_resume

    if receives_replicated_resume(getattr(sched, "pool", None)):
        return int(sched._savepoint_chunk_size)
    return int(block_size)


if TYPE_CHECKING:
    from collections import deque
    from collections.abc import Callable

    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.models.layer_spec import StateKind
    from arbi_serve.scheduler.quota_filter import QuotaFilter
    from arbi_serve.scheduler.savepoint_admission import SavepointSnapshotter
    from arbi_serve.server.metrics import Metrics


class _CommitMixin:
    """Prefill→decode commit + output append + terminal finish."""

    # ── Shared scheduler state (set in ``Scheduler.__init__``) ────────
    page_table: FlatPageTable | RadixPageTable
    pool: MultiStatePool
    primary_paged_kind: StateKind
    suspended: deque[Request]
    _commit_full_pages: Callable[[int], None] | None
    _prefix_incremental_publish: bool
    _spmd_deferred_release: Callable[[int], None] | None
    _savepoint_store: object | None
    _savepoint_chunk_size: int
    _savepoint_snapshotter: SavepointSnapshotter
    _quota_filter: QuotaFilter
    _metrics: Metrics | None
    _pp_kv_handoff: object | None

    def commit(
        self,
        slate: list[tuple[Request, int]],
        sampled_tokens: list[int | None],
    ) -> list[Request]:
        """Advance per-request state + append sampled tokens after a step.

        Synchronous (non-async-output) path: the two halves run back to
        back. Under async output the run loop splits them — :meth:`commit_state`
        runs SYNCHRONOUSLY when the deferred step is parked (so the next
        step schedules the request as decode, not a re-prefill), and
        :meth:`commit_output` runs one engine tick later when the deferred
        sample is materialized. See :func:`run_step.drain_pending_output`.

        Returns the requests due for PP consolidation (see
        :meth:`commit_state`) — does NOT run them: this is called from
        ``_commit_now`` BEFORE its own ``post_token`` loop stamps
        ``first_token_time``, so running them here would put the deferred
        transfer right back on TTFT. The caller runs the returned list via
        :meth:`_run_pp_consolidate` after ``post_token``. Callers that
        never arm the PP handoff (SPMD/attn_dp) always get an empty list.
        """
        ship_due, consolidate_due = self.commit_state(slate)
        self.commit_output(slate, sampled_tokens)
        return (ship_due, consolidate_due)

    def _run_pp_consolidate(self, due: tuple[list, list[Request]]) -> None:
        """Run the deferred ``PpKvHandoff.maybe_ship_chunk``/
        ``maybe_consolidate`` calls from :meth:`commit_state`'s returned
        ``(ship_due, consolidate_due)``. No-op if empty or unarmed.
        """
        ship_due, consolidate_due = due
        if not ship_due and not consolidate_due:
            return
        pp_kv_handoff = getattr(self, "_pp_kv_handoff", None)
        if pp_kv_handoff is None:
            return
        for req, page_ids, first_position in ship_due:
            pp_kv_handoff.maybe_ship_chunk(req, page_ids, first_position=first_position)
        for req in consolidate_due:
            pp_kv_handoff.maybe_consolidate(req)

    def commit_state(
        self, slate: list[tuple[Request, int]]
    ) -> tuple[list[tuple[Request, list[int], int]], list[Request]]:
        """Advance the prefill→decode state machine for a step's slate.

        Bumps ``prompt_consumed`` for prefill rows, snapshots crossed
        recurrent-savepoint boundaries, and on the prompt-completing chunk
        promotes the request to ``DECODING`` + promotes its full prompt
        pages into the radix cache. Does NOT append output tokens — that's
        :meth:`commit_output`.

        Also drains ``pending_context_token_ids`` into ``context_consumed``
        for any row the batch builder served as an injection row, so the
        injected context advances ``total_length`` without ever entering
        ``output_token_ids``.

        This MUST stay synchronous even under async output: ``is_prefill``
        keys off ``prompt_consumed`` and the next step's positions key off
        ``total_length``, so deferring either advance would leave the
        request looking mid-prefill (re-processing the prompt, duplicating
        the first decoded token) or re-injecting context onto KV slots it
        already owns. Idempotent per step: only prefill rows advance, a row
        leaves prefill once consumed, and the context buffer is cleared as
        it is counted.

        Returns ``(ship_due, consolidate_due)`` — the deferred
        ``PpKvHandoff.maybe_ship_chunk``/``maybe_consolidate`` calls,
        normally both empty since those fire inline here.
        ``ARBI_PP_KV_HANDOFF_DEFER_CONSOLIDATE`` collects them instead (only
        on the prompt-completing chunk); the caller runs them via
        :meth:`_run_pp_consolidate`, immediately except on the first-token
        TTFT path (``engine/run_step/__init__.py``), which runs them after
        the response is flushed.
        """
        commit_full = self._commit_full_pages
        pp_ship_due: list[tuple[Request, list[int], int]] = []
        pp_consolidate_due: list[Request] = []
        defer_consolidate = bool(runtime_flags().pp_kv_handoff_defer_consolidate)
        chunk_size = self._savepoint_chunk_size
        store = self._savepoint_store
        # Savepoint snapshot side. On a hybrid-model prefill row whose
        # ``prompt_consumed`` crosses a chunk boundary AND whose tenant is
        # ``cache_enabled``, snapshot the post-chunk recurrent state so a
        # later matching prompt can resume without re-prefilling.
        snapshot_eligible = store is not None and self._has_recurrent_state()
        snapshot_fn = (
            getattr(self.pool, "snapshot_recurrent_row", None) if snapshot_eligible else None
        )
        # The whole per-row walk, and inside it the accounting the boundary
        # brief names as its own suspect. Both are read only when the probe
        # is armed; the snapshot and radix-publish children below are timed
        # separately, so the walk's own cost never has to be inferred from a
        # subtraction of the two.
        _tw = _perf_ns() if _probe.enabled() else 0
        # Before the advance below, while ``is_prefill`` still describes the
        # rows this step fed.
        note_prefill_step(slate)
        for req, n_tok in slate:
            # ``getattr``, not a bare read: minimal request stand-ins in CPU
            # tests predate these fields and must stay a no-op here.
            pending_ctx = getattr(req, "pending_context_token_ids", None)
            row_is_prefill = req.is_prefill
            if pending_ctx and not row_is_prefill:
                # The injection row forwarded these; they now hold KV slots and
                # must advance ``total_length`` without entering the output
                # stream. Clearing the buffer makes the advance idempotent and
                # returns the request to ordinary single-token decode.
                #
                # Gated on ``not row_is_prefill`` to match ``_gather_slate``'s
                # OWN derivation exactly (``row_is_inject = pending_ctx and
                # not row_is_prefill``): a request that still has prompt to
                # consume was served a PREFILL row, which fed no context, so
                # counting it consumed here would advance ``total_length``
                # past KV that no forward ever wrote. Reachable since task
                # #60 gave duplex requests a real seed-prefill phase, during
                # which a WS caller can queue context.
                # ``consume_pending_context`` also records WHERE the
                # injection sits in the fed stream — the only way a
                # history-keyed state (Qwen4-Exp PLE) can rebuild the
                # position→token map once the ids leave the buffer.
                req.consume_pending_context()
            if not row_is_prefill:
                # ARBI_PP_KV_REPLICATE_DECODE_HANDOFF: a consolidated
                # request's non-host-rank row is retained (see
                # PpKvHandoff.maybe_consolidate's row/page-parity note) but
                # goes STALE the instant it stops being the decode host --
                # only the chosen host rank's row still reflects real
                # decode writes from that point on. snapshot_fn's mirror
                # call has no way to know which side is stale (it always
                # asks rank 1, and rank 1 is stale whenever the host is
                # rank 0 -- live-verified: this used to surface as a
                # KeyError "no row for request N" back when the row was
                # freed one-sided instead of merely retained-but-stale).
                # This rank already holds the request's FULL state after
                # consolidation (either directly, if it's the host, or
                # nothing useful to snapshot, if it isn't), so there is
                # nothing a cross-rank snapshot could add — but a snapshot
                # resume for a handed-off request isn't wired either, so
                # this is a real v1 scope cut (no prefix-cache resume for a
                # request post-handoff), not just a crash dodge.
                if (
                    snapshot_fn is not None
                    and store is not None
                    and not getattr(req, "_pp_decode_local_host", False)
                    and _decode_row_still_owned(self.pool, req)
                ):
                    self._savepoint_snapshotter.snapshot_decode_boundary(req, snapshot_fn)
                continue
            _tp = _perf_ns() if _tw else 0
            pc_before = req.prompt_consumed
            req.prompt_consumed += n_tok
            pc_after = req.prompt_consumed
            if _tp:
                _probe.note_value("commit_prompt_consumed_us", (_perf_ns() - _tp) / 1000.0)
            if (
                snapshot_fn is not None
                and store is not None
                and bool(getattr(req.sampling, "cache_enabled", True))
            ):
                _t0 = _perf_ns() if _probe.enabled() else 0
                self._savepoint_snapshotter.snapshot_crossed_boundaries(
                    req,
                    pc_before,
                    pc_after,
                    chunk_size,
                    snapshot_fn,
                    completes_prompt=pc_after >= len(req.prompt_token_ids),
                )
                if _t0:
                    _probe.note_value("commit_snapshot_us", (_perf_ns() - _t0) / 1000.0)
            # Publish only KV that this successful forward actually produced.
            # The explicit page-aligned bound is important: the radix
            # table's default token source is the request's complete prompt,
            # which would expose an uncomputed tail during chunked prefill.
            # It is a bound, not a slice: a slice copies the consumed prompt
            # once per prefill step, on the step thread, for pages the
            # commit never reads.
            # Keep this AFTER recurrent snapshots so a hybrid cache hit can
            # never observe KV before its matching savepoint is available.
            if (
                self._prefix_incremental_publish
                and commit_full is not None
                and bool(getattr(req.sampling, "cache_enabled", True))
            ):
                # Hybrid KV is reusable only together with a recurrent
                # savepoint. A PAIRED tree enforces that itself: it publishes
                # only up to the deepest savepoint this request wrote and the
                # store admitted (radix_pagetable_savepoints), so the bound
                # here is just the KV this forward produced. Unpaired (SPMD
                # lockstep), every rank derives the same savepoint grid.
                block_size = self.cache_cfg.block_size
                if getattr(self.page_table, "savepoint_paired", False):
                    grid = block_size
                else:
                    grid = prefix_publish_grid(self, block_size)
                published = ((pc_after // grid) * grid // block_size) * block_size
                if published:
                    # The key admission matched on (media-salted for images),
                    # never the raw ids: two images behind identical
                    # placeholder tokens would otherwise dedupe onto one
                    # node and this request's pages onto another image's KV.
                    commit_full(
                        req.request_id,
                        token_ids=req.cache_token_ids(),
                        num_tokens=published,
                    )
                    _PREFIX_INCREMENTAL_PUBLISH.fired = 1
            # ARBI_PP_KV_REPLICATE_DECODE_HANDOFF: stream this chunk's
            # now-stable PAGED_KV pages to the request's already-pinned
            # decode host (see PpKvHandoff.pin_decode_host_at_admission /
            # .maybe_ship_chunk) AS IT COMMITS, rather than waiting for
            # maybe_consolidate to ship the whole request in one lump at
            # the very end. A page never changes once its chunk is
            # committed, so shipping it now is exactly as valid as
            # shipping it later — it just gets it off the LAST chunk's
            # critical path.
            #
            # Deliberately NOT gated on ``self._prefix_incremental_publish``
            # (a separate, independently-configurable prefix-cache
            # feature) — this floors ``pc_before``/``pc_after`` the same
            # way that flag's own ``published`` bound does, but the two
            # concerns (publishing to the prefix cache vs. shipping bytes
            # to a decode-host rank) are otherwise unrelated, so this
            # runs whenever PP-KV-handoff is armed regardless of that
            # setting. Costs nothing on any non-PP-handoff engine (the
            # overwhelming default): a single ``getattr`` on the guard.
            #
            # And NOT gated on the request's ``cache_enabled`` either, for
            # the same reason: that flag says whether this prompt's KV may
            # be REUSED by a later request, which says nothing about where
            # this request's own decode reads it from. Gating on it is what
            # made a ``"cache": false`` request ship all of its pages in one
            # lump on the last chunk's critical path — reported by
            # ``maybe_consolidate``'s own "N/M pages already streamed
            # incrementally" line as ``0/M`` — including under the admin
            # console's own A/B, which bypasses the cache by default, so the
            # sanctioned way to measure this feature was the one way that
            # measured it with the optimization disabled.
            pp_kv_handoff = getattr(self, "_pp_kv_handoff", None)
            is_last_chunk = pc_after >= len(req.prompt_token_ids)
            if pp_kv_handoff is not None:
                block_size = self.cache_cfg.block_size
                prev_shippable = (pc_before // block_size) * block_size
                new_shippable = (pc_after // block_size) * block_size
                if snapshot_eligible:
                    # Same fold-grid bound the prefix-cache publish above
                    # applies: a page whose KV bytes are stable but whose
                    # matching recurrent savepoint hasn't landed yet is not
                    # this request's real decode-host-bound state yet.
                    snapshotted = (pc_after // chunk_size) * chunk_size
                    new_shippable = min(new_shippable, (snapshotted // block_size) * block_size)
                if new_shippable > prev_shippable:
                    page_ids = list(self.page_table.page_ids(req.request_id))
                    start_idx = prev_shippable // block_size
                    end_idx = new_shippable // block_size
                    # Same TTFT reasoning as maybe_consolidate below: on the
                    # prompt-completing chunk this can be the request's
                    # largest single ship (everything maybe_ship_chunk did
                    # not already stream on an EARLIER chunk), so defer it
                    # too rather than only the final recurrent-state piece.
                    defer_ship = (
                        defer_consolidate
                        and is_last_chunk
                        and getattr(pp_kv_handoff, "_remote", None) is None
                    )
                    if defer_ship:
                        pp_ship_due.append((req, page_ids[start_idx:end_idx], start_idx))
                    else:
                        pp_kv_handoff.maybe_ship_chunk(
                            req, page_ids[start_idx:end_idx], first_position=start_idx
                        )
            if is_last_chunk:
                if getattr(req.sampling, "prefill_score_token_ids", None) is not None:
                    finish_score = getattr(self, "_prefill_score_finish", None)
                    if finish_score is None:
                        raise RuntimeError("prefill scoring has no terminal readout callback")
                    finish_score(req)
                    continue
                # Decode uses only the M-RoPE delta. The image embeddings
                # and full position grid are prefill inputs, not output-
                # lifetime state. Retain CPU features and fingerprints so
                # a preempted request can encode again for re-prefill.
                if getattr(req, "multimodal", None) is not None:
                    req._media_embeds = None
                    req._mrope_full = None
                set_state(req, RequestState.DECODING)
                if self._metrics is not None:
                    self._metrics.prefill_dec()
                    self._metrics.decode_inc()
                if commit_full is not None:
                    commit_full(req.request_id)
                # ARBI_PP_KV_REPLICATE_DECODE_HANDOFF: this IS the
                # prefill->decode transition, exactly once per request, on
                # the PP coordinator rank. See
                # arbi_serve.distributed.pp_kv_handoff.PpKvHandoff.
                # ``getattr``, not a bare read: minimal ``_CommitMixin``
                # stand-ins in CPU tests (e.g. test_spmd_derivation.py's
                # ``_Committer``) predate this field and must stay a no-op
                # here, exactly like the ``pending_context_token_ids``
                # ``getattr`` above.
                pp_kv_handoff = getattr(self, "_pp_kv_handoff", None)
                if pp_kv_handoff is not None:
                    # Cross-box remote decode dispatch (sets
                    # req._pp_decode_remote_box) must stay inline: the
                    # post_token loop in _commit_now checks that flag
                    # BEFORE any deferred consolidate would run.
                    if defer_consolidate and getattr(pp_kv_handoff, "_remote", None) is None:
                        pp_consolidate_due.append(req)
                    else:
                        pp_kv_handoff.maybe_consolidate(req)
            elif (
                getattr(req, "_casper_handoff", False)
                or getattr(req, "_kv_computed_prefix_len", None) is not None
            ) and pc_after + 1 == len(req.prompt_token_ids):
                # The final prompt token belongs to the decode consumer, whether
                # this prefix used dense or sparse MLPs.
                self._prefill_hand_off(req)
                if (
                    pp_kv_handoff is not None
                    and getattr(req, "_kv_computed_prefix_len", None) is not None
                ):
                    pp_kv_handoff.maybe_consolidate(req)

        if _tw:
            _probe.note_value("commit_row_walk_us", (_perf_ns() - _tw) / 1000.0)
        # Close the interval ``schedule`` opened for this slate. A pure-prefill
        # step's wall time over its own token count is the rate the disk tier's
        # break-even races a cold restore against; nothing else in the engine
        # holds both halves.
        #
        # Guarded, because the snapshotter is genuinely optional: it is None
        # until the scheduler finishes constructing, and the row-shape and
        # injection-row suites drive this method against a scheduler that has
        # never had one. Reaching THROUGH the attribute is the same defect
        # this branch already fixed twice.
        snap = self._savepoint_snapshotter
        if snap is not None:
            snap.observe_step_prefill(slate)
        return (pp_ship_due, pp_consolidate_due)

    def commit_output(
        self,
        slate: list[tuple[Request, int]],
        sampled_tokens: list[int | None],
    ) -> None:
        """Append each row's sampled token to ``output_token_ids``.

        The deferrable half of :meth:`commit` — runs at sample-materialize
        time (one tick late under async output). A ``None`` token (mid-
        prefill chunk, or a row dropped because it finished mid-flight) is
        skipped. ``commit_state`` already ran for this slate.
        """
        for (req, _n_tok), token in zip(slate, sampled_tokens, strict=True):
            if token is None:
                continue
            req.output_token_ids.append(int(token))

    def release_device_state(self, req: Request) -> None:
        """Return ``req``'s KV pages and recurrent slab row, once per request.

        Whichever seam reaches it first releases: a finish, a cancel, or a
        hand-off to a remote decode server, which frees the prefill box's row at
        commit while the request object lives on to relay the stream. A row held
        until the remote decode finished would cap prefill concurrency at the
        recurrent pool's row count. Under SPMD the release is the deferred drain
        (commit included), so a cancel or hand-off releases exactly like a
        natural finish: the worker's evict replay cannot tell them apart and
        always mirror-commits and frees at its next tick's start. See
        :meth:`set_spmd_deferred_release`.
        """
        if getattr(req, "_device_state_released", False):
            return
        handoff = getattr(self, "_pp_kv_handoff", None)
        hold = getattr(handoff, "defer_device_release", None)
        if hold is not None and hold(req) is True:
            return
        req._device_state_released = True
        if self._spmd_deferred_release is not None:
            self._spmd_deferred_release(req.request_id)
            return
        self.page_table.remove_request(req.request_id)
        # Mirror the alloc in :meth:`add`: the row is zero-cleared on reuse.
        free_recurrent = getattr(self.pool, "free_recurrent_state", None)
        if free_recurrent is not None:
            free_recurrent(req.request_id)

    def finished(self, req: Request) -> None:
        """Called by the engine when stop / length / context limit hits.

        Commits any decode-completed full pages into the radix cache BEFORE
        releasing the request's page refs (the new shared nodes land at
        ``ref_count==0`` / evictable, so follow-up prompts covering the same
        generated tokens hit them). Cheap: one tree walk +
        ``output_tokens / block_size`` insertions max.
        """
        try:
            if self._spmd_deferred_release is not None:
                # SPMD rank 0: the commit AND the page/recurrent frees are
                # DEFERRED to the driver's next-tick drain — the byte-exact
                # point the worker's evict replay runs them — so both the
                # commit ORDER (vs this tick's other commits) and the free
                # ORDER (vs this tick's later allocations) stay rank-symmetric,
                # and the commit content is mirror-sourced. See
                # :meth:`set_spmd_deferred_release`.
                self.release_device_state(req)
            else:
                commit_full = self._commit_full_pages
                if commit_full is not None and req.sampling.cache_enabled:
                    # Key any decode-completed full pages on the full sequence
                    # (prompt + output) so chat continuations hit them instead of
                    # re-prefilling. Skipped for cache-opt-out (embed/rerank)
                    # requests — pure overhead since they never touched the tree.
                    #
                    # These pages are UNREACHABLE whenever the chat template
                    # re-renders an assistant turn differently from how it was
                    # served — Qwen's drops the think block the generation prompt
                    # opened — because a follow-up then sends different tokens.
                    # They cannot be re-keyed to fix that: the page key must name
                    # the tokens whose KV the page HOLDS, and the served KV is the
                    # served stream's. Different tokens are different KV, so the
                    # reply is genuinely not reusable there (arbicity#2286).
                    if _served_reply_unreachable_by_rerender(req):
                        # Known re-render template (thinking turn, no replay):
                        # the follow-up sends different tokens, so these pages
                        # are permanently unreachable — skip the tree walk and
                        # the insertions, and count the skip.
                        _FINISHED_COMMIT_SKIPPED_RERENDER.fired = 1
                    else:
                        full_seq = req.cache_token_ids() + req.output_token_ids
                        commit_full(req.request_id, token_ids=full_seq)
            # Order matters: the turn is complete HERE, so the entry it resumed
            # from may finally be replaced, and only then is the per-request
            # decode bookkeeping dropped.
            self._savepoint_snapshotter.request_completed(req)
        finally:
            # Publication into the prefix cache / savepoint store is optional
            # work and may raise; the release below is not. Without it a
            # request whose publish failed keeps its pages, recurrent row and
            # queue slot for the life of the process, and stays schedulable.
            self._retire_finished(req)

    def _retire_finished(self, req: Request) -> None:
        """Release everything ``req`` holds and mark it FINISHED.

        The unconditional half of :meth:`finished`, run even when its
        publication raised.
        """
        # Queue-membership parity with :meth:`remove`: a finishing request
        # is not always in ``running``. A step-failure ``_fail_slate`` can
        # finish a request the Preemptor bumped to WAITING mid-schedule
        # (the step then refused and finished the whole slate), and
        # ``finished`` only purged ``running`` — leaving the FINISHED
        # request in the waiting deque. The next ``schedule()`` re-emitted
        # the dead rid whose page-table entry was already removed below,
        # and the SPMD rank-0 delta build (``plan_evictions_spmd →
        # pages_needed``) KeyError'd OUTSIDE the per-step try/except —
        # killing the engine loop (the TP2 ab_main_spmd1 crash). Purge
        # waiting + the deferred-admission holding pen too so a finished
        # request can never be rescheduled. The phase counters below
        # already handle the WAITING state (``queue_dec``);
        # ``_waiting_remove`` keeps the O(1) interactive tally consistent.
        self._savepoint_snapshotter.forget_request(req.request_id)
        pp_kv_handoff = getattr(self, "_pp_kv_handoff", None)
        if pp_kv_handoff is not None:
            # Drop any incremental-shipping bookkeeping for a request that
            # finishes WITHOUT ever reaching maybe_consolidate (cancelled /
            # errored mid-prefill) — otherwise it leaks for the life of the
            # process. A request that DID consolidate already had its entry
            # popped there; this is a no-op for it.
            pp_kv_handoff.discard_request(req.request_id)
        if (
            not self._running_remove(req)
            and not self._waiting_remove(req)
            and _discard_by_identity(self._deferred_admits, req)
            and not req.is_flex
        ):
            self._n_deferred_interactive -= 1
        # A parked (offloaded) batch job that finishes (cancelled /
        # offload_lost) — give back its suspended-deque slot and the retention
        # it claimed. UNCONDITIONAL: a pin nobody unpins is tier capacity lost
        # for the life of the process, so this may not sit behind a flag that
        # says whether the deployment parks. A request that never parked holds
        # no chain and the release is a no-op on it.
        # By identity, and only when present: ``deque.remove`` formats ``repr(req)`` into the
        # ValueError it raises for an absent item, and a request's repr walks every field,
        # media tensors included, on every finish.
        _discard_by_identity(self.suspended, req)
        release_park_pins(self.page_table, getattr(req, "parked_chain", None))
        req.parked_chain = None
        # Release the tenant's in-flight slot + fold completion tokens
        # into the cumulative gauge. No-op for anon / unseen tenants.
        self._quota_filter.tracker.release(
            self._tenant_for(req),
            completion_tokens=n_generated(req),
            request_id=req.request_id,
        )
        # A reused media request must reserve a fresh tenant slot/token charge.
        # Clear at release, avoiding a tracker lookup on every continuation.
        req.__dict__.pop("_media_quota_reserved", None)
        # Immediate release (single-process); under SPMD it was queued above.
        self.release_device_state(req)
        req.state_handles.pop(self.primary_paged_kind, None)
        # Drop the GPU sample reference so the 0-d tensor stops pinning the
        # parent ``samples_gpu`` storage.
        req.last_sampled_gpu = None
        # Clear any parked optimistic advance on finish so a re-used
        # Request object (or a late total_length read) can't inherit a
        # stale parked tick.
        req.drop_parked_advances()
        # Drain phase / queue counters BEFORE flipping FINISHED so the
        # dashboard's batch-shape view stays balanced.
        if self._metrics is not None:
            if req.state == RequestState.PREFILLING:
                self._metrics.prefill_dec()
            elif req.state == RequestState.DECODING:
                self._metrics.decode_dec()
            elif req.state == RequestState.WAITING:
                # Edge case: cancelled while still queued (``remove`` is the
                # canonical path; ``finished`` covers the terminal hook).
                self._metrics.queue_dec()
        set_state(req, RequestState.FINISHED)
# ---- scheduler_counters.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""O(1) admission-counter maintenance + engine-wiring hooks mixin.

Provides the four ``waiting`` / ``running`` deque helpers that keep the
priority-split admission counters exact, the debug-only drift
reconciler, the engine-injected predicate setters, and
:meth:`shutdown`.

The shared attributes they read / write are declared as class-level
annotations (mirrors :mod:`arbi_serve.cache._pool_base`) — the real
values are set in :meth:`Scheduler.__init__`.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, NamedTuple

from arbi_serve.flag_truth import FiringWindow, path_counter
from arbi_serve.scheduler.partial_prefill_first import note_waiting_add, note_waiting_remove

if TYPE_CHECKING:
    from collections import deque
    from collections.abc import Callable

    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.task_queues import TaskQueues


#: A prompt's last token was held out of a CASPER sparse prefill chunk and handed to the
#: decode path as the request's first decode step (a true count).
_CASPER_HANDOFF = path_counter("casper_side_handoff", FiringWindow.SERVE, counted=True)
#: Whole prompts a windowless boot (no KV context window) left waiting because
#: this step could not take them whole. Non-zero only while the card is tighter
#: than the step budget the boot sized for one ``max_context`` prompt.
_WINDOWLESS_DEFERRED = path_counter("windowless_kv_deferred_prompt", FiringWindow.SERVE)


class SpmdPreempt(NamedTuple):
    """One logged preemption, in the shape the SPMD delta broadcasts.

    Field-for-field the payload of
    :class:`arbi_serve.distributed.spmd_delta.PreemptRow`; the driver's
    delta build is a straight copy. It lives here rather than being
    rebuilt at drain time because every field is a rank-0 DECISION, taken
    at a moment a later scan cannot reconstruct: the victim is routinely
    re-admitted onto the same tick's slate, after which nothing
    distinguishes it from an ordinary prefill row.
    """

    request_id: int
    new_prompt_len: int
    prefix_match_len: int = 0
    prefix_page_ids: tuple[int, ...] = ()
    cache_enabled: bool | None = None
    #: The RETAIN half of the same override. Carried because the worker's
    #: commit is gated on it; ``None`` keeps whatever the dropped entry had.
    retain_enabled: bool | None = None


def _discard_by_identity(dq: deque[Request], req: Request) -> bool:
    """Remove ``req`` from ``dq`` by object identity; report whether it was there.

    ``deque.remove`` compares with ``==``, and :class:`Request` is a
    dataclass whose generated ``__eq__`` materializes a tuple of every
    field for BOTH operands per candidate — so a miss costs microseconds,
    not nanoseconds, and one removal from a deep queue costs more than a
    scheduling tick's whole budget. Queue membership is identity (a
    request object is in exactly one queue and no two requests carry the
    same ``request_id``), so scan for it directly and never call
    ``__eq__`` at all.
    """
    for i, candidate in enumerate(dq):
        if candidate is req:
            del dq[i]
            return True
    return False


class _CounterMixin:
    """``waiting`` / ``running`` counter helpers + engine-wiring hooks."""

    # ── Shared scheduler state (set in ``Scheduler.__init__``) ────────
    waiting: deque[Request]
    running: deque[Request]
    suspended: deque[Request]
    _deferred_admits: deque[Request]
    _dropped_suspended: list[Request]
    _n_waiting_interactive: int
    _n_running_interactive: int
    _n_running_batch: int
    _n_deferred_interactive: int
    _forward_in_flight_fn: Callable[[], bool]
    _spmd_deferred_release: Callable[[int], None] | None
    #: :meth:`set_pageless_whole_prompts_fn`; ``None`` (every row paged) until wired.
    _pageless_whole_prompts_fn: Callable[[], bool] | None = None
    #: :meth:`set_kv_windowless`; the pool holds no context, so no prompt is split.
    _kv_windowless: bool = False
    _spmd_preempted: list[SpmdPreempt]
    _spmd_preempt_log: bool
    _pp_kv_handoff: object | None
    #: Per-task queues over ``waiting`` (:mod:`arbi_serve.scheduler.task_queues`); ``None``
    #: unless the served model declares task policies (:meth:`set_task_policies`).
    _task_queues: TaskQueues | None = None

    # ── O(1) admission-counter maintenance ──────────────────────────
    # Every mutation of ``waiting`` / ``running`` routes through one of
    # these four helpers so the priority-split counters stay exact. They
    # do the deque op AND the counter delta together, so no call site can
    # update one without the other (the single source of drift). All run
    # on the engine/loop thread; see the ``__init__`` note on lock-free
    # cross-thread reads.

    def _waiting_add(self, req: Request, *, left: bool = False) -> None:
        """Append ``req`` to ``waiting`` (right by default, left on preempt)."""
        if left:
            self.waiting.appendleft(req)
        else:
            self.waiting.append(req)
        if not req.is_flex:
            self._n_waiting_interactive += 1
        if self._task_queues is not None:
            self._task_queues.waiting_added(req, left=left)
        note_waiting_add(self, req, left=left)

    def _waiting_remove(self, req: Request) -> bool:
        """Remove ``req`` from ``waiting`` if present; return whether it was."""
        if not _discard_by_identity(self.waiting, req):
            return False
        if not req.is_flex:
            self._n_waiting_interactive -= 1
        if self._task_queues is not None:
            self._task_queues.waiting_removed(req)
        note_waiting_remove(self, req)
        return True

    def _running_add(self, req: Request) -> None:
        """Append ``req`` to ``running`` and bump the matching tally."""
        self.running.append(req)
        if req.is_flex:
            self._n_running_batch += 1
        else:
            self._n_running_interactive += 1
        if self._task_queues is not None:
            self._task_queues.running_added(req)

    def _running_remove(self, req: Request) -> bool:
        """Remove ``req`` from ``running`` if present; return whether it was."""
        if not _discard_by_identity(self.running, req):
            return False
        if req.is_flex:
            self._n_running_batch -= 1
        else:
            self._n_running_interactive -= 1
        if self._task_queues is not None:
            self._task_queues.running_removed(req)
        return True

    def set_task_policies(self, policies) -> None:
        """Queue each declared task apart (:mod:`arbi_serve.scheduler.task_queues`); an empty
        mapping keeps the one FCFS queue. The queues are rebuilt from ``waiting`` and
        ``running``, so this is safe at any point between steps."""
        from arbi_serve.scheduler.task_queues import TaskQueues

        if not policies:
            self._task_queues = None
            return
        queues = TaskQueues(policies)
        queues.rebuild(self.waiting, self.running)
        self._task_queues = queues

    def task_queue_stats(self) -> dict:
        """Per-task waiting/running rows and policy, for the stats endpoints (``{}`` when off)."""
        return {} if self._task_queues is None else self._task_queues.snapshot()

    # ── O(1) priority predicates derived from those counters ─────────

    def must_drain_background(self, req: Request) -> bool:
        """Run a background row despite pending interactive work when its exclusive
        cohort blocks a higher-priority bulk task: otherwise neither can progress.
        Real (running or runnable) interactive work still wins."""
        from arbi_serve.scheduler.task_queues import task_of

        queues = self._task_queues
        return (
            queues is not None
            and not self._n_running_interactive
            and queues.must_drain_for_interactive_bulk(task_of(req))
        )

    def any_batch_waiting(self) -> bool:
        """Whether any background-priority request is queued.

        ``_n_waiting_interactive`` counts every NON-batch waiting request
        (interactive and duplex alike), so the batch population is exactly
        the remainder of ``len(waiting)`` — the predicate needs no scan.
        """
        n_non_batch = self._n_waiting_interactive
        if isinstance(n_non_batch, int):
            return len(self.waiting) > n_non_batch
        return any(r.is_flex for r in self.waiting)

    def any_interactive_present(self) -> bool:
        """Whether any non-batch request is queued or running.

        The slate-construction gate behind interactive-always-priority
        (:func:`~arbi_serve.scheduler.step_budget.compute_step_budget`),
        read off the priority-split counters instead of scanning both
        deques. Duplex-lane requests count as non-batch on both sides,
        exactly as the scans they replace did.
        """
        n_waiting = self._n_waiting_interactive
        n_running = self._n_running_interactive
        if isinstance(n_waiting, int) and isinstance(n_running, int):
            return (n_waiting + n_running) > 0
        return any(not r.is_flex for r in self.waiting) or any(not r.is_flex for r in self.running)

    def _assert_admission_counters(self) -> None:
        """Reconcile the O(1) admission counters against a brute-force recount.

        Cheap O(queue+running) check a TEST calls after every mutation — a
        drifted counter would silently break the admission gate (over- or
        under-counting interactive demand). Nothing on the serving path
        calls it; the recount is O(queue+running) per call.
        """
        wi = sum(1 for r in self.waiting if not r.is_flex)
        ri = sum(1 for r in self.running if not r.is_flex)
        rb = sum(1 for r in self.running if r.is_flex)
        di = sum(1 for r in self._deferred_admits if not r.is_flex)
        if (
            wi != self._n_waiting_interactive
            or ri != self._n_running_interactive
            or rb != self._n_running_batch
            or di != self._n_deferred_interactive
        ):
            raise AssertionError(
                "admission counter drift: "
                f"waiting_interactive {self._n_waiting_interactive} != {wi}, "
                f"running_interactive {self._n_running_interactive} != {ri}, "
                f"running_batch {self._n_running_batch} != {rb}, "
                f"deferred_interactive {self._n_deferred_interactive} != {di}"
            )

    def set_pageless_whole_prompts_fn(self, fn: Callable[[], bool] | None) -> None:
        """Wire the engine's "do whole-prompt steps run without KV right now?".

        A pooling instance whose model admits the cache-free varlen forward
        (:func:`arbi_serve.engine.run_step.embed.pageless_whole_prompts`) reads
        no K/V an earlier step wrote and writes none a later step reads on a
        step of whole prompts, so those rows need no page: :meth:`schedule`
        then admits them without reserving any (marking ``req.kv_pageless``) and
        the pool bounds only prompts that are chunked across steps. Read once
        per :meth:`schedule` call, on the engine thread.
        """
        self._pageless_whole_prompts_fn = fn

    def set_kv_windowless(self, windowless: bool) -> None:
        """Wire a windowless boot (``boot_state.kv_windowless``): the KV pool holds
        no context, only the null sentinel and a page.

        Every row of such an engine must run as a pageless whole prompt. One that
        cannot this step — the activation gate narrowed it below its prompt, or the
        cache-free forward is unavailable — waits for a later step instead of being
        split across steps, which would need the context window the pool does not
        keep. The boot sizes the step budget for a whole ``max_context`` prompt, so
        a deferral happens only while the card is tighter than that budget.
        """
        self._kv_windowless = bool(windowless)

    def _windowless_defers(self) -> bool:
        """Whether a row that cannot run pageless must wait (a windowless boot never
        splits a prompt; :meth:`set_kv_windowless`). Counts each deferral."""
        if self._kv_windowless:
            _WINDOWLESS_DEFERRED.fired = 1
        return self._kv_windowless

    def _pageless_whole_prompt(self, req: Request, want: int) -> bool:
        """Whether ``req`` may take this step as a pageless whole prompt of ``want``."""
        return (
            req.prompt_consumed == 0
            and want == len(req.prompt_token_ids)
            and req.multimodal is None
            and not bool(getattr(req.sampling, "cache_enabled", True))
        )

    def set_casper_handoff_fn(self, fn: Callable[[], bool], *, pipeline: bool = False) -> None:
        """Wire the engine's "does a CASPER side plane route this model's prefill?"."""
        self._casper_handoff_fn = fn
        self._casper_pipeline_tail = pipeline

    def _prefill_handoff_cap(self, req: Request, want: int) -> int:
        from arbi_serve.distributed.kv_prefix_resume import computed_prefix

        prefix = computed_prefix(req)
        if prefix is not None:
            want = min(want, max(0, prefix - req.prompt_consumed))
        else:
            want = self._casper_prompt_cap(req, want)
        handoff = getattr(self, "_pp_kv_handoff", None)
        if handoff is not None:
            from arbi_serve.distributed.kv_ring_snapshot import cap_tail

            want = cap_tail(handoff, req, want)
        return want

    _casper_handoff_cap = _prefill_handoff_cap  # compatibility for older callers

    def _casper_prompt_cap(self, req: Request, want: int) -> int:
        """Stop a chunk one token short of its prompt's end on a CASPER-armed model.

        The first token is read from a prompt's last position, so that position never
        runs sparse (``models._casper_side_route``). The chunk that would end the prompt
        stops one token short and prefills sparse; :meth:`_casper_hand_off` then gives
        the request to the decode path, whose first step runs the prompt's last token
        on the EXL3 decode kernels, beside that step's other decode rows, and samples
        the first token from it. Nothing is computed twice. A request that reads prompt
        logprobs runs dense in any case, so it keeps its chunk whole.
        """
        fn = getattr(self, "_casper_handoff_fn", None)
        remaining = req.num_remaining_prompt
        if fn is None or remaining < 2 or want < remaining:
            return want
        if int(getattr(req.sampling, "prompt_logprobs", 0) or 0) or not fn():
            return want
        # PP must finish PREFILL on every rank so prompt-end KV publication
        # and remote handoff include the last position. Leave a one-token
        # dense prefill tail instead of moving this row early into decode.
        req._casper_handoff = not getattr(self, "_casper_pipeline_tail", False)
        return remaining - 1

    def _prefill_hand_off(self, req: Request) -> None:
        """Move a request whose prefill stopped one token short into decode.

        The prompt's last token becomes the input of the request's first decode row:
        with no output yet, a decode row feeds ``prompt_token_ids[-1]`` at position
        ``total_length - 1``, and its KV slot and recurrent state step are the decode
        step's own, exactly as for every decoded token. The prompt-completing chunk's
        own bookkeeping (the whole-prompt radix commit and the prompt-end savepoint) is
        skipped: its incremental publishes already cover the positions a forward wrote,
        and a whole-prompt commit would publish a page holding the one position no
        forward has written yet. The decode boundaries after it snapshot as usual.
        """
        from arbi_serve.engine.request import RequestState, set_state

        req.prompt_consumed = len(req.prompt_token_ids)
        set_state(req, RequestState.DECODING)
        metrics = getattr(self, "_metrics", None)
        if metrics is not None:
            metrics.prefill_dec()
            metrics.decode_inc()
        if getattr(req, "_casper_handoff", False):
            _CASPER_HANDOFF.fired += 1

    _casper_hand_off = _prefill_hand_off  # compatibility for older callers

    def set_forward_in_flight_fn(self, fn: Callable[[], bool]) -> None:
        """Wire the engine's "is a forward in flight?" predicate.

        Used by the admission-time recurrent-row self-heal to decide
        whether a suspend can run inline or must be deferred to the next
        between-forwards :meth:`schedule` tick.
        """
        self._forward_in_flight_fn = fn

    def set_pp_kv_handoff(self, handoff) -> None:
        """Wire the ARBI_PP_KV_REPLICATE_DECODE_HANDOFF hook (coordinator rank only).

        See :mod:`arbi_serve.distributed.pp_kv_handoff`. ``commit_state``
        calls ``handoff.maybe_consolidate(req)`` the instant a request's
        prefill completes; ``None`` (the default) is a complete no-op.
        """
        self._pp_kv_handoff = handoff

    def set_spmd_deferred_release(self, fn: Callable[[int], None] | None) -> None:
        """Defer rank-0 finish-side page mutations to the SPMD replay point.

        ``fn(request_id)`` queues the request on the SPMD driver's
        pending-release list; the driver DRAINS it at the top of the NEXT
        tick — running the mirror-sourced finish-commit
        (:meth:`SpmdRankLoop.commit_full_pages_on_finish`), the
        ``page_table.remove_request`` free, and the recurrent-slab free at
        the byte-exact point a WORKER's ``apply_delta`` evict replay runs
        them (start of its next tick: before that tick's preempt replays,
        LRU-eviction replays, and per-step allocations). With it set, BOTH
        rank-0 finish paths (:meth:`finished` and :meth:`remove`) skip
        their immediate page-table / recurrent-pool mutations and queue
        instead.

        Why DEFERRAL (not just a different commit source) — the c8 radix
        divergence is an ORDERING break, two ways:

          1. Rank 0 finish-commits MID-TICK (``post_token`` →
             :meth:`finished` during the verify stream / legacy commit),
             i.e. BEFORE the same tick's later prompt-completion commits,
             while the worker replays the finish at the START of the NEXT
             tick, i.e. AFTER them. Requests race-committing the SAME
             prefix chunks (concurrent same-doc prefill) then dedup in a
             DIFFERENT order per rank → the chunk→page bindings rotate —
             the observed ``add_request_spmd`` broadcast-page mismatch.
          2. Rank 0 FREES the finished request's pages mid-tick: a verify
             tick's legacy sub-pass derive allocates AFTER the verify
             stream, so rank 0's allocation can draw the just-freed pages
             while the worker's byte-identical allocation cannot (its free
             lands one tick later) → pool free-list divergence. The flat
             table is armed too: a row finished by the drain of a pipelined
             tick is still on the next tick's slate, and its verify plan
             allocates for it (see
             :mod:`arbi_serve.engine.distributed_driver_spmd_release`).

        Content also matters: rank 0's Request token list can be SHORTER
        than the mirror (the verify stream stops appending at a mid-accept
        finish; a FAILED step never commits to the Request at all), and
        ``remove`` (cancel / timeout) never committed — while the worker's
        replay always commits the mirror view. The drain therefore commits
        from the SAME replicated mirror the worker reads. ``None`` restores
        the single-process behaviour (immediate release, Request-sourced
        commit).
        """
        self._spmd_deferred_release = fn

    def enable_spmd_preempt_log(self, enabled: bool = True) -> None:
        """Start (or stop) logging preemptions for the SPMD delta builder.

        Armed by the SPMD rank-0 driver, which is the only thing that
        drains the log. Off elsewhere so a single-process server does not
        accumulate an entry per preemption for the life of the process.
        """
        self._spmd_preempt_log = bool(enabled)
        if not enabled:
            self._spmd_preempted = []

    def record_spmd_preempt(
        self,
        request_id: int,
        new_prompt_len: int,
        *,
        prefix_match_len: int = 0,
        prefix_page_ids: list[int] | None = None,
        cache_enabled: bool | None = None,
        retain_enabled: bool | None = None,
    ) -> None:
        """Log one preemption for the SPMD delta builder to broadcast.

        Called by :meth:`Preemptor.preempt_for_space` the moment a victim's
        pages are freed and its decode state reset — the ONE point at which
        the decision is unambiguous. A no-op unless
        :meth:`enable_spmd_preempt_log` armed the log (i.e. an SPMD rank-0
        driver is there to drain it).

        ``prefix_match_len`` / ``prefix_page_ids`` are the radix re-match
        rank 0's re-admit applied, and they ride the wire for exactly the
        reason :class:`AdmitRow`'s do: the match is the one non-derivable
        decision (its cap depends on rank 0's savepoint store, which a
        worker has no copy of), while everything around it is in lockstep.
        ``cache_enabled`` OVERRIDES the flag the re-admit seam carries off
        the victim's own entry; ``None`` (the default) keeps it, which is
        right for every preempt. Rank 0 sets it only where its re-bind
        resolved a DIFFERENT value — the hybrid force-disable — because a
        worker that missed that promotes pages rank 0 did not, splitting
        the per-rank free lists. The preempt itself is page-less, so all
        three arrive later, through :meth:`amend_spmd_preempt`.
        """
        if self._spmd_preempt_log:
            self._spmd_preempted.append(
                SpmdPreempt(
                    request_id=int(request_id),
                    new_prompt_len=int(new_prompt_len),
                    prefix_match_len=int(prefix_match_len),
                    prefix_page_ids=tuple(int(p) for p in (prefix_page_ids or ())),
                    cache_enabled=None if cache_enabled is None else bool(cache_enabled),
                    retain_enabled=None if retain_enabled is None else bool(retain_enabled),
                )
            )

    def amend_spmd_preempt(
        self,
        request_id: int,
        *,
        prefix_match_len: int,
        prefix_page_ids: list[int],
        cache_enabled: bool | None,
        retain_enabled: bool | None = None,
    ) -> None:
        """Attach the prefix re-bind's result to this tick's logged preempt.

        A preempt is decided in two steps inside ONE ``schedule()`` call:
        the victim's pages are freed (:meth:`record_spmd_preempt`), and
        then — if the same admission pass puts it back on the slate — it
        re-claims what the tree still holds
        (``Scheduler._rebind_preempted_prefix``). Both are rank-0 decisions
        a worker must replay, and they belong to the same
        :class:`PreemptRow`, so the second amends the first rather than
        opening a second wire type for it.

        Safe because the drain runs after ``schedule()`` returns and the
        re-bind can only fire within it (``_preempt_rebind_ids`` is cleared
        per call): the entry being amended is always still undrained.
        Amends the LAST entry for ``request_id`` — the victim may have been
        preempted more than once in a tick, and it is the current residency
        being re-bound. A no-op when the log is not armed.
        """
        if not self._spmd_preempt_log:
            return
        for i in range(len(self._spmd_preempted) - 1, -1, -1):
            if self._spmd_preempted[i].request_id == int(request_id):
                self._spmd_preempted[i] = self._spmd_preempted[i]._replace(
                    prefix_match_len=int(prefix_match_len),
                    prefix_page_ids=tuple(int(p) for p in prefix_page_ids),
                    cache_enabled=None if cache_enabled is None else bool(cache_enabled),
                    retain_enabled=None if retain_enabled is None else bool(retain_enabled),
                )
                return

    def drain_spmd_preempts(self) -> list[SpmdPreempt]:
        """Take (and clear) the preemptions logged since the last drain.

        The SPMD rank-0 delta builder drains this once per tick and turns
        each entry into a :class:`PreemptRow`, so every worker replays the
        SAME page free + re-add + recurrent-slab recycle + mirror reset
        that rank 0's :class:`Preemptor` just performed.

        This log — not a post-hoc scan of request state — is the source of
        truth because a preempted victim is pushed to the HEAD of
        ``waiting`` (:meth:`_waiting_add` with ``left=True``) and the SAME
        ``schedule()`` call's waiting-admit pass can re-admit it onto the
        very slate the preempt made room for. Such a victim is on the
        tick's slate, alive, and mid-prefill again — indistinguishable by
        inspection from a request that was simply scheduled, so the scan it
        replaced silently dropped its :class:`PreemptRow`.
        """
        out = self._spmd_preempted
        self._spmd_preempted = []
        return out

    def shutdown(self) -> None:
        """Sever every reference this scheduler holds to the model's GPU
        state, so an in-process model reload can free the KV pool even while
        the run loop's suspended frame still pins THIS scheduler object.

        The whole-engine reload (:func:`arbi_serve.engine.lifecycle.release_for_reload`)
        sets ``eng.scheduler = None``, but the run-loop coroutine is parked
        at an ``await`` with a live local ``drain_dropped =
        eng.scheduler.drain_dropped_suspended`` bound method — which keeps
        alive past ``free_all``. (Full ``shutdown()`` doesn't hit this
        because it terminates the run loop, destroying that frame.) Nulling
        the pool / page-table / collaborator refs here breaks the heavy path
        regardless; the lightweight gutted Scheduler is released on the first
        post-rebuild loop iteration, when the loop rebinds its locals to the
        new scheduler. Idempotent."""
        self.pool = None
        self.page_table = None
        self._commit_full_pages = None
        self._spmd_deferred_release = None
        self._preemptor = None
        self._offload_manager = None
        self._savepoint_snapshotter = None
        self._savepoint_store = None
        self._savepoint_chain_bs = None
        self._savepoint_page_bs = 0
        self._savepoint_fold_grid = 0
        self._fold_split_armed = None
        self._parking_enabled = False
        self._metrics = None
        self.grouper = None
        for dq in (self.waiting, self.running, self.suspended, self._deferred_admits):
            dq.clear()
        self._dropped_suspended.clear()
        # Deques cleared above — reset the O(1) admission tallies in lock
        # step so a post-reload Scheduler that somehow reused this object
        # would not start with a stale count.
        self._n_waiting_interactive = 0
        self._n_running_interactive = 0
        self._n_running_batch = 0
        self._n_deferred_interactive = 0
# ---- scheduler_offload.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Suspended-job KV offload (batch-backlog parking) delegator mixin.

The offload POLICY lives in :mod:`arbi_serve.scheduler.offload_manager`;
these are thin delegators kept on :class:`Scheduler` so the
``_add_inner`` self-heal and the test reach-ins keep working. The
parked-job deques (:attr:`suspended`, :attr:`_dropped_suspended`) are
created in :meth:`Scheduler.__init__`.

Shared attributes are declared as class-level annotations (mirrors
:mod:`arbi_serve.cache._pool_base`).
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from arbi_serve.cache import _metrics as cache_metrics
from arbi_serve.cache._state_pool_common import kv_parking_serves_here
from arbi_serve.engine.request import RequestState

if TYPE_CHECKING:
    from collections import deque

    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.offload_manager import OffloadManager


class _OffloadMixin:
    """Thin delegators over the :class:`OffloadManager` collaborator."""

    # ── Shared scheduler state (set in ``Scheduler.__init__``) ────────
    _offload_manager: OffloadManager
    _parking_enabled: bool
    page_table: Any
    pool: Any
    running: deque[Request]

    @property
    def parking_enabled(self) -> bool:
        """Whether a park can happen here: asked for, AND somewhere to park.

        BOTH halves, read together and never cached. Parking pins a request's
        prefix in the prefix tier, so a deployment that asks for parking
        without a radix page table or without the tier has asked for something
        this boot cannot do — and the boot REFUSES BY NAME rather than
        arriving here (see ``engine/active.py``). This property is what every
        caller asks instead of reaching for a store, so "can we park?" has one
        answer and not one per call site.
        """
        if not self._parking_enabled:
            return False
        return getattr(self.page_table, "_tier_store", None) is not None

    def _manage_offload(self) -> None:  # delegator → OffloadManager.manage
        self._offload_manager.manage()

    def _yield_row_to_interactive(self) -> bool:
        """Freeze one flex decode row so its recurrent row can seat an interactive request.

        On a hybrid the recurrent rows ARE the concurrency bound, so flex rows holding all of
        them would hold an interactive arrival in the deferred pen until one finished. A
        freeze moves no paged KV: it syncs the row's recurrent state into the prefix tier as
        a pinned tail entry (priced against the tier's pin budget) and frees the slot, so it
        needs the tier and nothing ``cache.kv_offload_enabled`` adds. Refused where a park is
        (:func:`kv_parking_serves_here`): the SPMD wire carries no freeze, so only rank 0
        would free the row. A request that declined the shared cache is never frozen into it.
        The newest flex row goes first, as the one with the least decode sunk into its slot.
        """
        if not kv_parking_serves_here(self.pool)[0]:
            return False
        for victim in reversed(list(self.running)):
            if (
                victim.is_flex
                and victim.state == RequestState.DECODING
                and getattr(victim.sampling, "cache_enabled", True)
                and self._offload_manager.freeze_in_place(victim)
            ):
                cache_metrics.counter_inc(
                    "arbi_serve.scheduler.preempt_flex_yield_total",
                    labels={"service_tier": "flex"},
                )
                return True
        return False

    def _resume_frozen_without_parking(self) -> None:
        """Unfreeze the flex rows :meth:`_yield_row_to_interactive` stood down, once no
        interactive request is queued, running or deferred.

        A boot that parks resumes through :meth:`OffloadManager.manage`; this is the same
        resume for one that does not, where the only stood-down rows are those freezes and
        the parks the allocation path made of them under page pressure.
        """
        if not self._interactive_present():
            self._offload_manager._resume_parked(allow_batch=True)

    def drain_dropped_suspended(self) -> list[Request]:
        """Return + clear jobs whose resume failed irrecoverably.

        Thin delegator to :meth:`OffloadManager.drain_dropped_suspended`;
        the engine run loop runs the terminal path for each.
        """
        return self._offload_manager.drain_dropped_suspended()

    def _suspend_to_offload(self, req: Request) -> bool:  # → OffloadManager
        return self._offload_manager.suspend_to_offload(req)

    def _resume_from_offload(self, req: Request) -> bool:  # → OffloadManager
        return self._offload_manager.resume_from_offload(req)
# ---- scheduler_quota.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""TenantContext-aware admission (rate-limit + concurrency quota) mixin.

Thin delegators over the
:class:`~arbi_serve.scheduler.quota_filter.QuotaFilter` collaborator
plus the two static tenant-id resolvers.

Shared attributes are declared as class-level annotations (mirrors
:mod:`arbi_serve.cache._pool_base`).
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from arbi_serve.tenant.context import ANONYMOUS_TENANT, TenantContext

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.quota_filter import QuotaFilter
    from arbi_serve.tenant.quota import QuotaTracker


class _QuotaMixin:
    """Per-tenant rate-limit + concurrency-cap admission filter delegators."""

    # ── Shared scheduler state (set in ``Scheduler.__init__``) ────────
    _quota_filter: QuotaFilter

    @staticmethod
    def _tenant_for(req: Request) -> TenantContext:
        """Return the request's :class:`TenantContext`, fallback-safe.

        Reads :attr:`Request.tenant`; falls back to
        :data:`ANONYMOUS_TENANT` when missing. Never raises.
        """
        return getattr(req, "tenant", None) or ANONYMOUS_TENANT

    @staticmethod
    def _tenant_id_for(req: Request) -> str:
        """Resolve the cache-namespace tenant id for ``req``.

        Resolution: ``tenant.tenant_id``, then ``req.tenant_id``, then
        ``""`` (global namespace — preserves cross-request sharing).

        LoRA isolation: a request's KV depends on its active adapter, so
        the adapter id is folded into the namespace. Two requests sharing
        a prompt but using DIFFERENT adapters (or base vs an adapter)
        must NOT share radix / savepoint cache pages — otherwise the
        second request decodes against KV computed under the wrong
        adapter (silent correctness bug; surfaces as "a zero-delta
        adapter changes the output" because it reuses another adapter's
        cached prefix). ``lora_id is None`` (no adapter) keeps the
        original namespace, so non-LoRA traffic is byte-for-byte
        unchanged.
        """
        tenant = getattr(req, "tenant", None)
        base = ""
        if tenant is not None:
            tid = getattr(tenant, "tenant_id", None)
            if tid and tid != "anon":
                base = tid
        if not base:
            base = getattr(req, "tenant_id", "") or ""
        lora_id = getattr(req, "lora_id", None)
        if lora_id is not None:
            return f"{base}\x00lora={lora_id}"
        return base

    def _apply_tenant_quota(
        self,
        slate: list[tuple[Request, int]],
    ) -> list[tuple[Request, int]]:
        """Drop slate rows whose tenant has exhausted its quota.

        Thin delegator to :meth:`QuotaFilter.apply` (policy + deferral
        counters in ``scheduler.quota_filter``).
        """
        return self._quota_filter.apply(slate)

    def deferred_by_quota(self) -> dict[str, int]:
        """Return per-reason deferral counts since boot (test / metrics hook).

        Thin delegator to :meth:`QuotaFilter.deferred_by_quota`.
        """
        return self._quota_filter.deferred_by_quota()

    @property
    def quota_tracker(self) -> QuotaTracker:
        """Expose the tracker so the engine terminal-state hook can call
        :meth:`QuotaTracker.release` on request finish."""
        return self._quota_filter.tracker
# ---- scheduler_selection.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Waiting-queue selection / prefix-serial / MTP-bucketing mixin.

Covers the per-step waiting-candidate picker, the optional
prefix-serial policy, the thin MTP uniform-K bucketing delegator, and
the duplex-lane-only slate builder.

Shared attributes are declared as class-level annotations (mirrors
:mod:`arbi_serve.cache._pool_base`).
"""

from __future__ import annotations

import sys
from typing import TYPE_CHECKING

from arbi_serve.engine.request import RequestState, set_state

if TYPE_CHECKING:
    from collections import deque

    from arbi_serve.cache.pagetable import FlatPageTable
    from arbi_serve.cache.radix_pagetable import RadixPageTable
    from arbi_serve.config import BatchConfig, CacheConfig
    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.mtp_bucketing import MtpBucketer
    from arbi_serve.scheduler.prefix_grouping import PrefixGrouper, PrefixSerialContext
    from arbi_serve.scheduler.task_queues import TaskQueues
    from arbi_serve.server.metrics import Metrics


#: :attr:`_SelectionMixin.step_token_cap` when nothing narrows the step.
UNCAPPED = sys.maxsize


class _SelectionMixin:
    """Waiting-queue candidate selection + prefix serial + MTP bucketing."""

    # ── Shared scheduler state (set in ``Scheduler.__init__``) ────────
    waiting: deque[Request]
    running: deque[Request]
    batch_cfg: BatchConfig
    cache_cfg: CacheConfig
    page_table: FlatPageTable | RadixPageTable
    grouper: PrefixGrouper | None
    _mtp_bucketer: MtpBucketer
    _metrics: Metrics | None
    _duplex_ever_admitted: bool
    _duplex_consecutive_ticks: int
    _task_queues: TaskQueues | None
    #: This tick's token allowance where it is narrower than
    #: ``batch_cfg.max_batched_tokens``: an attention-DP member's share of a
    #: step its peers also draw from (``AttnDpSchedulerGroup.schedule_per_dp``).
    step_token_cap: int = UNCAPPED

    def _solo_prefill_paced_out(self, req: Request) -> bool:
        """True iff ``req``'s next prefill chunk is held out of THIS tick.

        ``ARBI_PP_COADMIT_PREFILL_EVERY_N``, whose whole decision — including
        deriving N from this engine's own tick clock when the operator pinned
        no number — lives in :mod:`arbi_serve.scheduler.coadmit_pacing`.
        """
        ready = getattr(self, "_media_prefill_ready", None)
        if ready is not None and not ready(req):
            return True
        return self._coadmit_pacer.paced_out(req, self.running)

    def _prefill_runs_on_peer(self, req: Request) -> bool:
        """Whether ``req``'s next prefill chunk is a forward on the PEER rank.

        True only for a row ``ARBI_PP_PREFILL_SOLO_BESIDE_DECODE`` pinned to
        the other rank (``pp_kv_handoff._arm_solo_prefill``): such a chunk
        is dispatched from this tick but computed on the other card, so it
        draws ``schedule()``'s ``peer_token_budget`` rather than this rank's.
        One ``getattr`` miss on every engine without the flag.
        """
        if not getattr(req, "_pp_prefill_solo", False):
            return False
        handoff = getattr(self, "_pp_kv_handoff", None)
        if handoff is None:
            return False
        host = getattr(req, "_pp_decode_host_rank", None)
        return host is not None and int(host) != int(handoff.parallel_cfg.rank)

    def _next_waiting_candidate(
        self,
        any_batch_waiting: bool,
        prefix_context: PrefixSerialContext | None = None,
    ) -> Request | None:
        """Pick the next waiting request to attempt admitting this step.

        Priority-aware, FCFS-within-class selection:

          * Fast path — no batch waiting (``any_batch_waiting=False``,
            all-interactive default) AND the head of the queue isn't a
            duplex-lane request: return ``self.waiting[0]`` verbatim, no
            extra scan.
          * Mixed path — prefer the oldest INTERACTIVE waiting request;
            only when none is waiting consider batch, and then only if the
            interactive backlog sits at/below
            ``batch_admit_waiting_watermark`` (default 0 ⇒ empty queue).

        Duplex-lane requests (``is_duplex_frame``) are INVISIBLE to this
        picker regardless of path — this method is only ever called from
        ``Scheduler.schedule()``'s ordinary (non-duplex) tick body, since
        a duplex tick short-circuits before reaching it (see the duplex-
        lane exclusivity gate at the top of ``schedule()``). A duplex
        request is admitted from ``waiting`` exclusively by
        ``Scheduler._build_duplex_slate`` on a duplex tick, never here.

        Returns ``None`` when only watermark-held batch candidates remain
        (caller stops admitting; they retry next step). The returned
        request is NOT removed from ``self.waiting`` — the caller pops it
        by identity once it clears the allocation / budget gates.
        """
        if not self.waiting:
            return None
        preparation_ready = getattr(self, "_media_preparation_ready", None)
        if preparation_ready is not None and getattr(self, "_task_queues", None) is not None:
            queues = self._task_queues
            original = queues.admission_ready

            def ready(request):
                return (
                    (original is None or original(request))
                    and preparation_ready(request)
                    and (prefix_context is None or prefix_context.pick([request]) is request)
                )

            queues.admission_ready = ready
            try:
                return self._next_task_candidate(queues)
            finally:
                queues.admission_ready = original
        if preparation_ready is not None:
            eligible = [r for r in self.waiting if not r.is_duplex_frame and preparation_ready(r)]
            interactive = [r for r in eligible if not r.is_flex]
            if interactive:
                return (
                    interactive[0] if prefix_context is None else prefix_context.pick(interactive)
                )
            if int(getattr(self.batch_cfg, "batch_admit_waiting_watermark", 0)) < 0:
                return None
            if not eligible:
                return None
            return eligible[0] if prefix_context is None else prefix_context.pick(eligible)
        if self._task_queues is not None and prefix_context is None:
            return self._next_task_candidate(self._task_queues)
        if not any_batch_waiting and not self.waiting[0].is_duplex_frame:
            if prefix_context is None:
                return self.waiting[0]
            return prefix_context.pick(self.waiting)
        # Mixed queue (batch present, and/or the head is duplex-lane).
        # Find the oldest interactive request first, skipping duplex
        # entirely -- it's neither "interactive" nor "background" here, just
        # invisible to this picker.
        #
        # The scan stops at that first interactive request: everything the
        # rest of the queue could contribute (the batch fallback, the
        # interactive backlog count) is read ONLY on the no-interactive
        # branch below. And when ``_n_waiting_interactive`` -- which counts
        # every non-batch waiting request, duplex included -- is zero, the
        # queue is all batch, so the scan has nothing to find and the
        # oldest batch candidate is the head.
        first_interactive: Request | None = None
        first_batch: Request | None = None
        if self._n_waiting_interactive:
            for r in self.waiting:
                if r.is_duplex_frame:
                    continue
                if r.is_flex:
                    if first_batch is None:
                        first_batch = r
                else:
                    first_interactive = r
                    break
        else:
            first_batch = self.waiting[0]
        if first_interactive is not None:
            if prefix_context is None:
                return first_interactive
            return prefix_context.pick(
                r for r in self.waiting if not r.is_flex and not r.is_duplex_frame
            )
        # No interactive waiting — the scan above proves the interactive
        # backlog is 0 here, so the watermark gate reduces to its own
        # sign. Kept explicit: it documents the contract and lets a
        # future caller pass a non-empty interactive queue.
        watermark = int(getattr(self.batch_cfg, "batch_admit_waiting_watermark", 0))
        if watermark >= 0:
            if prefix_context is None:
                return first_batch
            return prefix_context.pick(
                r for r in self.waiting if r.is_flex and not r.is_duplex_frame
            )
        return None

    def _next_task_candidate(self, queues: TaskQueues) -> Request | None:
        """The picker over per-task queues (:mod:`arbi_serve.scheduler.task_queues`).

        The same class rules as the single queue: an interactive request before any batch one,
        and batch only when the watermark admits it. Within a class, the best task (latency
        class, priority) among those under their ``max_inflight`` and past their batch cadence
        goes first, oldest request first within the task. ``running`` already holds every row
        this step admitted, so a task's bound counts them, and a non-empty ``running`` means the
        step runs work anyway, so a task may wait for batch mates without idling the GPU.
        """
        busy = bool(self.running)
        req = queues.pick(interactive_only=True, slate_has_work=busy)
        if req is not None:
            return req
        if int(getattr(self.batch_cfg, "batch_admit_waiting_watermark", 0)) < 0:
            return None
        return queues.pick(interactive_only=False, slate_has_work=busy)

    def _bucket_mtp_k_uniform(self, slate: list[tuple[Request, int]]) -> list[tuple[Request, int]]:
        """Drop MTP-opted decode rows whose K differs from the chosen step K.

        Thin delegator to :meth:`MtpBucketer.bucket_uniform` (single-K
        per-step filter + ``_mtp_k_skip_counts`` bookkeeping live in
        ``scheduler.mtp_bucketing``).
        """
        return self._mtp_bucketer.bucket_uniform(slate)

    @property
    def mtp_spec_disabled_by_load(self) -> bool:
        """Whether the load valve is currently suppressing speculation.

        The engine-side truth behind the admin ``server_info`` field and the
        ``spec-decode DISABLED by load`` log line: ``True`` means MTP-opted
        rows are decoding without drafting because the decode batch reached
        ``mtp_spec_disable_batch``.
        """
        return self._mtp_bucketer.spec_disabled_now

    @property
    def mtp_spec_disabled_steps(self) -> int:
        """Monotonic count of admission steps the load valve suppressed
        speculation on. The heartbeat ships its delta as
        ``arbi_serve_mtp_spec_disabled_steps_total``."""
        return self._mtp_bucketer.spec_disabled_steps

    @property
    def mtp_spec_disable_threshold(self) -> int:
        """The load valve's resolved threshold as of the last admission step
        (``0`` = never disable). In ``auto`` this is the smallest width the
        valve has MEASURED a stop verdict at, so the number means the same
        thing it does under a pinned threshold."""
        return self._mtp_bucketer.spec_disable_threshold

    @property
    def mtp_spec_disable_mode(self) -> str:
        """The valve's tri-state as of the last admission step — ``off`` /
        ``on`` / ``auto``. The number above is not self-describing: an
        operator-pinned 2 and an ``auto`` that measured 2 are different
        facts about the deployment."""
        return self._mtp_bucketer.spec_disable_mode

    @property
    def mtp_spec_disable_source(self) -> str:
        """Where the resolved threshold came from — an operator, a live
        measurement, or the architecture fallback."""
        return self._mtp_bucketer.spec_disable_source

    @property
    def mtp_spec_disable_detail(self) -> str:
        """One line naming the live reason for the valve's current arm."""
        return self._mtp_bucketer.spec_disable_detail

    @property
    def mtp_spec_valve_widths(self) -> dict:
        """``auto``'s per-cell arm estimates; empty until ``auto`` has run."""
        return self._mtp_bucketer.valve_widths()

    def duplex_tick_due(self, now: float) -> bool:
        """Whether THIS step should serve the duplex lane exclusively.

        The single source of truth for the duplex-lane gate's readiness +
        deadline question, so the two callers that must agree exactly
        cannot drift apart (design doc §7.9):

          * ``Scheduler.schedule()``'s own exclusivity gate, which acts on
            a ``True`` by returning :meth:`_build_duplex_slate`'s slate;
          * ``run_forever``'s duplex pre-schedule hook
            (:mod:`arbi_serve.realtime.duplex_lane`), which acts on a
            ``True`` by setting every due session's
            ``pending_embed_override`` BEFORE ``schedule()`` runs. Both
            must be answered against the SAME ``now`` — the run loop reads
            the clock once and passes it to both — or a deadline crossing
            between the two calls would either feed a frame to a tick that
            never fires (stale override, wrong audio next tick) or fire a
            tick with no frame prepared.

        "Ready" is "at least one duplex-lane request exists in ``running``
        or ``waiting``" — a duplex session is ALWAYS ready, never skipped
        for want of audio: a tick with no client audio yet is fed a
        silence frame instead (design doc §2.2's shared 80 ms grid; the
        reference's own live-queue fallback), because skipping a tick
        would desync the frame-index-based ``agent_idle``/BOS-EOS
        bookkeeping from the grid.

        Readiness is asked PER SESSION (design doc §7.9.14): the lane is
        due when at least one duplex request's OWN
        ``next_duplex_deadline`` has come due. A request that has never
        ticked (``None``) is due immediately, so a freshly admitted
        session is not stuck waiting out a deadline nobody armed yet.
        Sessions with different cadences — a real-time conversation and a
        bounded, unpaced one — therefore coexist on one engine.
        """
        if not self._duplex_ever_admitted:
            # Ordinary deployment: one bool read per step, no scans (see
            # the latch's own comment in ``_add_inner``). This gate used
            # to scan ``running`` AND ``waiting`` on every step of every
            # deployment, duplex or not.
            return False
        return any(self._duplex_due(r, now) for r in self.running) or any(
            self._duplex_due(r, now) for r in self.waiting
        )

    def has_ordinary_work(self) -> bool:
        """Whether any NON-duplex request could be served by an ordinary
        slate right now — the fairness valve's second condition (see
        :meth:`duplex_lane_should_yield`).

        Deliberately "could be served", not "will be": a ``waiting`` row
        may still be refused for page room this step. Yielding a step to a
        queue that then produces an empty slate costs one 5 ms idle-park
        floor (``run_step/loop.py``) and is self-correcting; NOT yielding
        because the queue looked unschedulable would be the starvation
        this valve exists to bound. Same O(1) ``_duplex_ever_admitted``
        fast-out as its siblings, and only ever reached on the cap-th
        consecutive duplex step, never on an ordinary one.
        """
        if not self._duplex_ever_admitted:
            return True
        return any(not r.is_duplex_frame for r in self.running) or any(
            not r.is_duplex_frame for r in self.waiting
        )

    def duplex_lane_should_yield(self) -> bool:
        """Whether this due duplex step should be handed to ordinary
        traffic instead — ``batch_cfg.duplex_lane_max_consecutive_ticks``
        consecutive duplex steps have already been taken AND there is
        ordinary work waiting. See that field's own comment for the
        policy and why a paced session can never reach it."""
        cap = int(getattr(self.batch_cfg, "duplex_lane_max_consecutive_ticks", 0) or 0)
        if cap <= 0 or self._duplex_consecutive_ticks < cap:
            return False
        return self.has_ordinary_work()

    def next_duplex_deadline(self) -> float | None:
        """Earliest wall-clock instant any duplex session is next due, or
        ``None`` when no duplex session exists.

        The run loop's idle park needs this. ``duplex_tick_due`` answers
        "is a tick due NOW", which is the wrong question for a loop about
        to sleep: an empty slate means no session is due *yet*, not that
        the engine is idle, and parking past the nearest deadline drops
        every frame in between (design doc §7.14). ``0.0`` — a session
        that has never ticked, or an UNPACED one — means "due
        immediately", so the caller must not sleep at all.

        Mirrors :meth:`duplex_tick_due`'s O(1) fast-out and its
        ``getattr`` guard for the minimal request stand-ins CPU tests use.
        """
        if not self._duplex_ever_admitted:
            return None
        best: float | None = None
        for req in (*self.running, *self.waiting):
            if not req.is_duplex_frame:
                continue
            if not getattr(req, "duplex_tick_enabled", True):
                continue
            deadline = getattr(req, "next_duplex_deadline", None)
            if deadline is None:
                return 0.0
            if best is None or deadline < best:
                best = float(deadline)
        return best

    @staticmethod
    def _duplex_due(req: Request, now: float) -> bool:
        """``req`` is a duplex session whose own frame deadline is due.

        ``getattr``-guarded rather than a bare call: minimal request
        stand-ins in CPU tests predate ``Request.duplex_tick_due`` and
        must keep behaving as always-due duplex rows.
        """
        if not req.is_duplex_frame:
            return False
        due = getattr(req, "duplex_tick_due", None)
        return True if due is None else bool(due(now))

    def _duplex_row_size(self, req: Request, token_budget: int) -> tuple[int, int, bool]:
        """Size this duplex request's next row: ``(n, pages, is_prefill_row)``.

        Three row shapes, in the order a session meets them:

          * **Seed prefill** (``req.is_prefill``) — a chunked prefill row
            of ``min(num_remaining_prompt, chunk_prefill, token_budget)``
            tokens, reserving ``ceil(n / block_size)`` pages exactly like
            the ordinary prefill branch of ``Scheduler.schedule``. A
            duplex request's seed prompt is genuinely uncomputed KV (it
            is ``cache_enabled = False`` and has no cached prefix), so it
            gets a * **Context injection** — ``1 + len(pending_context_token_ids)``
            (``injection_row_width``), the tool-response resume row.
          * **Ordinary frame decode** — one token.

        ``n == 0`` means "no room in this step's token budget"; the
        caller skips the row and retries on the next duplex tick."""
        bs = self.cache_cfg.block_size
        # ``getattr``, not a bare read (here and below): minimal request
        # stand-ins in CPU tests predate these and must stay ordinary
        # decode rows. Defaulting ``is_prefill`` to ``False`` also keeps
        # ``num_remaining_prompt`` unreached for such a stand-in.
        if getattr(req, "is_prefill", False):
            want = min(
                req.num_remaining_prompt,
                int(self.batch_cfg.chunk_prefill),
                token_budget,
            )
            if want <= 0:
                return 0, 0, True
            return want, -(-want // bs), True
        row_n = getattr(req, "injection_row_width", 1)
        return row_n, self._decode_page_commit(req, row_n), False

    def _duplex_wide_row_owner(self, now: float, token_budget: int) -> Request | None:
        """The one due duplex request whose next row is WIDER than a single
        token, if any — that request owns this tick exclusively.

        **This is a correctness invariant, not a throughput heuristic**
        (design doc §7.9.18). A duplex tick's steady-state rows carry an
        embed override, and an override-carrying step is routed onto the
        single EAGER whole-batch forward by ``model_runner``'s
        ``_has_embed_override`` guard — which deliberately skips the
        mixed-composition capture rung, the split decode/prefill rung and
        every captured-graph replay, because none of them has a seam for a
        per-step ``inputs_embeds``. So a duplex step is exactly one forward
        over exactly one batch, with no split available to rescue its
        composition.

        A recurrent (Mamba-2) block dispatches on
        ``n_tokens == num_rows``: one token per row is the decode path,
        anything else is the PREFILL path — for the WHOLE batch. A mixed
        seed-prefill/decode slate therefore enters the B>1 varlen prefill loop.

        This isolation is a GUARD, and its cost is unmeasured.
        ``Mamba2Block``'s varlen loop masks each row's carried state per row
        (``models/mamba2_block.py``, the ``row_init`` mask), so a mixed
        fresh/continued composition is ordinary there — this guard is not
        holding back a live refusal from that block. It is kept because the
        blast radius of being wrong is the WHOLE SLATE: a raise inside the
        step reaches ``run_forever``'s error branch, which finishes EVERY
        row — the total-outage shape §7.9.14 fixed one layer up, reachable
        through the same trigger (two duplex connections that did not open
        at the same instant, or one tool call resolving while another
        session is live). §7.9.14's ``embed_input_ids`` hook stops
        ``resolve_embed_override`` from raising; it cannot stop a kernel
        below it, and no CPU test sees that path because they run a stub
        model. Relaxing this therefore needs a GPU run, not a CPU test.

        Two compositions are safe and are deliberately still allowed, so
        this is the narrowest rule the kernel contract actually implies:

          * **Every row exactly ONE token.** The block takes its decode
            path, which applies a single-token state update per row
            against that row's own slab state — correct for a fresh row
            (zero state) and a continued one alike. So a seed prefill's
            FINAL chunk, when it is one token wide, still shares a tick
            with steady-state rows, and that is still a genuinely MIXED
            override batch served through ``embed_input_ids``.
          * **Every row a FRESH first chunk** (nothing cached for it yet).
            The B>1 varlen prefill loop only refuses ``past > 0``, so two
            connections opening in the SAME tick still prefill together.

        Only when a wide row and an already-started row must share a tick
        does one of them have to go, and it is the WIDE one that takes the
        tick: it is the row that cannot be split, and giving the tick to
        the decode rows instead would starve it forever (a session that
        gets no row keeps its deadline, so the incumbents would be due
        again on every subsequent step too).

        Ordering matches :meth:`_build_duplex_slate`'s own two sources
        (waiting before running), so a joining session's seed prefill wins
        the tick over an already-running session's injection row."""
        rows: list[tuple[Request, int]] = []
        for req in (*self.waiting, *self.running):
            if not self._duplex_due(req, now):
                continue
            row_n, _pages, _is_prefill = self._duplex_row_size(req, token_budget)
            if row_n > 0:
                rows.append((req, row_n))
        if len(rows) <= 1 or all(n == 1 for _r, n in rows):
            return None
        if all(self._duplex_row_is_fresh(r) for r, _n in rows):
            return None
        return next((r for r, n in rows if n > 1), None)

    @staticmethod
    def _duplex_row_is_fresh(req: Request) -> bool:
        """This request's next row starts at sequence position 0, i.e. it
        arrives with NOTHING cached (``past == 0`` in ``Mamba2Block``'s own
        terms — see :meth:`_duplex_wide_row_owner`).

        ``getattr``, not bare reads: minimal request stand-ins in CPU tests
        predate both fields, and they only ever carry one-token rows, which
        never reach this predicate anyway.
        """
        return (
            int(getattr(req, "prompt_consumed", 0)) == 0
            and not getattr(req, "output_token_ids", ())
            and not getattr(req, "pending_context_token_ids", ())
        )

    def _build_duplex_slate(self, now: float) -> list[tuple[Request, int]]:
        """Build a duplex-lane-ONLY slate: exactly one row per duplex request.

        Row width comes from :meth:`_duplex_row_size` — a chunked seed
        prefill row while the request is still consuming its seed prompt,
        then ``req.injection_row_width`` (``1`` for an ordinary frame
        tick, ``1 + len(pending_context_token_ids)`` when the lane has
        queued injected context). Every shape reserves pages for every
        token it will allocate, and the lane feeds no audio frame on a
        prefill or injection tick.

        Called exclusively from ``Scheduler.schedule()``'s duplex-lane
        exclusivity gate once a duplex tick is due and ready. No
        ordinary (interactive/batch) row is ever considered here — this
        mirrors ``resolve_embed_override``'s all-or-nothing-per-tick
        invariant (``forward_exec.py:194-204``) as a scheduling policy.

        Two sources of duplex-lane rows, both handled here:

          1. Already-``RUNNING`` duplex requests (``PREFILLING`` while
             the seed is still being consumed, then ``DECODING``) — one
             row each, using the exact same page-commit accounting
             (``_decode_page_commit`` / ``_can_allocate_reserved`` /
             ``_preempt_until_allocatable``) the ordinary
             decode-continuation and prefill-continuation loops use.
          2. Still-``WAITING`` duplex requests — this is the ONLY
             admission path they ever take (they are invisible to
             ``_next_waiting_candidate``). A request with seed prompt
             still to consume is admitted into ``PREFILLING``, mirroring
             ``Scheduler.schedule``'s ordinary prefill admission; one
             whose prompt is already consumed goes straight to
             ``DECODING``.

        MTP bucketing and batch/interactive priority arbitration do not
        apply — duplex requests are outside that priority split
        entirely. ``chunk_prefill`` and ``max_batched_tokens`` DO apply,
        to the seed prefill rows, so a long system prompt is chunked
        rather than served as one unbounded row — but a chunk is NOT
        "just another row shape the runtime already handles" once other
        sessions are live, which is what the wide-row invariant below
        exists for. Bounded by ``batch_cfg.max_batch`` like any other
        step (defensive; duplex session counts are expected to be small).

        Only sessions whose OWN deadline is due get a row this tick, and
        each slated session's own ``next_duplex_deadline`` is advanced by
        its own ``duplex_interval_s`` — never another session's, and never
        a session's that did not actually get a row (design doc §7.9.14).
        A step that merely checked and found nothing due advances nothing.

        **A row WIDER than one token is served ALONE** (design doc
        §7.9.18) — see :meth:`_duplex_wide_row_owner` for why that is a
        correctness invariant of this lane and not a throughput choice.
        The other due sessions keep their deadlines (nothing advances a
        deadline that did not get a row), so they are still due and are
        served on the very NEXT engine step rather than losing a frame;
        the lane's own post-step hook returns their unconsumed audio to
        the inbound queue through the ordinary prepared-but-not-stepped
        path (``DuplexLane._requeue_prepared_frame``).
        """
        # A multi-token row owns the whole tick — see
        # :meth:`_duplex_wide_row_owner`.
        solo = self._duplex_wide_row_owner(now, int(self.batch_cfg.max_batched_tokens))
        slate = self._build_duplex_slate_rows(now, solo=solo, allow_wide=True)
        if not slate and solo is not None:
            # The owner could not be allocated this tick (no page room, and
            # nothing preemptable). Serving nothing would let one blocked
            # wide row stall every other session indefinitely — those
            # sessions keep their deadlines, so they would simply be due
            # again against the same blocked row on every step. Fall back
            # to the rows that ARE safe together without it: with every
            # wide row skipped, what is left is one token per row, which is
            # the recurrent block's decode path. A row that failed to
            # allocate reserved nothing and was never removed from
            # ``waiting``, so this second pass starts from unchanged state.
            slate = self._build_duplex_slate_rows(now, solo=None, allow_wide=False)
        return slate

    def _build_duplex_slate_rows(
        self, now: float, *, solo: Request | None, allow_wide: bool
    ) -> list[tuple[Request, int]]:
        """One pass of :meth:`_build_duplex_slate`'s two-source walk.

        ``solo`` restricts the pass to a single request; ``allow_wide=False``
        skips every row wider than one token. Both exist only for the
        wide-row invariant — see :meth:`_duplex_wide_row_owner`.
        """
        bs = self.cache_cfg.block_size
        slate: list[tuple[Request, int]] = []
        slate_req_ids: set[int] = set()
        pages_committed = 0
        batch_left = int(self.batch_cfg.max_batch)
        token_budget = int(self.batch_cfg.max_batched_tokens)

        # Source 1: admit WAITING duplex requests — into PREFILLING while
        # their seed prompt still has tokens to consume, else DECODING.
        for req in [
            r for r in self.waiting if self._duplex_due(r, now) and (solo is None or r is solo)
        ]:
            if batch_left <= 0 or token_budget <= 0:
                break
            row_n, adm_pages, row_is_prefill = self._duplex_row_size(req, token_budget)
            if row_n <= 0 or (not allow_wide and row_n > 1):
                continue
            # A prefill row's page demand is its token count (ceil-divided
            # internally); a decode row's is its already-computed page count.
            demand = row_n if row_is_prefill else adm_pages * bs
            if (
                adm_pages > 0
                and not self._can_allocate_reserved(demand, pages_committed)
                and not self._preempt_until_allocatable(
                    demand,
                    slate_req_ids,
                    admitting_is_batch=False,
                    reserved_pages=pages_committed,
                )
            ):
                # No room this tick; retried on the next duplex tick.
                continue
            self._waiting_remove(req)
            set_state(req, RequestState.PREFILLING if row_is_prefill else RequestState.DECODING)
            self._running_add(req)
            if row_is_prefill and getattr(req, "timing", None) is not None:
                # Queued→prefill boundary, once-only — same stamp the
                # ordinary prefill admission makes.
                req.timing.stamp_first_scheduled_step()
            if self._metrics is not None:
                self._metrics.queue_dec()
                if row_is_prefill:
                    self._metrics.prefill_inc()
                else:
                    self._metrics.decode_inc()
            slate.append((req, row_n))
            slate_req_ids.add(req.request_id)
            pages_committed += adm_pages
            token_budget -= row_n
            batch_left -= 1

        # Source 2: every already-running duplex request gets one row —
        # a seed-prefill continuation chunk, or its steady-state row.
        for req in list(self.running):
            if batch_left <= 0 or token_budget <= 0:
                break
            if req.request_id in slate_req_ids or not self._duplex_due(req, now):
                continue
            if solo is not None and req is not solo:
                continue
            row_n, dec_pages, row_is_prefill = self._duplex_row_size(req, token_budget)
            if row_n <= 0 or (not allow_wide and row_n > 1):
                continue
            demand = row_n if row_is_prefill else dec_pages * bs
            if (
                dec_pages > 0
                and not self._can_allocate_reserved(demand, pages_committed)
                and not self._preempt_until_allocatable(
                    demand,
                    slate_req_ids | {req.request_id},
                    admitting_is_batch=False,
                    reserved_pages=pages_committed,
                )
            ):
                # No room this tick; retried on the next duplex tick.
                continue
            slate.append((req, row_n))
            slate_req_ids.add(req.request_id)
            pages_committed += dec_pages
            token_budget -= row_n
            batch_left -= 1

        slate = self._apply_tenant_quota(slate)
        # Only a session that actually got a row has its own deadline advanced.
        engine_default = float(self.batch_cfg.duplex_frame_interval_s)
        for req, _n in slate:
            # ``getattr``, not a bare call: minimal request stand-ins in
            # CPU tests predate these and must stay always-due rows.
            resolve_interval = getattr(req, "duplex_interval_s", None)
            if resolve_interval is None:
                continue
            interval = resolve_interval(engine_default)
            prev = getattr(req, "next_duplex_deadline", None)
            # A session holding UNCONSUMED real audio is already behind the
            # live microphone, and pacing it back onto the grid can never
            # work that debt off: the grid delivers exactly one frame per
            # 80 ms, which is precisely the rate a real-time client
            # produces them, so a backlog built during any stall (the seed
            # prefill, a TTS-heavy turn, a scheduling hiccup) would be
            # carried for the whole session and simply added to by the
            # next one. Leaving this session due NOW lets the engine spend
            # spare speed repaying that debt. Only already-arrived microphone
            # frames are caught up; the lane retains one frame of jitter lead.
            # Playback remains paced by the client's audio clock, and
            # ``duplex_lane_max_consecutive_ticks`` still bounds how long
            # ordinary traffic waits. Design doc §7.40.
            if getattr(req, "duplex_audio_backlog", 0) > 0:
                req.next_duplex_deadline = now
                continue
            # The grid is absolute: anchoring on the deadline just served
            # keeps a tick slated late from slipping every later deadline.
            # ``max(now, ...)`` bounds catch-up at one tick per iteration,
            # so a session that fell whole frames behind resumes on the
            # grid instead of firing its backlog. Design doc §7.15.
            if prev is None:
                req.next_duplex_deadline = now + interval
            else:
                req.next_duplex_deadline = max(now, prev + interval)
        return slate
# ---- spec_request_gate.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""A per-request acceptance gate: a request whose own drafts keep missing decodes plainly for the rest of its life.

The load valve decides per decode WIDTH from measured step costs, and learns the losing arm by running it. On an
alternating mix of short requests it never settles, so what it pays for learning exceeds what it saves. This gate asks
nothing of the clock: a request's lifetime counters (drafts proposed and accepted, ``Request.mtp_proposed`` /
``mtp_accepted``) say how many drafts a verify of THIS request has been accepting, and below the declared floor the
verify width is not earned back (a verify of ``K`` drafts costs a multiple of a plain step; an accepted draft is a
token the plain step would have needed its own step for). There is no probing and no return: the decision is a
function of the request's own tokens, so a greedy request's text does not depend on when it ran.

The floor is ``ARBI_MTP_REQUEST_GATE``, accepted drafts per verify step; ``0`` (the default) is off. The read starts
once the request has had :data:`MIN_VERIFIES` verifies, because one verify's accepted count is one draw of a bursty run.
"""

from __future__ import annotations

from typing import Any

from arbi_serve.flag_truth import path_counter

REQUEST_GATE_ROWS = path_counter("mtp_request_gate_rows")

#: Verifies a request must have had before its own acceptance is read.
MIN_VERIFIES = 4


def declines(req: Any, floor: float) -> bool:
    """Whether ``req``'s own verifies accept fewer than ``floor`` drafts each, once it has had enough of them."""
    if floor <= 0.0:
        return False
    k = int(req.sampling.mtp_k)
    proposed = getattr(req, "mtp_proposed", None)
    if k <= 0 or proposed is None:
        return False
    verifies = int(proposed) / k
    if verifies < MIN_VERIFIES:
        return False
    return int(getattr(req, "mtp_accepted", 0) or 0) / verifies < floor
# ---- spec_row_estimate.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The load valve's per-row estimate for a host drafter: tokens per step, kept fresh.

The valve prices a slate by each row's expected committed tokens per step
against the measured step-cost ratio (``SpecValveController._model_arm``).
Its default per-row figure is ``1 + K * accepted / proposed`` from the
request's lifetime counters. For the n-gram drafter that figure is wrong
twice:

* It counts only steps that verified. A row whose suffix matched nothing
  decodes one token, and so does the seed step after a miss, but the
  step-cost ratio is the mean over ALL the speculating arm's steps, misses
  included. ``1 + K * rate`` therefore overstates tokens per step by the
  miss share, and the valve speculates on chat it is losing on.
* It is frozen while the row does not speculate. A stood-down row verifies
  nothing, so a request that starts copying (an agent quoting a file it was
  composing around) stays priced by the stretch that stood it down until a
  probe reopens the whole width.

A host drafter proposes from committed ids alone, so both are cheap to fix.
Each row keeps an EMA of accepted drafts per step: a verify contributes its
accepted count, a step without one contributes 0. A stood-down row keeps
measuring itself with SHADOW drafts: the lookup it would have verified is
scored against the tokens the row then commits. Under the rejection sampler
a point-mass draft ``d`` is accepted with probability ``p(d)``, the same
probability plain sampling commits ``d``, so the shadow's matched prefix has
the distribution of the verify's accepted count. The plain steps a shadow
spans are the ones its verify would have replaced, so it is one observation.

On a slate of two rows or more the valve then uses ``1 + EMA`` for the row
in its slate model, and on a speculating slate stands down, row by row, a
row whose own estimate is below the step-cost ratio (with hysteresis) --
never every row, since whether the slate speculates is the valve's call. A stood-down n-gram row loses
no drafter state; it rejoins when its shadow says the copy is back.

The estimate rides the request (``req.mtp_row_est``), so it lives and dies
with it and a drafter swapped out mid-serve leaves nothing behind that the
next drafter's rows could be priced by. Rank 0 only, host only.
``ARBI_MTP_SPEC_ROW_ESTIMATE`` (default ON) is fresh-read per step; off, the
valve prices every row from its lifetime counters and stands down whole
slates only, as before.
"""

from __future__ import annotations

from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any

from arbi_serve.flag_truth import FiringWindow, path_counter

#: EMA weight of one step's observation. A row switches between copying and
#: composing within a few dozen tokens; ~7 observations is the window.
ROW_EMA_ALPHA = 0.15
#: Observations before the estimate replaces the lifetime-counter figure.
ROW_MIN_OBS = 4
#: Relative band around the step-cost ratio: a row on a speculating slate
#: stands down below ``ratio * (1 - band)`` and rejoins above ``ratio``.
ROW_BAND = 0.05

#: Narrowest slate the estimate prices. At width 1 the slate model keeps the
#: lifetime figure: the console A/B on Flint + n-gram measured the per-step
#: estimate taking chat at c=1 plain where speculating won, and at width 1
#: there is no row to admit beside another, so nothing else is lost.
ROW_MIN_WIDTH = 2

#: Fired per shadow observation and per row stood down on its own estimate.
ROW_ESTIMATE = path_counter("mtp_spec_row_estimate", FiringWindow.SERVE, counted=True)


@dataclass(slots=True)
class RowEstimate:
    """One request's accepted-drafts-per-step EMA and its pending shadow draft."""

    value: float = 0.0
    n: int = 0
    #: Stood down on its own estimate (the hysteresis state of :meth:`keeps`).
    out: bool = False
    #: The valve zeroed this row's ``mtp_k`` for the step now running.
    stood_down: bool = False
    sh_pos: int = -1
    sh_draft: list[int] | None = None

    def observe(self, accepted: int) -> None:
        """One step's accepted drafts (0 for a step that verified nothing)."""
        x = float(accepted)
        self.value = x if self.n == 0 else self.value + ROW_EMA_ALPHA * (x - self.value)
        self.n += 1

    def tau(self) -> float | None:
        """Expected committed tokens per step, or ``None`` until measured."""
        return 1.0 + self.value if self.n >= ROW_MIN_OBS else None

    def keeps(self, ratio: float) -> bool:
        """Whether this row, on a speculating slate, keeps speculating at ``ratio``."""
        tau = self.tau()
        if tau is None or ratio <= 0.0:
            return True
        self.out = tau < ratio if self.out else tau < ratio * (1.0 - ROW_BAND)
        return not self.out

    def set_shadow(self, pos: int, draft: list[int]) -> None:
        """Hold ``draft`` (proposed at history length ``pos``) for scoring."""
        self.sh_pos, self.sh_draft = int(pos), list(draft)

    def score_shadow(self, history: Sequence[int], length: int) -> None:
        """Resolve the pending shadow against committed ``history[:length]``.

        Resolved at the first mismatch or once every drafted position is
        committed; until then it waits for the tokens still in flight.
        """
        draft, pos = self.sh_draft, self.sh_pos
        if draft is None:
            return
        avail = length - pos
        if avail <= 0:
            return
        span = min(len(draft), avail)
        j = 0
        while j < span and int(history[pos + j]) == draft[j]:
            j += 1
        if j < span or avail >= len(draft):
            self.sh_draft = None
            self.observe(j)
            ROW_ESTIMATE.fire_n(1)


_ENABLED: tuple[object, bool] = (None, False)


def enabled() -> bool:
    """``ARBI_MTP_SPEC_ROW_ESTIMATE``, read once per flags snapshot (frozen, replaced on an override)."""
    global _ENABLED
    from arbi_serve.runtime_flags import runtime_flags

    flags = runtime_flags()
    if _ENABLED[0] is not flags:
        _ENABLED = (flags, bool(flags.mtp_spec_row_estimate))
    return _ENABLED[1]


def estimate_of(req: Any, *, create: bool = False) -> RowEstimate | None:
    """``req``'s row estimate; made on first use when ``create``."""
    est = getattr(req, "mtp_row_est", None)
    if est is None and create:
        est = RowEstimate()
        req.mtp_row_est = est
    return est


def row_tau(req: Any, k: int, min_proposed: int, width: int) -> float | None:
    """Expected tokens per step for ``req`` at draft depth ``k``, or ``None`` (learning).

    On a slate of ``width`` at least :data:`ROW_MIN_WIDTH`, the row's own
    step-level estimate when a host drafter tracks it; else
    ``1 + k * accepted / proposed`` from the request's lifetime counters once
    ``min_proposed`` drafts have been verified.
    """
    est = getattr(req, "mtp_row_est", None)
    if est is not None and width >= ROW_MIN_WIDTH and enabled():
        return est.tau()
    proposed = int(getattr(req, "mtp_proposed", 0) or 0)
    if proposed < min_proposed:
        return None
    return 1.0 + k * int(getattr(req, "mtp_accepted", 0) or 0) / proposed
# ---- spec_valve.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The speculation load valve: mode resolution + the runtime-adaptive controller.

The valve decides, per decode step, whether the MTP-opted rows draft or
run a plain decode. It is a tri-state knob:

``off``
    Never disable. Every opted row always speculates.
``on``
    Disable at a pinned decode batch the operator chose. A bare ``on``
    with no number takes the architecture fallback
    (:func:`arch_fallback_batch`).
``auto``
    Decided from live measurement by :class:`SpecValveController`.

``auto`` compares the two arms on the quantity the trade is actually
about — committed tokens per second at the current decode width — by
running each arm in phases and keeping a per-width estimate of both. It
needs no accept rate, no model-topology guess and no cached number from a
synthetic sweep: the drafter's payoff is whatever it measures on the
traffic the server is serving.

The counterfactual arm is the signal that disappears once a decision is
made, so the controller re-probes it: on a cadence that stretches as the
verdict becomes more decisive, and sooner when the arm it CAN still see
moves outside its own band — what a workload change looks like from the
surviving arm. A probe runs the arm the valve did not choose, so it has a
price; the cadence floor is what bounds it, at one phase in
``PROBE_PHASES_MIN + 1`` whatever the traffic does.

Stopping is not the mirror of starting. A width that stops speculating
also stops observing the arm it stopped, so a stop taken on one thin
measurement outlives that measurement by however long the probe cadence
takes to contradict it — while the cadence STRETCHES with how decisive the
wrong verdict looks. So a stop needs both arms sampled enough for a median
to mean something and needs consecutive probes to agree, and a resume
needs one probe to disagree.

A dense verifier
----------------

The gate (``mtp_bucketing``) speculates on a dense verifier without driving
this controller only where measurement already covers it: the slate's cell
has a measured speculating/plain step-cost ratio and every row with a read of
its own commits more than that per step (``dense_prior_refuted``). An unpriced
cell, or a row that could lose, is decided here.

A slate the prior covers is not sent here because this controller decides per
cell, from the cell's recent requests, and a drafter with no shadow pass
(``spec_shadow``: DFlash) learns a new row in a losing cell in a budgeted window
that reads the row's counters right after a switch. A cell taught by losing
requests holds the next winning ones plain, and a drafter that re-seeds on
resume (DFlash after a plain stretch longer than its backlog or carrying a
prefill row) reads every winner as a loser
(``tests/test_spec_valve_dense_dflash.py``). A dense row that clears the
measured step-cost ratio cannot lose by speculating, so it is exposed to
neither.

``auto`` is a TRACKER, not an optimum. Its ceiling is the better fixed arm
minus what the probes cost, so an operator who has measured their own
deployment beats it by pinning ``off`` or a batch. What it buys is never
being catastrophically wrong on a deployment nobody measured — which is
the failure a single shipped constant produces."""

from __future__ import annotations

import logging
import time
from bisect import insort
from dataclasses import dataclass, field
from statistics import median

from arbi_serve.engine.request import n_generated
from arbi_serve.mser import warmup_cut
from arbi_serve.scheduler import spec_valve_learn as _learn
from arbi_serve.scheduler import spec_valve_shadow as _shadow
from arbi_serve.scheduler.spec_row_estimate import row_tau
from arbi_serve.scheduler.spec_valve_cells import (  # noqa: F401 -- re-exported
    CONTEXT_BANDS,
    cell_band,
    cell_key,
    cell_label,
    cell_width,
    context_band,
    seed_from_neighbours,
    width_bucket,
)
from arbi_serve.scheduler.spec_valve_cost import (
    lent_price,
    sorted_settled,
    step_price,
    steps_settled,
)
from arbi_serve.scheduler.spec_valve_estimate import (  # noqa: F401 -- re-exported
    BASIS_ESTIMATED,
    BASIS_GUESS,
    BASIS_INITIAL,
    BASIS_MEASURED,
    BASIS_PRICED,
    BASIS_PRIOR,
    BASIS_SEEDED,
    DECIDE_MARGIN,
    DRIFT_MIN_SAMPLES,
    PHASE_SAMPLE_RING,
    PROBE_DECISIVE_GAIN,
    PROBE_DRIFT_REL,
    PROBE_PHASES_MAX,
    PROBE_PHASES_MIN,
    VERDICT_CONFIRMATIONS,
    VERDICT_MIN_SAMPLES,
    VERDICT_OVERLAP_FRAC,
    VERDICT_RESUME_STEP,
    WidthEstimate,
)
from arbi_serve.scheduler.spec_valve_explain import explain_arm
from arbi_serve.scheduler.spec_valve_mode import (  # noqa: F401 -- re-exported
    MIN_PINNED_BATCH,
    MODE_AUTO,
    MODE_OFF,
    MODE_ON,
    SOURCE_ARCH_FALLBACK,
    SOURCE_DEFAULT,
    SOURCE_MEASURED,
    SOURCE_OPERATOR,
    ValveSetting,
    arch_fallback_batch,
    parse_valve_flag,
)
from arbi_serve.scheduler.spec_valve_model import model_arm
from arbi_serve.scheduler.spec_valve_probe import cold_cell_waits, priced_probe_floor
from arbi_serve.scheduler.spec_valve_warm import WarmupWatch, draft_counts

logger = logging.getLogger(__name__)
#: Steps discarded at the head of every phase. A flipped arm changes the
#: executed op stream, and deferred output can commit a step's tokens one
#: admission later, so the ticks straddling a flip belong to neither arm.
PHASE_SETTLE_STEPS = 2

#: Steps scored per phase, after the settle. The decision cadence is a
#: whole phase, never a step: a valve that re-decides every step is worse
#: than either fixed choice.
PHASE_SCORED_STEPS = 10

#: Steps discarded at the head of a speculating phase that opens right
#: after a switch INTO speculation (a reopened phase). A switch destroys
#: the state only the speculating arm carries — the row's cached drafts
#: are dropped and a tap-conditioned drafter's draft-KV slot is
#: staleness-marked — so the drafter re-warms while the phase scores,
#: and the two-step flip transient above cannot cover it. The plain arm
#: carries no state a switch can destroy, so it keeps the short settle:
#: the arms need different settles, and the difference is which arm was
#: just switched into, not which is measured.
#:
#: One full scored window: the longest cold span the pinned damage model
#: exhibits (a depression spanning the whole scored window — see
#: ``test_a_corruption_outliving_the_settle_*``). A reopened phase
#: therefore scores only steps that ran on a re-warmed drafter whenever
#: the re-warm fits inside a phase; a re-warm LONGER than a phase cannot
#: be settled by scoring and needs a different fix. Reopened phases run
#: longer, and switches are rare by construction (dead band plus
#: multi-probe confirm), so the cost lands on transitions, never on the
#: resting arm.
REOPEN_SETTLE_STEPS = PHASE_SETTLE_STEPS + PHASE_SCORED_STEPS

#: Seconds a phase must also span before it scores. A step count alone is
#: not a measurement window: a speculating step commits several tokens per
#: row and a plain one commits one, so the two arms cover very different
#: wall times in the same number of steps and the faster arm's score would
#: carry several times the variance.
PHASE_MIN_SECONDS = 1.0
#: The wall-clock floor of a PROBE phase. A probe runs the arm the valve did
#: not choose -- at a batch width where speculation loses, the losing arm -- so
#: its window is the probe's whole price; the step-count floor still makes it
#: a sample.
PROBE_MIN_SECONDS = 0.5

#: Steps a phase may see at OTHER widths before it is abandoned unscored.
#: A width that keeps leaving its bucket must not pin one arm forever.
#: Counted as out-of-bucket steps rather than total span, so a phase that
#: is simply taking many fast steps to fill its measurement window is
#: never mistaken for one that cannot make progress.
PHASE_MAX_OFF_BUCKET_STEPS = 4 * (PHASE_SETTLE_STEPS + PHASE_SCORED_STEPS)


#: An admission-to-admission gap longer than this did not time a decode
#: step (an idle park, a suspend, a long prefill wave). Discarded.
MAX_STEP_S = 1.0

#: Draft tokens a row must have had verified before its OWN acceptance rate is
#: trusted by the step-cost model (:meth:`SpecValveController._model_arm`):
#: four DFlash blocks of seven, learnt inside one speculating phase.
MODEL_MIN_PROPOSED = 28

#: Verify steps a row's own read needs as well: a verify's accepted count is one draw of a
#: bursty run, so a deep drafter's read on a few verifies is a few draws however many drafts.
MODEL_MIN_VERIFIES = 4


def min_read(k: int) -> int:
    """Drafts a row's own acceptance read needs at draft depth ``k``."""
    return max(MODEL_MIN_PROPOSED, MODEL_MIN_VERIFIES * int(k))


@dataclass
class _Phase:
    """One in-flight measurement phase, anchored to a width bucket."""

    speculating: bool
    bucket: int
    probing: bool = False
    #: True when this phase runs the speculating arm immediately after the
    #: controller ran the plain arm — the switch that drops cached drafts
    #: and staleness-marks the drafter's draft-KV slot, so the phase opens
    #: cold. Scores under :data:`REOPEN_SETTLE_STEPS`, not
    #: :data:`PHASE_SETTLE_STEPS`.
    reopened: bool = False
    #: Steps scored or settled AT the anchored bucket.
    steps: int = 0
    #: Steps seen at OTHER widths since the phase opened (abandon guard).
    off_bucket: int = 0
    tokens: int = 0
    seconds: float = 0.0
    #: Steps charged to ``seconds`` (past the settle).
    scored: int = 0
    #: Request ids served when the phase first ran a step: the rows its arm was chosen for.
    rows: frozenset = frozenset()
    #: The other cell whose own arm agreed with this phase's when a band switch reached it.
    agreed: int = -1
    #: A learning window (spec_valve_learn): speculates until these rows are priced; never scored.
    learning: bool = False
    learn_rows: frozenset = frozenset()
    #: A reopened speculating phase's warm-up, watched on its verified drafts
    #: (``spec_valve_warm``); ``None`` until a step reports any.
    watch: WarmupWatch | None = None
    #: Verified drafts on the phase's scored steps.
    proposed: int = 0
    accepted: int = 0
    #: Each scored step's seconds and committed tokens, in order: what the
    #: phase's measured warm-up cut (:func:`~arbi_serve.mser.warmup_cut`) reads.
    step_s: list = field(default_factory=list)
    step_tokens: list = field(default_factory=list)
    #: A plain probe's ``step_s`` kept in ascending order as it grows (``sorted_settled``).
    sorted_s: list = field(default_factory=list)


def _past_warmup(phase: _Phase) -> tuple[float, int, int]:
    """``(seconds, tokens, steps)`` of a phase's scored steps past its measured warm-up.

    The settle and the drafter's warm-up watch drop what is known to be cold
    before scoring starts; what neither sees -- a step-cost transient such as
    an arm's first replays after a boot or a switch -- shows as a trend at the
    head of the scored series. The MSER-5 cut on seconds per committed token
    finds it from the series itself (at most half of it), so a cold head never
    becomes the arm's sample and a stationary phase loses nothing.
    """
    per_token = [dt / n for dt, n in zip(phase.step_s, phase.step_tokens, strict=True)]
    cut = warmup_cut(per_token)
    if cut <= 0:
        return phase.seconds, phase.tokens, phase.scored
    return sum(phase.step_s[cut:]), sum(phase.step_tokens[cut:]), len(phase.step_s) - cut


class SpecValveController:
    """Runtime-adaptive speculation valve.

    Runs the two arms in phases and keeps, per decode width, an estimate
    of committed tokens/sec for each. Between phases it picks the arm its
    estimates favour, holding inside a dead band so noise cannot flip it,
    and periodically spends a phase on the arm it did NOT pick so the
    comparison stays live.

    The decision is necessarily per STEP, not per request: one step runs
    one uniform verify width, so the whole slate speculates or none of it
    does. Under a mixed workload the estimates converge to the mix average
    at each width and the valve picks the better arm FOR THE MIX; the dead
    band and the phase cadence are what stop a mix straddling parity from
    oscillating.
    """

    def __init__(self, *, bootstrap_batch: int = 0, bootstrap_detail: str = "") -> None:
        #: The topology fallback batch: 0 marks a dense verifier (:meth:`dense_prior`). Every cell starts ON.
        self._bootstrap_batch = max(0, int(bootstrap_batch))
        self._bootstrap_detail = str(bootstrap_detail)
        self._widths: dict[int, WidthEstimate] = {}
        #: Smallest width holding a confirmed stop verdict, maintained at
        #: phase boundaries so the per-step read is a field access.
        self._disable_batch = 0
        self._phase: _Phase | None = None
        self._phases_since_probe = 0
        #: A drift asked for the counterfactual to be re-measured; taken at
        #: the next cadence floor rather than immediately.
        self._drift_pending = False
        #: The rows of the step now open and their generated counts, updated in place on the same rows.
        self._mark_rows: tuple = ()
        self._mark_gens: list = []
        #: Tokens the fast path credited since ``_mark_gens`` was last read: one per row per plain
        #: step, the commit a plain decode step makes; the next read takes them back off its total.
        self._mark_owed = 0
        #: Whether the open step speculates, so its close reads draft counts back.
        self._mark_drafted = False
        #: The marked rows' lifetime verify counters, ``None`` for a row without them.
        self._mark_prop: list = []
        self._mark_acc: list = []
        #: The closing step's per-row verified drafts (``None``: no read) and their totals.
        self._step_dp: list = []
        self._step_da: list = []
        self._step_read = False
        self._step_prop = 0
        self._step_acc = 0
        #: The phase row set already found to hold a row of the marked slate.
        self._held_seen: frozenset | None = None
        #: The settled plain phase a same-rows step may close and mark on the fast path, or None.
        self._fast: _Phase | None = None
        #: The opted rows of the step now open, for the step-cost model.
        self._slate: tuple = ()
        self._measured = False
        self._mark_t: float = 0.0
        self._mark_bucket: int = 0
        self._mark_pure: bool = True
        self._speculating: bool = True
        #: Rows the last ``_model_arm`` opened a learning window for (empty: none).
        self._learn_rows: frozenset = frozenset()
        #: The last ``_model_arm`` priced the slate from step costs.
        self._priced: bool = False
        #: This engine's boot-measured step price (``spec_valve_boot.BootPrice``), or None.
        self.boot_price = None
        #: The runner's device step timer (``spec_decode.step_timing.StepTimer``), or None.
        self.step_timer = None
        #: Decode width -> a plain step's measured wall seconds beyond its boot device cost.
        self._plain_host: dict[int, float] = {}
        #: The once-per-engine plain host-cost phase has been taken (measured or not).
        self._plain_host_probed: bool = False
        #: The arm the last NON-probe phase ran: what an undecided slate holds.
        self._resting: bool = True
        self._detail: str = "nothing measured yet; every cell starts speculating (initial)"

    # ── surfaced state ───────────────────────────────────────────────

    @property
    def detail(self) -> str:
        """One line naming the live reason for the current arm."""
        return self._detail

    @property
    def speculating(self) -> bool:
        """The arm the next step runs."""
        return self._speculating

    def measured(self) -> bool:
        """Whether any width holds a real two-arm comparison (latched: a width's sample rings never empty)."""
        if not self._measured:
            self._measured = any(e.ready() for e in self._widths.values())
        return self._measured

    def disable_batch(self) -> int:
        """Smallest width holding a CONFIRMED "stop speculating" verdict.

        ``0`` when no width holds one. Reported as the valve's effective
        threshold so an ``auto`` deployment surfaces the same quantity a
        pinned one does — and it is the same fact the arm choice rests on,
        not a second, looser reading of the estimates. Maintained at phase
        boundaries: this is read once per admission step.
        """
        return self._disable_batch

    def _width(self, bucket: int) -> WidthEstimate:
        """The cell's estimate, made on first use (no allocation once it exists)."""
        est = self._widths.get(bucket)
        if est is None:
            est = self._widths[bucket] = WidthEstimate()
        return est

    def dense_prior(self) -> bool:
        """True when the topology fallback is the dense verdict (``arch_fallback_batch`` 0)."""
        return self._bootstrap_batch <= 0

    def step_cost_ratio(self, opted: list) -> float:
        """Speculating over plain step time measured at ``opted``'s cell, or 0."""
        if not opted:
            return 0.0
        est = self._widths.get(cell_key(width_bucket(len(opted)), context_band(opted)))
        return est.step_cost_ratio() if est is not None else 0.0

    def note_prior(self, opted: list) -> None:
        """Record a step ``auto`` speculated on the dense prior, unmeasured; the open step is discarded."""
        self._mark_rows = ()
        if opted:
            est = self._width(cell_key(width_bucket(len(opted)), context_band(opted)))
            # A cell with nothing of its own measured is in its initial state, prior or not.
            own = est.spec_n or est.plain_n or est.spec_steps or est.plain_steps
            est.arm, est.basis = True, (BASIS_PRIOR if own else BASIS_INITIAL)
            est.prior_steps += 1

    def snapshot(self) -> dict:
        """Per-cell arm estimates (width, and context band past the first), for the admin surface."""
        rows = {
            w: {
                "spec_tok_s": round(e.spec, 2),
                "plain_tok_s": round(e.plain, 2),
                "gain": round(e.gain(), 3),
                "spec_samples": e.spec_n,
                "plain_samples": e.plain_n,
                "phases": e.phases,
                "probe_phases": e.probes,
                "switches": e.switches,
                "plain_decisions": e.plain_decisions,
                "spec_step_ms": round(median(e.spec_step_s) * 1e3, 3) if e.spec_step_s else 0.0,
                "plain_step_ms": round(median(e.plain_step_s) * 1e3, 3) if e.plain_step_s else 0.0,
                "model_gain": round(e.model_gain, 3),
                "overlap": e.overlap(),
                "stop_streak": e.stop_streak,
                "stopped": e.stopped,
                "arm": None if e.arm is None else ("speculate" if e.arm else "plain"),
                "basis": e.basis,
                "prior_steps": e.prior_steps,
                "plain_est_ms": round(e.lent[1] * 1e3, 3) if e.plain_basis else 0.0,
                "plain_basis": e.plain_basis,
                "draft_dev_ms": round(median(e.draft_dev) * 1e3, 3) if e.draft_dev else 0.0,
                "verify_dev_ms": round(median(e.verify_dev) * 1e3, 3) if e.verify_dev else 0.0,
            }
            for w, e in sorted(self._widths.items())
        }
        return {cell_label(int(k)): v for k, v in rows.items()}

    # ── per-step drive ───────────────────────────────────────────────

    def should_speculate(
        self, opted: list, *, pure_decode: bool = True, now: float | None = None
    ) -> bool:
        """Close out the step that just ran, then answer for the next one.

        ``opted`` is the MTP-opted decode slate at admission; its rows
        carry the token counts the PREVIOUS step committed, which is what
        makes the measurement free of engine plumbing. Costs one clock
        read and one pass over the slate.

        ``pure_decode`` is whether the step now opening carries ONLY decode
        rows. A step that also prefills spends most of its wall clock on
        the prefill, and charging that to whichever arm happens to be
        running measures the arrival pattern instead of the drafter. Such
        steps are skipped rather than scored; the phase and the arm hold
        across them.
        """
        t = time.monotonic() if now is None else now
        rows = tuple(opted)
        # The same rows as the step just closed keep their cell: the band reads the prompt, which a
        # decode row keeps (a re-prefill fold makes it a prefill row, off the slate, first).
        same = bool(rows) and rows == self._mark_rows
        if same:
            bucket = self._mark_bucket
            if self._fast is not None and self._fast_step(t, rows, pure_decode):
                return self._speculating
            self._close_step(t, bucket, self._read_same(rows))
        else:
            bucket = cell_key(width_bucket(len(rows)), context_band(rows)) if rows else 0
            self._held_seen = None
            self._close_step(t, bucket, -1)
            self._mark_gens = [n_generated(r) for r in rows]
            self._mark_owed = 0
            self._mark_drafted = False
        if not rows:
            self._mark_rows = ()
            return self._speculating
        self._slate = rows  # the model prices the rows now served
        est, phase = self._widths.get(bucket), self._phase
        # No riding another cell's arm across a band switch its verdict or cold start refuses.
        if phase is not None and bucket not in (phase.bucket, phase.agreed):
            ready = est is not None and est.ready()
            arm = self._decide(est, bucket) if ready else not self._cold_waits(bucket)
            if arm != phase.speculating and (ready or not arm):
                self._phase = None
            else:
                phase.agreed = bucket  # decided once: not re-read on every step's newer drafts
        # Nor riding past a row's shadow read: it is a new decision (spec_valve_shadow).
        if self._phase is not None and not self._phase.probing and _shadow.ripe(rows):
            self._phase = None
        # Nor riding a request that left: a slate whose every row is new is a new decision.
        left = phase is self._phase and phase is not None and not phase.probing
        left = left and est is not None and bool(phase.rows)
        if left:
            held = phase.rows
            if held is self._held_seen:
                left = False  # held a row of these same rows already
            else:
                left = not any(r.request_id in held for r in rows)
                if not left:
                    self._held_seen = held
        if left and self._decide(est, bucket) != phase.speculating:
            self._phase = None
        elif left:
            phase.rows = frozenset(r.request_id for r in rows)  # the new rows chose this arm too
        if self._phase is None:
            self._begin_phase(bucket)
        if not self._phase.rows:
            self._phase.rows = frozenset(r.request_id for r in rows)
        # Mark the ROW, not just its count. A row that FINISHES during the
        # step is gone from the next admission's slate, so a count looked up
        # there reads ``None`` and the row's tokens are dropped — while the
        # step's wall clock is still charged in full. That under-credits
        # whichever arm commits more tokens per row per step, which is
        # always the speculating one, in proportion to how often rows
        # finish. Holding the row lets the close read its FINAL count
        # whether or not it is still being served.
        # Draft counts are read back only for a speculating step (``_close_step``); a same-rows
        # read already left them current.
        if self._speculating and not (same and self._mark_drafted):
            self._mark_counts(rows)
        self._mark_drafted = self._speculating
        self._mark_rows = rows
        self._mark_t = t
        self._mark_bucket = bucket
        self._mark_pure = bool(pure_decode)
        if not self._speculating:
            self._width(bucket).plain_decisions += 1
        timer = self.step_timer
        if timer is not None:
            timer.tag, timer.want = bucket, self._speculating
        ph = self._phase
        steady = not (ph.speculating or ph.probing or ph.learning) and ph.bucket == bucket
        self._fast = ph if steady and ph.steps >= PHASE_SETTLE_STEPS and ph.rows else None
        return self._speculating

    def _read_same(self, rows: tuple) -> int:
        """Advance the marks of the same rows to their counts now in one pass; the tokens they committed.

        Net of what the fast path already credited since the marks were read (``_mark_owed``).
        """
        gens, committed = self._mark_gens, -self._mark_owed
        self._mark_owed = 0
        if not self._mark_drafted:
            for i, r in enumerate(rows):
                a = n_generated(r)
                if a > gens[i]:
                    committed += a - gens[i]
                gens[i] = a
            return committed
        props, accs, dps, das = self._mark_prop, self._mark_acc, self._step_dp, self._step_da
        prop = acc = 0
        for i, r in enumerate(rows):
            a = n_generated(r)
            if a > gens[i]:
                committed += a - gens[i]
            gens[i] = a
            p1 = getattr(r, "mtp_proposed", None)
            p0 = props[i]
            if p1 is None:
                props[i] = dps[i] = None
                continue
            p1, a1 = int(p1 or 0), int(getattr(r, "mtp_accepted", 0) or 0)
            if p0 is None:
                dps[i] = None
            else:
                dps[i], das[i] = p1 - p0, a1 - accs[i]
                prop += p1 - p0
                acc += a1 - accs[i]
            props[i], accs[i] = p1, a1
        self._step_read, self._step_prop, self._step_acc = True, prop, acc
        return committed

    def _read_left(self, rows: tuple) -> int:
        """:meth:`_read_same` for marked rows that are no longer the slate: read them, leave the marks."""
        committed, self._mark_owed = -self._mark_owed, 0
        for r, b in zip(rows, self._mark_gens, strict=True):
            a = n_generated(r)
            if a > b:
                committed += a - b
        if self._mark_drafted:
            prop = acc = 0
            dps, das = self._step_dp, self._step_da
            for i, (r, p0) in enumerate(zip(rows, self._mark_prop, strict=True)):
                c1 = draft_counts(r)
                if c1 is None or p0 is None:
                    dps[i] = None
                    continue
                dps[i], das[i] = c1[0] - p0, c1[1] - self._mark_acc[i]
                prop += dps[i]
                acc += das[i]
            self._step_read, self._step_prop, self._step_acc = True, prop, acc
        return committed

    def _mark_counts(self, rows: tuple) -> None:
        """Read the rows' verify counters into fresh marks (a new slate, or a switch into speculation)."""
        counts = [draft_counts(r) for r in rows]
        self._mark_prop = [None if c is None else c[0] for c in counts]
        self._mark_acc = [0 if c is None else c[1] for c in counts]
        self._step_dp = [None] * len(rows)
        self._step_da = [0] * len(rows)

    def _fast_step(self, t: float, rows: tuple, pure_decode: bool) -> bool:
        """Close and mark a step of the same rows inside a settled plain phase; False defers to the full path.

        Every check the full path makes is either guaranteed by the state that armed ``_fast``
        (same cell, rows still held, no probe, learning or warm-up) or made here; a step that
        would end the phase, or one a shadow read waits on, takes the full path.

        No row is read. The closing step ran these same rows plain, and a plain decode step
        commits exactly one token per row it runs: a row that finishes, aborts or is preempted
        leaves the slate (so the step is not ``same``), and every other committed count belongs
        to a speculating or prefill step, which never arms ``_fast``. The step is credited
        ``len(rows)`` and the marks are left where they were; the next full read
        (:meth:`_read_same`, :meth:`_read_left`) subtracts the credit, so a step that broke that
        rule moves its difference onto the step that read, not into the arm's token count.
        """
        phase = self._fast
        if phase is not self._phase or not self._mark_pure or _shadow.ripe(rows):
            return False
        dt = t - self._mark_t
        if not 0.0 < dt <= MAX_STEP_S:
            return False  # no step, or an idle gap: not one plain step of these rows
        seconds = phase.seconds + dt
        if (
            phase.steps + 1 >= PHASE_SETTLE_STEPS + PHASE_SCORED_STEPS
            and seconds >= PHASE_MIN_SECONDS
        ):
            return False
        committed = len(rows)
        est = self._widths[phase.bucket]
        est.learn.earn(dt)
        phase.steps += 1
        phase.seconds = seconds
        phase.tokens += committed
        phase.scored += 1
        phase.step_s.append(dt)
        phase.step_tokens.append(committed)
        est.plain_steps.append(dt)
        self._mark_owed += committed
        self._slate = rows
        self._mark_rows = rows
        self._mark_drafted = False
        self._mark_t = t
        self._mark_pure = bool(pure_decode)
        self._widths[phase.bucket].plain_decisions += 1
        return True

    def _close_step(self, t: float, bucket: int, committed: int) -> None:
        """Charge the step that just ran to the open phase, or discard it.

        ``committed`` is what the marked rows committed when :meth:`_read_same` read them, else -1.
        """
        rows, self._mark_rows = self._mark_rows, ()
        read, self._step_read = self._step_read, False
        timer = self.step_timer
        if timer is not None and timer.pending:
            self._note_device(timer.poll())
        phase = self._phase
        if not rows or phase is None:
            return
        if bucket != phase.bucket or self._mark_bucket != phase.bucket:
            phase.off_bucket += 1
            if phase.off_bucket > PHASE_MAX_OFF_BUCKET_STEPS:
                # The width never settled in one bucket long enough to score
                # a phase. Abandon rather than hold one arm indefinitely.
                self._phase = None
            return
        if not self._mark_pure:
            # The step that just ran also prefilled. Its wall clock is not
            # this arm's decode cost.
            return
        dt = t - self._mark_t
        if dt <= 0.0 or dt > MAX_STEP_S:
            return
        if committed < 0:
            committed = self._read_left(rows)
            read = self._step_read
            self._step_read = False
        if committed <= 0:
            # The step committed nothing this arm can be charged for.
            return
        est = self._width(phase.bucket)
        est.learn.earn(dt)
        if phase.learning:
            self._learn_step(est, phase, rows, dt, committed)
            return
        step_prop = self._step_prop if read else 0
        step_acc = self._step_acc if read else 0
        if phase.speculating and phase.reopened and (phase.watch is not None or step_prop > 0):
            # The drafter's own signal sizes the warm-up (``spec_valve_warm``).
            if phase.watch is None:
                phase.watch = WarmupWatch(
                    steady=est.steady.rate(), window=MODEL_MIN_PROPOSED, margin=DECIDE_MARGIN
                )
            if not phase.watch.observe(step_prop, step_acc):
                return
            settle = 0
        else:
            settle = (
                REOPEN_SETTLE_STEPS
                if (phase.speculating and phase.reopened)
                else PHASE_SETTLE_STEPS
            )
        phase.steps += 1
        if phase.steps <= settle:
            return
        if phase.speculating:
            if read:
                dps, das = self._step_dp, self._step_da
                for i, row in enumerate(rows):
                    if dps[i] is not None:
                        est.steady.record_row(row.request_id, dps[i], das[i])
            phase.proposed += step_prop
            phase.accepted += step_acc
        phase.seconds += dt
        phase.tokens += committed
        phase.scored += 1
        phase.step_s.append(dt)
        phase.step_tokens.append(committed)
        (est.spec_steps if phase.speculating else est.plain_steps).append(dt)
        # A plain probe ends once its own steps price the plain step.
        sized = False
        if phase.probing and not phase.speculating:
            insort(phase.sorted_s, dt)
            sized = sorted_settled(phase.sorted_s)
        min_s = PROBE_MIN_SECONDS if phase.probing else PHASE_MIN_SECONDS
        if sized or (phase.steps >= settle + PHASE_SCORED_STEPS and phase.seconds >= min_s):
            self._end_phase(phase)
            self._begin_phase(phase.bucket)

    def _note_device(self, part: tuple | None) -> None:
        """File one finished ``(cell, drafter_s, verify_s)`` device read into its cell."""
        if part is None:
            return
        est = self._widths.get(part[0])
        if est is not None:
            est.draft_dev.append(part[1])
            est.verify_dev.append(part[2])

    def _learn_step(
        self, est: WidthEstimate, phase: _Phase, rows: tuple, dt: float, n: int
    ) -> None:
        """Charge one learning-window step and close the window once its rows are decided."""
        marks = {r.request_id: r for r in rows}
        plain = median(est.plain_step_s) if est.plain_step_s else 0.0
        est.learn.charge(_learn.step_loss_s(dt, n, len(marks), plain))
        ratio, open_rows = est.step_cost_ratio(), []
        for rid in phase.learn_rows:
            if rid in marks:
                req = marks[rid]
                k = int(req.sampling.mtp_k or 0)
                tau = row_tau(req, k, min_read(k), len(marks))
                if not _learn.row_decided(est.row_taus, req, tau, ratio, DECIDE_MARGIN):
                    open_rows.append(rid)
        if not open_rows or est.learn.overdrawn():
            self._phase = None  # the next admission prices the rows on the drafts just verified

    # ── phase lifecycle ──────────────────────────────────────────────

    def _begin_phase(self, bucket: int) -> None:
        est = self._width(bucket)
        favoured = self._decide(est, bucket)
        learn = self._learn_rows
        arm, probing = self._pick_arm(est, favoured, bucket)
        learning = bool(learn) and arm and not probing
        # ``self._speculating`` still holds the arm the previous phase ran
        # (it is overwritten below), so a speculating phase that differs
        # from it opened right after a switch into speculation — the
        # transition that leaves the drafter cold. A cell with no warm
        # speculating step yet is cold too, its first phase included: its
        # steps price nothing until the drafter's own acceptance says warm.
        reopened = bool(arm) and bool(arm != self._speculating or not est.spec_steps)
        est.switches += arm != self._speculating
        self._speculating = arm
        if not (probing or learning):
            self._resting = arm
        self._phase = _Phase(speculating=arm, bucket=bucket, probing=probing, reopened=reopened)
        if learning:
            self._phase.learning, self._phase.learn_rows = True, learn
        self._explain(est, bucket, probing)

    def _pick_arm(self, est: WidthEstimate, favoured: bool, bucket: int) -> tuple[bool, bool]:
        """Which arm this phase runs, and whether that is a probe.

        An arm with no samples must be sampled or the comparison never
        comes into existence — so bootstrapping a width is itself a probe,
        and it is the ONLY way ``auto`` ever escapes its starting guess.
        With both arms present the probe falls back to the cadence (a cold cell in a losing band: cold_cell_waits).
        """
        waits = est.spec_n == 0 and self._cold_waits(bucket)
        if est.spec_n == 0 and est.plain_n == 0:
            # Nothing known at all: run the starting arm first, and let the
            # next phase go and fetch its counterfactual.
            return favoured and not waits, False
        if self._estimating(bucket) and not self._plain_host_probed and est.spec_n:
            self._plain_host_probed = True
            return False, True  # once per engine: a plain phase measures the plain step's host cost
        if self._priced:
            pass  # the step-cost model priced this slate (own or lent prices): no arm needs fetching
        elif self._estimating(bucket):
            pass  # the plain step is estimated from the speculating one: no arm is fetched by a probe
        elif est.spec_n == 0:
            return (False, False) if waits else (True, True)
        elif est.plain_n == 0:
            return False, True
        if self._probe_due(est, bucket):
            # Spend the phase on the arm NOT in use — the one whose estimate
            # is going stale. Not "not favoured": when the verdict has just
            # flipped those differ, and it is the unobserved arm that needs
            # refreshing, not the one that was measured a phase ago.
            return (not self._speculating), True
        return favoured, False

    def _cold_waits(self, bucket: int) -> bool:
        return cold_cell_waits(self._widths, bucket, self._phases_since_probe, margin=DECIDE_MARGIN, floor=PROBE_PHASES_MIN, ceiling=PROBE_PHASES_MAX)  # fmt: skip

    def _end_phase(self, phase: _Phase) -> None:
        est = self._width(phase.bucket)
        seconds, tokens, scored = _past_warmup(phase)
        if seconds > 0.0 and tokens > 0:
            est.observe(speculating=phase.speculating, tok_s=tokens / seconds)
            if phase.speculating:
                est.steady.record_phase(phase.proposed, phase.accepted)
                est.steady.forget_rows({getattr(r, "request_id", id(r)) for r in self._slate})
            ring = est.spec_step_s if phase.speculating else est.plain_step_s
            ring.append(seconds / max(1, scored))
            if not phase.speculating:
                self._note_plain_host(phase.bucket, seconds / max(1, scored))
        est.phases += 1
        if phase.probing:
            est.probes += 1
            self._phases_since_probe = est.since_probe = 0
            self._drift_pending = False
            # Both arms have now been measured against each other; the pair
            # the verdict rests on is re-pinned, and drift is measured from
            # here. This is also the ONLY moment a stop verdict may move:
            # the counterfactual has just been re-drawn, so this read is
            # evidence independent of the one before it.
            if est.ready():
                est.sync_reference()
                was = est.stopped
                est.confirm()
                if est.stopped != was:
                    self._refresh_disable_batch()
        else:
            self._phases_since_probe += 1
            est.since_probe += 1
            if est.ready() and est.drifted(speculating=phase.speculating):
                # The arm we CAN see moved away from the pair the verdict was
                # set on: the workload changed under us, so the stored
                # counterfactual is no longer a comparison. Requested, not
                # taken immediately — the cadence floor still applies.
                self._drift_pending, est.decisive = True, False
        self._phase = None

    def _refresh_disable_batch(self) -> None:
        """Recompute the reported threshold. Phase boundaries only."""
        stopping = [cell_width(w) for w, e in self._widths.items() if e.stopped]
        self._disable_batch = min(stopping) if stopping else 0

    def _note_plain_host(self, bucket: int, plain_s: float) -> None:
        """Keep a plain step's wall seconds beyond the boot ladder's device cost at its width."""
        boot = self.boot_price
        device = boot.plain(cell_width(bucket)) if boot is not None and boot.rungs else 0.0
        if device > 0.0:
            self._plain_host[cell_width(bucket)] = max(1e-6, plain_s - device)

    def _estimating(self, bucket: int) -> bool:
        """Whether the boot ladder prices this cell's plain step from its speculating one (no probes)."""
        boot = self.boot_price
        return boot is not None and bool(boot.rungs) and boot.covers(cell_width(bucket))

    def _probe_due(self, est: WidthEstimate, bucket: int | None = None) -> bool:
        """Whether this phase spends itself on the arm not in use.

        Never before both arms exist (there is nothing to hold against),
        then on a cadence that stretches with how decisive the verdict is.
        A pending drift shortens that cadence to
        :data:`PROBE_PHASES_MIN` but never below it: this floor is what
        BOUNDS what keeping the counterfactual alive can cost. At most one
        phase in ``PROBE_PHASES_MIN + 1`` runs the arm the valve did not
        choose, whatever the traffic does.

        Three things take the cadence to a floor, all of them cases where
        the stored counterfactual is not something to ride: a pending drift,
        a width whose arms are not yet both sampled enough to return a
        verdict at all, and a width whose live read disagrees with its
        standing verdict. A drift takes :data:`PROBE_PHASES_MIN`. The other
        two take it PRICED (:func:`priced_probe_floor`, at most ``PROBE_COST_BUDGET``
        of decode time), counted in the cell's own phases (``since_probe``).
        """
        if not est.ready() or (bucket is not None and self._estimating(bucket)):
            return False
        if steps_settled(est.plain_steps) and self._speculating and est.model_gain > 0.0:
            return False  # the plain step is priced and the rows' own drafts price the slate
        priced_spec = step_price(est.spec_steps) or est.lent[0]
        if priced_spec and not self._speculating and 0.0 < est.model_gain < 1.0 - DECIDE_MARGIN:
            return (
                False  # the speculating step is priced and the rows' own drafts read a clear loss
            )
        margin = min(1.0, abs(est.gain() - 1.0) / PROBE_DECISIVE_GAIN)
        cadence = PROBE_PHASES_MIN + int((PROBE_PHASES_MAX - PROBE_PHASES_MIN) * margin)
        if self._drift_pending:
            cadence = PROBE_PHASES_MIN
        elif not est.settled() or est.stop_reads() != est.stopped:
            # The floor, priced: a decisive loss stretches it (spec_valve_probe).
            cadence = priced_probe_floor(est.gain(), floor=PROBE_PHASES_MIN, ceiling=cadence)
        return est.since_probe >= cadence

    def _decide(self, est: WidthEstimate, bucket: int) -> bool:
        """The arm this width runs between probes.

        A CONFIRMED stop (the fact :meth:`disable_batch` reports) runs plain.
        Short of one, the width runs the arm its evidence favours: speculating
        unless the median gain reads a loss past the dead band. Waiting for a
        confirmed verdict before leaving a losing arm cost every short burst
        the whole confirmation window -- three samples a side plus two
        agreeing probes at the probe cadence, tens of seconds -- on the arm it
        had already measured losing. The
        verdict machinery still decides what is REPORTED and how often the
        other arm is re-probed; it no longer holds the server on a measured
        loss while it accumulates.

        A width with nothing measured starts from its neighbours
        (:func:`seed_from_neighbours`), and failing that speculates
        (:data:`BASIS_INITIAL`).
        """
        arm, est.basis = self._decide_from(est, bucket)
        est.arm = arm
        return arm

    def _decide_from(self, est: WidthEstimate, bucket: int) -> tuple[bool, str]:
        """``(arm, basis)``: the arm :meth:`_decide` returns and the evidence it rests on."""
        self._lend(est, bucket)
        model = self._model_arm(est)
        if model is not None:
            return model, BASIS_PRICED
        if not est.ready():
            seeded = seed_from_neighbours(self._widths, bucket, DECIDE_MARGIN)
            if seeded is not None:
                return seeded, BASIS_SEEDED
            return True, BASIS_INITIAL  # nothing measured here or at a bounding width: start ON
        if est.stopped:
            return False, BASIS_MEASURED
        return not (0.0 < est.gain() < 1.0 - DECIDE_MARGIN), BASIS_MEASURED

    def _lend(self, est: WidthEstimate, bucket: int) -> None:
        """Price an arm this cell has not stepped: its plain step from its speculating one, else the band's other widths."""
        band, width = cell_band(bucket), cell_width(bucket)
        peers = [
            (cell_width(k), e)
            for k, e in self._widths.items()
            if k != bucket and cell_band(k) == band
        ]
        plain = lent_price([(w, step_price(e.plain_steps)) for w, e in peers], width)
        spec = lent_price([(w, step_price(e.spec_steps)) for w, e in peers], width)
        boot, est.plain_basis = self.boot_price, ""
        est.laddered = self._estimating(bucket)
        own_spec = step_price(est.spec_steps)
        if own_spec and self._estimating(bucket) and not step_price(est.plain_steps):
            parts = (
                (median(est.draft_dev), median(est.verify_dev)) if est.verify_dev else (0.0, 0.0)
            )
            host = lent_price(list(self._plain_host.items()), width)
            guess = boot.plain_estimate(width, own_spec, parts, host)
            if guess > 0.0:
                plain, est.plain_basis = guess, BASIS_ESTIMATED
        if not spec and band == 0 and boot is not None:
            # No warm speculating step in the band: the boot sweep's measured price at this width.
            plain = plain or boot.plain(width)
            spec = boot.spec(width, step_price(est.plain_steps) or plain)
        est.lent = (spec, plain)

    def _model_arm(self, est: WidthEstimate) -> bool | None:
        return model_arm(self, est)

    def _explain(self, est: WidthEstimate, bucket: int, probing: bool) -> None:
        self._detail = explain_arm(self, est, bucket, probing)
# ---- spec_valve_boot.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The speculating step's price as the MTP boot sweep measured it on this card.

A cell that has not stepped the speculating arm warm has no price of its own
for it (``SpecValveController._lend``). The boot sweep timed each draft depth
on this card: ``results[k]`` committed tokens/s at ``accept_len[k]`` tokens per
step, so one step at depth ``k`` takes ``accept_len[k] / results[k]`` seconds
and a plain step ``1 / results[0]``. The cell borrows the RATIO, applied to its
own plain step where it has one: the sweep ran short prompts, the cell may not.
The price belongs to the engine whose sweep or calibration record measured it.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from arbi_serve.scheduler.spec_valve_cost import lent_price

__all__ = [
    "BootPrice",
    "BootRung",
    "boot_price_from_record",
    "ladder_price",
    "publish_boot_price",
    "publish_ladder_price",
]


@dataclass(frozen=True)
class BootRung:
    """Device seconds the boot ladder replayed at one decode width: plain, verify (B*(K+1)) and drafter."""

    width: int
    plain_s: float
    verify_s: float
    draft_s: float

    @property
    def spec_s(self) -> float:
        """One speculating step's device seconds: drafter plus verify."""
        return self.draft_s + self.verify_s


@dataclass(frozen=True)
class BootPrice:
    """The boot-measured speculating/plain step price: one swept width, or a ladder of rungs."""

    ratio: float
    plain_s: float
    width: int
    rungs: tuple = ()
    #: The draft depth the ladder's verify graphs ran at (0: a sweep record's single width).
    k: int = 0

    def _lent(self, width: int, value) -> float:
        """``value(rung)`` at ``width``, linear between rungs; 0 outside the ladder."""
        rungs = self.rungs
        if not rungs or not rungs[0].width <= int(width) <= rungs[-1].width:
            return 0.0
        return lent_price([(r.width, value(r)) for r in rungs], int(width))

    def covers(self, width: int) -> bool:
        """Whether a step at ``width`` has a boot price (the swept width, or inside the ladder)."""
        if self.rungs:
            return self.rungs[0].width <= int(width) <= self.rungs[-1].width
        return int(width) == self.width

    def ratio_at(self, width: int) -> float:
        """Speculating over plain step time at ``width``, or 0."""
        if self.rungs:
            return self._lent(width, lambda r: r.spec_s / r.plain_s)
        return self.ratio if int(width) == self.width else 0.0

    def target_ratio(self, width: int) -> float:
        """Target forward at B over target forward at B*(K+1) tokens at ``width``, or 0 (no ladder)."""
        return self._lent(width, lambda r: r.plain_s / r.verify_s)

    def device(self, width: int) -> tuple[float, float]:
        """``(spec_s, plain_s)`` device seconds the ladder replayed at ``width``, or zeros."""
        if not self.rungs:
            return 0.0, 0.0
        return self._lent(width, lambda r: r.spec_s), self._lent(width, lambda r: r.plain_s)

    def plain(self, width: int) -> float:
        """The boot plain step at ``width``, or 0."""
        if self.rungs:
            return self._lent(width, lambda r: r.plain_s)
        return self.plain_s if int(width) == self.width else 0.0

    def spec(self, width: int, plain_s: float) -> float:
        """A speculating step at ``width``: the ratio times ``plain_s`` (else the boot plain step), or 0."""
        ratio = self.ratio_at(width)
        return ratio * (plain_s if plain_s > 0.0 else self.plain(width)) if ratio else 0.0

    def plain_estimate(
        self, width: int, spec_wall_s: float, parts: tuple[float, float], host_s: float = 0.0
    ) -> float:
        """A plain step's wall seconds at ``width`` from a speculating step's, or 0.

        ``parts`` is the live ``(drafter, verify)`` device seconds of such steps (zeros: none).
        ``host_s`` is the engine's measured plain host seconds (0: none yet); with it the
        plain step is its device cost plus that, never the speculating step's own host time.
        """
        if spec_wall_s <= 0.0 or not self.covers(width):
            return 0.0
        draft_s, verify_s = parts
        target = self.target_ratio(width)
        if host_s > 0.0:
            device = verify_s * target if verify_s > 0.0 and target > 0.0 else self.plain(width)
            return device + host_s if device > 0.0 else 0.0
        if verify_s > 0.0 and target > 0.0:
            return max(verify_s * target, spec_wall_s - draft_s - verify_s + verify_s * target)
        spec_dev, plain_dev = self.device(width)
        if spec_dev > 0.0 and plain_dev > 0.0:
            return max(plain_dev, spec_wall_s - spec_dev + plain_dev)
        ratio = self.ratio_at(width)
        return spec_wall_s / ratio if ratio > 0.0 else 0.0

    def line(self) -> str:
        """The per-rung ratios as the boot log prints them."""
        return " ".join(
            f"B{r.width}:spec/plain={r.spec_s / r.plain_s:.3f},plain/verify={r.plain_s / r.verify_s:.3f}"
            for r in self.rungs
        )


def ladder_price(rungs: list[BootRung], k: int = 0) -> BootPrice | None:
    """A ladder BootPrice at draft depth ``k`` from the rungs with positive times, or None."""
    good = tuple(
        sorted((r for r in rungs if min(r.plain_s, r.verify_s) > 0.0), key=lambda r: r.width)
    )
    if not good:
        return None
    first = good[0]
    return BootPrice(first.spec_s / first.plain_s, first.plain_s, first.width, good, int(k))


def boot_price_from_record(record: dict[str, Any], k: int) -> BootPrice | None:
    """The step prices at depth ``k`` from a boot-sweep record (a fresh sweep or the k-calibration cache)."""
    results = {int(a): float(b) for a, b in (record.get("results") or {}).items()}
    measurement = record.get("measurement") or {}
    accept = {int(a): float(b) for a, b in (measurement.get("accept_len") or {}).items()}
    plain_tok_s, spec_tok_s, per_step = results.get(0, 0.0), results.get(k, 0.0), accept.get(k, 0.0)
    if k <= 0 or plain_tok_s <= 0.0 or spec_tok_s <= 0.0 or per_step <= 0.0:
        return None
    plain_s, spec_s = 1.0 / plain_tok_s, per_step / spec_tok_s
    # The sweep submits its prompts at once; the engine runs as many as its max batch.
    prompts = int(measurement.get("num_prompts") or 1)
    width = min(prompts, int(measurement.get("max_batch") or prompts))
    return BootPrice(spec_s / plain_s, plain_s, max(1, width))


def publish_boot_price(eng: Any, record: dict[str, Any], k: int) -> BootPrice | None:
    """Give ``eng``'s load valve the price its sweep or calibration record measured, unless a boot ladder timed depth ``k``."""
    price = getattr(eng, "mtp_boot_price", None)
    if price is None or not price.rungs or price.k != int(k):
        price = boot_price_from_record(record, k)
    return publish_ladder_price(eng, price)


def publish_ladder_price(eng: Any, price: BootPrice | None) -> BootPrice | None:
    """Give ``eng``'s load valve ``price``."""
    eng.mtp_boot_price = price
    bucketer = getattr(getattr(eng, "scheduler", None), "_mtp_bucketer", None)
    if bucketer is not None:
        bucketer.set_valve_boot_price(price)
    return price
# ---- spec_valve_cells.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The cells the speculation valve keeps its estimates in: a width and a context band.

Split out of :mod:`arbi_serve.scheduler.spec_valve`, which re-exports every name
here. A cell is one decode width bucket (a power of two) and one band of the
slate's longest prompt, packed into one int so the controller's per-cell maps
stay plain dicts.
"""

from __future__ import annotations

__all__ = [
    "CONTEXT_BANDS",
    "cell_band",
    "cell_key",
    "cell_label",
    "cell_width",
    "context_band",
    "seed_from_neighbours",
    "width_bucket",
]


def width_bucket(batch: int) -> int:
    """Round a decode width up to a power of two.

    Both terms of the trade move with the width, so estimates are kept per
    width; bucketing stops a busy server spreading its samples over every
    integer batch it ever ran.
    """
    b = max(1, int(batch))
    return 1 << (b - 1).bit_length()


#: Context-length bands a width's estimate is kept per, in tokens: a slate
#: whose longest row holds fewer than ``CONTEXT_BANDS[i]`` tokens of context is
#: in band ``i``, and anything longer in the last band.
CONTEXT_BANDS: tuple[int, ...] = (2048, 4096, 8192, 16384)
#: Cells per width in the integer key a (width, context band) pair packs into.
_CTX_SPAN = len(CONTEXT_BANDS) + 1


def context_band(slate: list) -> int:
    """The context band of a slate: the band of its longest prompt.

    A verify slate attends every row's whole context for each of its ``K+1``
    positions, so what a speculating step costs against a plain one moves with
    context length as well as with width -- and the drafter's own acceptance
    moves with it too. A width judged on short prompts and then served long
    ones would run the short-prompt verdict on traffic it does not describe.
    """
    # The PROMPT, not prompt + output: a request's band then holds for its
    # whole life instead of crossing an edge mid-decode and throwing away the
    # estimate it was building; the prompt is what makes a context long.
    longest = 0
    for row in slate:
        prompt = getattr(row, "prompt_token_ids", None)
        if prompt is not None:
            longest = max(longest, len(prompt))
    for i, edge in enumerate(CONTEXT_BANDS):
        if longest < edge:
            return i
    return len(CONTEXT_BANDS)


def cell_key(width: int, band: int) -> int:
    """One estimate cell: a width bucket and a context band, packed."""
    return int(width) * _CTX_SPAN + int(band)


def cell_width(key: int) -> int:
    """The width bucket of a cell key."""
    return int(key) // _CTX_SPAN


def cell_band(key: int) -> int:
    """The context band of a cell key."""
    return int(key) % _CTX_SPAN


def cell_label(key: int) -> str:
    """``"4"`` for width 4 at the shortest band, ``"4@<8192"`` beyond it."""
    w, b = cell_width(key), cell_band(key)
    if b == 0:
        return str(w)
    edge = CONTEXT_BANDS[b] if b < len(CONTEXT_BANDS) else None
    return f"{w}@<{edge}" if edge else f"{w}@>={CONTEXT_BANDS[-1]}"


def seed_from_neighbours(cells: dict, bucket: int, margin: float) -> bool | None:
    """The starting arm a measured neighbour cell implies, or ``None``.

    The verify slate is ``B*(K+1)`` rows against a ``B``-row decode, so the
    relative cost of speculating does not FALL as the width grows: a narrower
    width where it measured a loss bounds every wider one, and a wider width
    where it measured a win bounds every narrower one. Context length orders
    cells the same way (a longer context makes the verify slate relatively
    dearer and the drafter no better), so a cell is bounded by one that is
    narrower-or-equal AND shorter-or-equal, or wider-or-equal AND
    longer-or-equal. A narrower win or a wider loss says nothing about this
    cell, which then keeps the topology guess. ``cells`` maps cell keys to
    width estimates (``ready``, ``stopped``, ``gain``).
    """
    w0, b0 = cell_width(bucket), cell_band(bucket)
    for key, e in cells.items():
        w, b = cell_width(key), cell_band(key)
        bounds = w <= w0 and b <= b0 and key != bucket and e.ready()
        if bounds and (e.stopped or 0.0 < e.gain() < 1.0 - margin):
            return False
    for key, e in cells.items():
        w, b = cell_width(key), cell_band(key)
        bounds = w >= w0 and b >= b0 and key != bucket and e.ready()
        if bounds and not e.stopped and e.gain() > 1.0 + margin:
            return True
    return None
# ---- spec_valve_cost.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Interval helpers for the speculation valve's step-cost model: step-time spread and slate gain."""

from __future__ import annotations

import math
import statistics
from collections import deque
from collections.abc import Sequence

__all__ = [
    "t95",
    "STEP_MIN",
    "STEP_RING",
    "STEP_REL_HALF",
    "StepRing",
    "gain_interval",
    "lent_price",
    "step_price",
    "mean_half",
    "sorted_settled",
    "steps_settled",
]

#: Per-step times kept per arm per cell.
STEP_RING = 64
#: Steps a step-time estimate needs before its interval means anything.
STEP_MIN = 8
#: A step cost is priced when its 95% half-width is at most this fraction of its mean.
STEP_REL_HALF = 0.025

#: Two-sided 95% Student-t quantiles by degrees of freedom; past the table, 1.96.
_T95 = {
    1: 12.71, 2: 4.303, 3: 3.182, 4: 2.776, 5: 2.571, 6: 2.447, 7: 2.365, 8: 2.306,
    9: 2.262, 10: 2.228, 12: 2.179, 15: 2.131, 20: 2.086, 30: 2.042,
}  # fmt: skip


def t95(df: int) -> float:
    """Two-sided 95% Student t quantile at ``df`` degrees of freedom."""
    if df <= 0:
        return math.inf
    for k in sorted(_T95):
        if df <= k:
            return _T95[k]
    return 1.96


def mean_half(xs: Sequence[float]) -> tuple[float, float]:
    """``(mean, 95% half-width)`` of ``xs``; an infinite half-width below two values."""
    n = len(xs)
    if n == 0:
        return 0.0, math.inf
    mean = sum(xs) / n
    if n < 2:
        return mean, math.inf
    var = sum((x - mean) ** 2 for x in xs) / (n - 1)
    return mean, t95(n - 1) * math.sqrt(var / n)


def steps_settled(step_s: Sequence[float], *, rel: float = STEP_REL_HALF) -> bool:
    """Whether these step times price the step: enough of them, and a tight 95% interval on their median.

    The interval is distribution-free (order statistics), so a rare stalled step widens it by one rank, not by its size.
    """
    return len(step_s) >= STEP_MIN and sorted_settled(sorted(step_s), rel=rel)


def sorted_settled(xs: Sequence[float], *, rel: float = STEP_REL_HALF) -> bool:
    """:func:`steps_settled` on step times already in ascending order (no copy, no sort)."""
    n = len(xs)
    if n < STEP_MIN:
        return False
    reach = 1.96 * math.sqrt(n) / 2.0
    lo, hi = max(0, math.floor(n / 2.0 - reach)), min(n - 1, math.ceil(n / 2.0 + reach) - 1)
    i = n // 2
    mid = xs[i] if n % 2 else (xs[i - 1] + xs[i]) / 2  # statistics.median, bit for bit
    return mid > 0.0 and (xs[hi] - xs[lo]) / 2.0 <= rel * mid


def _rel_half(xs: Sequence[float]) -> float:
    mean, half = mean_half(xs)
    return half / mean if mean > 0.0 and math.isfinite(half) else math.inf


def gain_interval(
    rows: Sequence[tuple[float, int]],
    k: int,
    spec_step_s: Sequence[float],
    plain_step_s: Sequence[float],
) -> tuple[float, float, float]:
    """``(gain, lo, hi)``: the slate's gain over plain with a 95% interval (binomial acceptance + step-time spread)."""
    spec_mean, _ = mean_half(spec_step_s)
    plain_mean, _ = mean_half(plain_step_s)
    if not rows or spec_mean <= 0.0 or plain_mean <= 0.0:
        return 0.0, 0.0, math.inf
    ratio = spec_mean / plain_mean
    taus = [t for t, _ in rows]
    mean_tau = sum(taus) / len(taus)
    var = 0.0
    for tau, drafts in rows:
        p = min(1.0, max(0.0, (tau - 1.0) / k)) if k > 0 else 0.0
        var += (k * k * p * (1.0 - p) / drafts) if drafts > 0 else math.inf
    tau_rel = 1.96 * math.sqrt(var) / len(rows) / mean_tau if mean_tau > 0.0 else math.inf
    ratio_rel = math.hypot(_rel_half(spec_step_s), _rel_half(plain_step_s))
    gain = mean_tau / ratio
    rel = math.hypot(tau_rel, ratio_rel)
    if not math.isfinite(rel):
        return gain, 0.0, math.inf
    return gain, gain * (1.0 - rel), gain * (1.0 + rel)


class StepRing(deque):
    """A bounded ring of step times whose :func:`step_price` is computed once per change."""

    __slots__ = ("_price",)

    def __init__(self, iterable=(), maxlen: int = STEP_RING) -> None:
        super().__init__(iterable, maxlen)
        self._price: float | None = None

    def append(self, x: float) -> None:
        self._price = None
        super().append(x)

    def extend(self, xs) -> None:
        self._price = None
        super().extend(xs)

    def clear(self) -> None:
        self._price = None
        super().clear()


def step_price(steps: Sequence[float]) -> float:
    """The median single-step time once ``steps`` hold :data:`STEP_MIN` of them, else 0."""
    if isinstance(steps, StepRing):
        price = steps._price  # noqa: SLF001
        if price is None:
            price = steps._price = statistics.median(steps) if len(steps) >= STEP_MIN else 0.0  # noqa: SLF001
        return price
    return statistics.median(steps) if len(steps) >= STEP_MIN else 0.0


def lent_price(widths: Sequence[tuple[int, float]], width: int) -> float:
    """A step price at ``width`` from priced ``(width, price)`` cells of its band: linear between neighbours, flat past them."""
    pts = sorted((w, p) for w, p in widths if p > 0.0)
    if not pts:
        return 0.0
    below = [pt for pt in pts if pt[0] <= width]
    above = [pt for pt in pts if pt[0] >= width]
    if not below:
        return above[0][1]
    if not above:
        return below[-1][1]
    (w0, p0), (w1, p1) = below[-1], above[0]
    return p0 if w1 == w0 else p0 + (p1 - p0) * (width - w0) / (w1 - w0)
# ---- spec_valve_estimate.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The speculation valve's per-cell estimate of both arms, and the verdict constants it reads."""

from __future__ import annotations

from collections import deque
from dataclasses import dataclass, field
from statistics import median

from arbi_serve.scheduler import spec_valve_learn as _learn
from arbi_serve.scheduler.spec_valve_cost import STEP_RING, StepRing, step_price
from arbi_serve.scheduler.spec_valve_warm import SteadyAcceptance

__all__ = [
    "BASIS_ESTIMATED",
    "BASIS_GUESS",
    "BASIS_INITIAL",
    "BASIS_MEASURED",
    "BASIS_PRICED",
    "BASIS_PRIOR",
    "BASIS_SEEDED",
    "DECIDE_MARGIN",
    "PHASE_SAMPLE_RING",
    "DRIFT_MIN_SAMPLES",
    "VERDICT_MIN_SAMPLES",
    "VERDICT_OVERLAP_FRAC",
    "VERDICT_CONFIRMATIONS",
    "VERDICT_RESUME_STEP",
    "PROBE_PHASES_MIN",
    "PROBE_PHASES_MAX",
    "PROBE_DECISIVE_GAIN",
    "PROBE_DRIFT_REL",
    "WidthEstimate",
]

#: What a cell's arm rests on, as the admin snapshot reports it: its rows priced against measured
#: step costs, its two arms' measured tokens/sec, a measured neighbour cell, the topology guess,
#: or the dense prior the gate speculates on without measuring (``dense_prior_refuted``).
BASIS_PRICED = "priced"
BASIS_PRIOR = "dense prior, not measuring"
BASIS_MEASURED = "measured"
BASIS_SEEDED = "neighbour"
BASIS_GUESS = "topology guess"
#: A cell with nothing measured here or at a bounding width: it starts speculating.
BASIS_INITIAL = "initial"
#: A plain step price estimated from the cell's own speculating steps and the boot ladder.
BASIS_ESTIMATED = "estimated"

#: Device-timed step parts kept per cell (``spec_decode.step_timing``).
DEVICE_RING = 16

#: Relative dead band around parity. Inside it the controller holds its
#: current arm rather than flipping on measurement noise.
DECIDE_MARGIN = 0.05

#: Phase scores kept per arm. The estimate is their MEDIAN, never a
#: running average: on a live server a single phase can be distorted by
#: prefill interleaving or request churn, and an estimate that a lone
#: sample can move is an estimate the valve will chase.
PHASE_SAMPLE_RING = 5

#: Samples an arm needs before its estimate is stable enough for a drift
#: to mean anything. Below it the median still moves a whole rank per
#: sample, so every early phase would read as a workload change and the
#: valve would spend its youth probing instead of converging.
DRIFT_MIN_SAMPLES = 3

#: Samples EACH arm needs before a width may return a stop verdict at all.
#: Stopping is the decision that costs the counterfactual — once a width
#: stops speculating, the speculating arm is only refreshed on the probe
#: cadence, so a stop taken on a thin sample is a stop that survives long
#: after the draw that caused it. A median over fewer than this rests on a
#: single ordered sample and moves a whole rank per phase.
VERDICT_MIN_SAMPLES = 3

#: Phase-score pairs, one from each arm's ring, that may CONTRADICT a stop
#: verdict — pairs in which the speculating phase outscored the plain one.
#:
#: The medians alone cannot carry the verdict. Two arms whose per-phase
#: scores overlap heavily can show a median gap in either direction on any
#: given pair of rings, and the gap the valve is being asked to resolve is
#: single-digit percent against a per-phase scatter several times that. So
#: the rings are compared as SAMPLES, not as two numbers: nearly every
#: speculating phase must have scored below nearly every plain phase. That
#: is the one-sided rank test, and this fraction is its size — on full
#: rings it admits 2 contradicting pairs in 25, which interchangeable arms
#: produce about one draw in sixty; at the sample floor it rounds to
#: complete separation, one draw in twenty.
#:
#: A FRACTION rather than a count so the test keeps its size as the rings
#: fill: more samples then buy power instead of a looser threshold. Zero
#: would be safer still against a false stop and measurably worse at
#: catching a real one, which is not the trade to make — a valve that
#: cannot stop is a valve nobody needs.
#:
#: Cost is one pass over the two rings — at most ``PHASE_SAMPLE_RING**2``
#: comparisons — at a phase boundary, never on a step.
VERDICT_OVERLAP_FRAC = 0.10

#: Consecutive counterfactual PROBES whose re-read must agree before a
#: stop verdict becomes a width's standing arm.
#:
#: Sample count alone does not buy this. The arms' per-phase scores on a
#: bursty workload are wide enough that a median of three can land below
#: parity on a width where speculation genuinely wins, and widening the
#: ring only slows that draw down — the estimate is still one draw from a
#: single distribution. A probe is a FRESH draw of the counterfactual,
#: separated from the last by at least :data:`PROBE_PHASES_MIN` phases, so
#: requiring agreement across consecutive probes is the only guard whose
#: protection compounds with each one.
#:
#: Deliberately one-sided, in the direction the errors are: a stop needs
#: this many agreeing probes, a resume needs one disagreeing probe. Wrongly
#: speculating for a few phases costs the gap for those phases; wrongly
#: stopped costs it until a probe cadence that STRETCHES with the wrong
#: verdict gets around to checking.
VERDICT_CONFIRMATIONS = 2

#: How far one DISAGREEING probe walks the verdict back. The streak is a
#: bounded walk over ``[0, VERDICT_CONFIRMATIONS]``, not a run counter, so
#: this is the other half of the hysteresis: it sets how much fresh
#: evidence resuming takes, exactly as the constant above sets how much
#: stopping takes.
VERDICT_RESUME_STEP = 1

#: Phases between counterfactual probes, at the tightest cadence (a
#: verdict sitting near parity) and the loosest (a decisive one). The
#: cadence stretches with ``|gain - 1|`` so a config that clearly wins
#: pays almost nothing to keep proving it.
PROBE_PHASES_MIN = 8
PROBE_PHASES_MAX = 64

#: ``|gain - 1|`` at which the probe cadence reaches its loosest.
PROBE_DECISIVE_GAIN = 0.5

#: Relative move in the OBSERVABLE arm's ESTIMATE, since the last time
#: both arms were measured together, that asks for a probe. The
#: counterfactual cannot be watched, but a workload shift moves the arm
#: that can be, and that is the trigger. Measured against the median
#: rather than the last sample, so it takes a sustained change to fire.
#:
#: A FLOOR, not the whole test: an arm whose own phase-to-phase scatter is
#: wider than this would trip it forever on a workload that never changed,
#: which is how a speculating arm behaves when the accept rate moves. The
#: move must also clear the arm's own observed spread — see
#: :meth:`WidthEstimate.drifted`.
PROBE_DRIFT_REL = 0.25


@dataclass
class WidthEstimate:
    """Committed tokens/sec at one decode width, one estimate per arm.

    Each arm's estimate is the MEDIAN of its recent phase scores. A live
    server's phases are not equally clean — prefill interleaves, requests
    arrive and finish, the slate churns — so an estimator a single sample
    can move is one the valve will chase, spending its phases re-checking
    noise instead of serving on the arm it already knows is faster.
    """

    spec_samples: deque = field(default_factory=lambda: deque(maxlen=PHASE_SAMPLE_RING))
    plain_samples: deque = field(default_factory=lambda: deque(maxlen=PHASE_SAMPLE_RING))
    #: Seconds per STEP on each arm at this width (scored part of each phase).
    #: A step's cost depends on the width and the arm, barely on how many of
    #: its drafts were accepted, so unlike tokens/sec it carries across
    #: workloads -- which is what lets the valve price a slate it has not
    #: served yet from its rows' own acceptance (:meth:`step_cost_ratio`).
    spec_step_s: deque = field(default_factory=lambda: deque(maxlen=PHASE_SAMPLE_RING))
    plain_step_s: deque = field(default_factory=lambda: deque(maxlen=PHASE_SAMPLE_RING))
    #: Single plain step times at this cell (``spec_valve_cost.steps_settled``).
    plain_steps: deque = field(default_factory=lambda: StepRing(maxlen=STEP_RING))
    #: The cell's last priced slate had a gain interval below the dead band (cleared by a drift).
    decisive: bool = False
    #: The step-cost model's gain for the cell's last priced slate (0: none yet).
    model_gain: float = 0.0
    #: Phases that opened on the other arm than the phase before.
    switches: int = 0
    #: Admission steps this cell answered with the plain arm.
    plain_decisions: int = 0
    #: ``(spec, plain)`` step prices interpolated from this band's other widths (0: none).
    lent: tuple = (0.0, 0.0)
    #: Single speculating step times at this cell.
    spec_steps: deque = field(default_factory=lambda: StepRing(maxlen=STEP_RING))
    #: Device seconds of sampled speculating steps' drafter and verify launches (``spec_decode.step_timing``).
    draft_dev: deque = field(default_factory=lambda: deque(maxlen=DEVICE_RING))
    verify_dev: deque = field(default_factory=lambda: deque(maxlen=DEVICE_RING))
    #: What ``lent[1]`` rests on when this cell has no plain step price of its own (``BASIS_ESTIMATED``: the boot ladder).
    plain_basis: str = ""
    #: The cell's plain step is priced from the boot ladder (``SpecValveController._estimating``).
    laddered: bool = False
    #: The cell's last priced slate turned it off on a loss whose whole interval is below parity.
    off_decisive: bool = False
    #: The arm this cell last decided (``None``: never decided) and what decided it (``BASIS_*``).
    arm: bool | None = None
    basis: str = ""
    #: Admission steps this cell speculated on the dense prior, unmeasured.
    prior_steps: int = 0
    #: The two estimates as of the last phase pair measured together. The
    #: verdict rests on THIS pair, so it is what a drift is measured from.
    ref_spec: float = 0.0
    ref_plain: float = 0.0
    #: Phases scored at this width, and how many of them were probes.
    #: The sample rings are bounded, so their lengths do NOT count phases;
    #: the probe cost is this ratio and nothing else measures it.
    phases: int = 0
    probes: int = 0
    #: Consecutive probes whose re-read agreed that speculation loses here,
    #: and the verdict that becomes once it reaches
    #: :data:`VERDICT_CONFIRMATIONS`. ``stopped`` is the ONLY thing that
    #: switches speculation off at a width; a single low read is a
    #: candidate, never a verdict.
    stop_streak: int = 0
    stopped: bool = False
    #: Phases this cell ran since its own last probe: a neighbour's phases never make it due.
    since_probe: int = 0
    #: request id -> its latest priced tau, for the requests this cell priced last
    #: (:mod:`~arbi_serve.scheduler.spec_valve_rows`).
    row_taus: dict = field(default_factory=dict)
    #: Decode time this cell may still lose to learning windows (spec_valve_learn).
    learn: _learn.LearnLedger = field(default_factory=_learn.LearnLedger)
    #: Acceptance on warm speculating steps (``spec_valve_warm``): what a
    #: reopened phase warms up to, and what rows are priced on.
    steady: SteadyAcceptance = field(default_factory=SteadyAcceptance)

    @property
    def spec(self) -> float:
        return median(self.spec_samples) if self.spec_samples else 0.0

    @property
    def plain(self) -> float:
        return median(self.plain_samples) if self.plain_samples else 0.0

    @property
    def spec_n(self) -> int:
        """Samples held for the speculating arm — NOT a phase count. The
        rings are bounded; :attr:`phases` counts phases."""
        return len(self.spec_samples)

    @property
    def plain_n(self) -> int:
        """Samples held for the plain arm. See :attr:`spec_n`."""
        return len(self.plain_samples)

    def step_cost_ratio(self) -> float:
        """Speculating over plain step time: single-step medians, else prices lent by the band, else phase medians; 0 unknown."""
        spec = step_price(self.spec_steps) or self.lent[0]
        plain = step_price(self.plain_steps) or self.lent[1]
        if spec > 0.0 and plain > 0.0:
            return spec / plain
        if not self.spec_step_s or not self.plain_step_s:
            return 0.0
        plain = median(self.plain_step_s)
        return median(self.spec_step_s) / plain if plain > 0.0 else 0.0

    def ready(self) -> bool:
        """Both arms measured at least once ⇒ the comparison is real."""
        return bool(self.spec_samples) and bool(self.plain_samples)

    def gain(self) -> float:
        """Speculation's throughput relative to a plain decode. ``>1`` pays."""
        plain = self.plain
        if not self.ready() or plain <= 0.0:
            return 0.0
        return self.spec / plain

    def settled(self) -> bool:
        """Both arms carry enough samples for a median to mean something."""
        return self.spec_n >= VERDICT_MIN_SAMPLES and self.plain_n >= VERDICT_MIN_SAMPLES

    def stop_reads(self) -> bool:
        """Whether the CURRENT pair reads as "speculation loses here".

        A candidate verdict, not the verdict: it takes
        :data:`VERDICT_CONFIRMATIONS` consecutive probes agreeing on this
        before :attr:`stopped` follows. Both gates below are what keep a
        single unlucky phase from being one — enough samples that the
        median is not one draw, and a gap below parity wider than the dead
        band the arm choice already respects.
        """
        if not self.settled():
            return False
        gain = self.gain()
        if not 0.0 < gain < 1.0 - DECIDE_MARGIN:
            return False
        return self.overlap() <= int(VERDICT_OVERLAP_FRAC * self.spec_n * self.plain_n)

    def overlap(self) -> int:
        """Phase pairs that contradict a stop: speculating beat plain.

        The two rings compared as samples rather than as two medians. A
        width where speculation genuinely loses separates the rings; a
        width sitting near parity interleaves them however the medians
        happen to land.
        """
        plain = self.plain_samples
        return sum(1 for s in self.spec_samples for p in plain if s >= p)

    def rings_lose(self) -> bool:
        """The rings read a loss past the dead band AND separate, at any sample count.

        :meth:`stop_reads` without its sample floor: enough to stop new rows
        learning (a wide slate's phases are tight, and one pair already says
        it), never enough to stop.
        """
        gain = self.gain()
        if not 0.0 < gain < 1.0 - DECIDE_MARGIN:
            return False
        return self.overlap() <= int(VERDICT_OVERLAP_FRAC * self.spec_n * self.plain_n)

    def holds_stop(self) -> bool:
        """A stopped width whose MEDIANS still read a loss: hold the verdict.

        Separation of the rings (:meth:`stop_reads`) is what it takes to stop;
        once stopped, one speculating phase that overlaps the plain ring is not
        evidence that the drafter now pays while the median still says it loses.
        """
        return self.stopped and self.settled() and 0.0 < self.gain() < 1.0 - DECIDE_MARGIN

    def confirm(self) -> None:
        """Fold one counterfactual re-read into the stop verdict.

        Called at the close of a PROBE and nowhere else: only a probe has
        just re-measured the arm the width is not running, so only a probe
        is fresh evidence. The streak is a bounded walk rather than a run
        counter: an agreeing probe advances it, a disagreeing one walks it
        back by :data:`VERDICT_RESUME_STEP`. That is what makes stopping
        cost several probes and resuming cost one -- once the medians are
        back inside the dead band: a stopped width whose median gain still
        reads a loss holds its verdict through an overlapping phase.
        """
        if self.stop_reads():
            step = 1
        elif self.holds_stop():
            # A stopped width whose MEDIANS still say speculation loses holds
            # its verdict even when one lucky speculating phase overlaps the
            # plain ring. A drafter whose acceptance swings with the prompt
            # always throws such a phase sooner or later, and resuming on it
            # put the width back on a losing arm right after every stop.
            # Separation is still what it takes to STOP; the
            # median falling back inside the dead band is what it takes to
            # resume.
            step = 0
        else:
            step = -VERDICT_RESUME_STEP
        self.stop_streak = max(0, min(VERDICT_CONFIRMATIONS, self.stop_streak + step))
        self.stopped = self.stop_streak >= VERDICT_CONFIRMATIONS

    def observe(self, *, speculating: bool, tok_s: float) -> None:
        """Fold a phase score into one arm's sample ring."""
        (self.spec_samples if speculating else self.plain_samples).append(tok_s)

    def sync_reference(self) -> None:
        """Pin the pair the current verdict rests on.

        Called when both arms have just been measured against each other,
        so a later drift is measured from a comparison that was true.
        """
        self.ref_spec, self.ref_plain = self.spec, self.plain

    def drifted(self, *, speculating: bool) -> bool:
        """Whether the arm in use has moved away from the pinned pair.

        This is the only workload-change signal available once one arm is
        switched off, and it is what buys the counterfactual back — so it
        has to fire on a real change and stay quiet on the arm's own
        scatter. Two guards do that: the estimate must be old enough to
        have a shape at all, and the move must clear BOTH the fixed floor
        and the spread this arm's own recent phases already show. A
        speculating arm's throughput moves with the accept rate from one
        phase to the next; a valve that read that as a workload change
        would spend its phases re-checking noise.
        """
        ring = self.spec_samples if speculating else self.plain_samples
        if len(ring) < DRIFT_MIN_SAMPLES:
            return False
        now = self.spec if speculating else self.plain
        ref = self.ref_spec if speculating else self.ref_plain
        if ref <= 0.0 or now <= 0.0:
            return False
        move = abs(now - ref) / ref
        scatter = (max(ring) - min(ring)) / now if now > 0.0 else 0.0
        return move > PROBE_DRIFT_REL and move > scatter
# ---- spec_valve_explain.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The speculation load valve's one-line explanation of its current arm.

Split out of :mod:`arbi_serve.scheduler.spec_valve`, which calls it.
"""

from __future__ import annotations

from typing import Any

from arbi_serve.scheduler.spec_valve_cells import cell_label
from arbi_serve.scheduler.spec_valve_estimate import BASIS_SEEDED


def explain_arm(valve: Any, est: Any, bucket: int, probing: bool) -> str:
    """The one line naming the live reason for the valve's current arm."""
    from arbi_serve.scheduler.spec_valve import VERDICT_CONFIRMATIONS, VERDICT_MIN_SAMPLES

    arm = "speculating" if valve._speculating else "not speculating"
    if probing:
        return (
            f"{arm} — probing the counterfactual at width {cell_label(bucket)} "
            f"(gain {est.gain():.2f} over {est.spec_n}+{est.plain_n} samples)"
        )
    if est.ready():
        pending = ""
        if est.stop_streak and not est.stopped:
            pending = (
                f"; a stop verdict is unconfirmed at {est.stop_streak}"
                f"/{VERDICT_CONFIRMATIONS} probes"
            )
        elif not est.settled():
            pending = (
                f"; too few samples to stop on ({est.spec_n}+{est.plain_n}, "
                f"needs {VERDICT_MIN_SAMPLES} each)"
            )
        return (
            f"{arm} — measured at width {cell_label(bucket)}: {est.spec:.1f} tok/s speculating "
            f"vs {est.plain:.1f} plain (gain {est.gain():.2f}){pending}"
        )
    if est.plain_basis:
        verdict = "a decisive loss" if est.decisive else "no decisive loss"
        return (
            f"{arm} — at width {cell_label(bucket)} the plain step is estimated at "
            f"{est.lent[1] * 1e3:.2f} ms from the speculating step (boot ladder): "
            f"gain {est.model_gain:.2f}, {verdict}"
        )
    if valve._speculating:
        start = "every cell starts speculating (initial)"
    elif est.basis == BASIS_SEEDED:
        start = "held plain: a narrower width of its band measured a loss"
    else:
        start = "held plain: a cold cell of a band that reads a loss"
    return f"{arm} — nothing measured at width {cell_label(bucket)} yet; {start}"
# ---- spec_valve_learn.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Learning a new request's rate in a cell that reads a loss, priced like a probe.

The step-cost model (``SpecValveController._model_arm``) prices each row by its
own acceptance, so a row with no rate yet has to speculate for a few verifies
before it can be priced. A cell whose recent requests all lost
(:func:`~arbi_serve.scheduler.spec_valve_rows.rows_lose`), or whose first phase
pair separated (``WidthEstimate.rings_lose``), used to refuse that outright: a
new request ran plain from its first step to its last. That is right while the
traffic stays the same, and wrong the moment it changes. A cell taught by chat
held every code edit after it plain -- each request never speculated, so it was
never priced, so it never could -- until a probe priced at chat's loss came due,
which takes longer than several requests live. The traffic a cell serves next is
not the traffic that taught it.

So the refusal is priced instead of absolute. A row that has no rate yet learns
in a short LEARNING window, charged against the cell's own ledger at the measured
loss of each window step, and the ledger earns :data:`PROBE_COST_BUDGET` of the
cell's decode time -- the same share a probe may spend. A window:

* opens only once the row has generated :data:`LEARN_AFTER_TOKENS` tokens. A
  response's first tokens are not its rate: across Flint and Qwen3.8 dumps a
  chat answer's first sixteen accept far more drafts than the rest, so a window
  over them would price chat as a winner;
* closes once every row it opened for is DECIDED -- its pooled estimate
  (:func:`~arbi_serve.scheduler.spec_valve_rows.shrunk_tau`) lies below the
  dead band, or above it on at least :data:`LEARN_WIN_VERIFIES` verifies -- or
  has spent :data:`LEARN_MAX_VERIFIES` verifies. Stopping on a
  fixed draft count instead let the pooled prior, made of the losing requests
  that taught the cell, pull a winner back inside the dead band, where the cell's
  resting arm (plain) then held it for the rest of the response;
* is never scored into the phase rings: it is short and opens on a cold drafter,
  the bias the rings already carry.
"""

from __future__ import annotations

from dataclasses import dataclass

from arbi_serve.engine.request import n_generated
from arbi_serve.scheduler.spec_valve_probe import PROBE_COST_BUDGET
from arbi_serve.scheduler.spec_valve_rows import row_read, rows_lose

__all__ = [
    "LEARN_AFTER_TOKENS",
    "LEARN_CREDIT_CAP_S",
    "LEARN_MAX_VERIFIES",
    "LEARN_WIN_VERIFIES",
    "LearnLedger",
    "cap_short_reads",
    "cell_loses",
    "learners",
    "row_decided",
    "step_loss_s",
]

#: Generated tokens a row must have before it may open a learning window.
LEARN_AFTER_TOKENS = 64

#: Verifies a learning window may spend per row before it closes undecided.
LEARN_MAX_VERIFIES = 32

#: Verifies a row needs before its window may close on a WIN. A loss closes the
#: window at once; a win commits the cell to a whole speculating phase, and a
#: few verifies of a losing response read as one often enough to cost it.
LEARN_WIN_VERIFIES = 12

#: Most credit a cell banks: a long quiet stretch must not buy a burst of windows.
LEARN_CREDIT_CAP_S = 0.64


@dataclass
class LearnLedger:
    """Seconds of decode a cell may still lose to learning windows."""

    credit_s: float = 0.0

    def earn(self, dt: float) -> None:
        """Bank the budget share of ``dt`` seconds of decode served at this cell."""
        self.credit_s = min(LEARN_CREDIT_CAP_S, self.credit_s + PROBE_COST_BUDGET * max(0.0, dt))

    def charge(self, loss_s: float) -> None:
        """Spend what a learning step lost against the plain arm."""
        self.credit_s -= max(0.0, loss_s)

    def affords(self) -> bool:
        return self.credit_s > 0.0

    def overdrawn(self) -> bool:
        """A window that has spent a full cap past zero closes, decided or not."""
        return self.credit_s <= -LEARN_CREDIT_CAP_S


def _k(req) -> int:
    return int(getattr(getattr(req, "sampling", None), "mtp_k", 0) or 0)


def cell_loses(est, ratio: float, margin: float, k: int) -> bool:
    """Whether a cell's evidence reads a loss: its recent requests' long reads, or its rings."""
    return rows_lose(est.row_taus, ratio, margin, LEARN_WIN_VERIFIES * k) or est.rings_lose()


def cap_short_reads(taus: list, priced: list, k: int, ratio: float) -> list:
    """Pooled taus with any read on fewer than :data:`LEARN_WIN_VERIFIES` verifies held at parity.

    Where the cell reads a loss, a short read may say a row loses but never that
    it wins: averaged over a slate, a few verifies of each of several losing
    responses still read as a win often enough to buy a whole speculating phase.
    """
    return [
        min(t, ratio) if n < LEARN_WIN_VERIFIES * k else t
        for t, (_, _, n) in zip(taus, priced, strict=True)
    ]


def learners(slate: list, unpriced: set) -> frozenset:
    """Request ids of ``slate`` rows with no rate yet that are past their opening tokens."""
    return frozenset(
        getattr(r, "request_id", id(r))
        for r in slate
        if getattr(r, "request_id", id(r)) in unpriced and n_generated(r) >= LEARN_AFTER_TOKENS
    )


def row_decided(ring: dict, req, tau: float | None, ratio: float, margin: float) -> bool:
    """Whether a learning row's pooled estimate has left the dead band, or its window is spent."""
    k, drafts = _k(req), int(getattr(req, "mtp_proposed", 0) or 0)
    if k > 0 and drafts >= LEARN_MAX_VERIFIES * k:
        return True
    if tau is None or ratio <= 0.0:
        return False
    gain = (
        row_read(ring, getattr(req, "request_id", id(req)), tau, drafts, k, ratio, margin) / ratio
    )
    if gain > 1.0 + margin:
        return drafts >= LEARN_WIN_VERIFIES * k
    return gain < 1.0 - margin


def step_loss_s(dt: float, committed: int, width: int, plain_step_s: float) -> float:
    """What one speculating step lost against plain decode of the same tokens.

    A plain step at this width commits one token per row, so the ``committed``
    tokens would have taken ``committed / width`` plain steps. With no plain step
    time measured the whole step is charged.
    """
    if plain_step_s <= 0.0 or width <= 0:
        return max(0.0, dt)
    return max(0.0, dt - committed / width * plain_step_s)
# ---- spec_valve_mode.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The speculation valve's tri-state setting: what one flag value resolves to.

Split out of :mod:`arbi_serve.scheduler.spec_valve`, which re-exports every name
here. The runtime-adaptive controller behind ``auto`` stays there.
"""

from __future__ import annotations

from dataclasses import dataclass

__all__ = [
    "MIN_PINNED_BATCH",
    "MODE_AUTO",
    "MODE_OFF",
    "MODE_ON",
    "SOURCE_ARCH_FALLBACK",
    "SOURCE_DEFAULT",
    "SOURCE_MEASURED",
    "SOURCE_OPERATOR",
    "ValveSetting",
    "arch_fallback_batch",
    "parse_valve_flag",
    "dense_prior_refuted",
]

#: The three states an operator may set the valve to.
MODE_OFF = "off"
MODE_ON = "on"
MODE_AUTO = "auto"

#: Where a resolved value came from, reported alongside it so an
#: operator-pinned number, a topology guess and a live measurement are
#: never mistaken for one another.
SOURCE_OPERATOR = "operator"
SOURCE_MEASURED = "measured"
SOURCE_ARCH_FALLBACK = "architecture-fallback"
SOURCE_DEFAULT = "default"

#: Smallest coherent pinned batch. ``on`` means "stop speculating under
#: load", and a single decode row is not load — a threshold below this
#: would make ``on`` mean "never speculate", which is a different request
#: and not one this flag can express.
MIN_PINNED_BATCH = 2


def arch_fallback_batch(layer_specs) -> tuple[int, str]:
    """Last-resort disable batch guessed from the verifier's FFN topology.

    A GUESS, never a measurement, and labelled as one wherever it is
    surfaced. It exists to give ``auto`` a starting arm before it has
    measured anything, and to give a bare ``on`` a number. The quantity it
    stands in for is the drafter's accepted tokens per step against the
    verify step's ``K+1`` token multiplier, which
    :class:`~arbi_serve.scheduler.spec_valve.SpecValveController` measures
    directly and supersedes as soon as it holds both arms at the serving width.

    A verify step runs ``B*(K+1)`` tokens where a plain decode runs ``B``.
    On a sparse MoE each token routes to its own expert subset, so the
    verify pass multiplies the traffic that already dominates; on a dense
    model it spreads the same weight traffic over more rows of GEMM. That
    second half is a dense-bf16-GEMM argument, and a quantized verifier whose
    slate crosses a kernel-dispatch boundary the decode step sits below need
    not obey it — the returned reason states the premise, not a measurement
    of this boot.

    Returns ``(batch, reason)``; ``0`` is the dense verdict (``dense_prior_refuted``).
    """
    if any(getattr(spec, "moe", None) is not None for spec in layer_specs):
        return 2, "sparse-MoE verifier: verify-step expert traffic grows with token count"
    return 0, "dense verifier: verify-step weight traffic is independent of token count"


#: Verified drafts a row needs before its acceptance can refute the prior.
DENSE_PRIOR_MIN_PROPOSED = 28


def dense_prior_refuted(rows, ratio: float, margin: float = 0.05) -> bool:
    """Whether the dense prior does not cover these opted rows: ``ratio`` (the cell's measured
    speculating/plain step-cost ratio) is unknown (0), or a row's own ``1 + k * accepted / proposed``
    is below ``ratio * (1 + margin)``."""
    if ratio <= 0.0:
        return True
    for req in rows:
        k = int(getattr(getattr(req, "sampling", None), "mtp_k", 0) or 0)
        proposed = int(getattr(req, "mtp_proposed", 0) or 0)
        if k <= 0 or proposed < DENSE_PRIOR_MIN_PROPOSED:
            continue
        if 1.0 + k * int(getattr(req, "mtp_accepted", 0) or 0) / proposed < ratio * (1.0 + margin):
            return True
    return False


@dataclass(frozen=True)
class ValveSetting:
    """The tri-state setting one flag value resolves to.

    ``pinned`` is the batch an ``on`` mode disables at, ``0`` otherwise.
    ``source`` and ``detail`` carry the provenance.
    """

    mode: str
    pinned: int = 0
    source: str = SOURCE_DEFAULT
    detail: str = ""


def parse_valve_flag(raw, *, arch_batch: int = 0, arch_reason: str = "") -> ValveSetting:
    """Resolve ``mtp_spec_disable_batch`` into a :class:`ValveSetting`.

    Accepted: ``""`` (unset ⇒ ``auto``), ``auto``, ``off`` / ``never`` /
    ``0``, ``on`` (⇒ the architecture fallback batch), and any positive
    integer (⇒ pinned). Anything else resolves to ``off`` — never
    disabling is the safe reading of an unreadable flag — and says so.
    """
    text = str(raw or "").strip().lower()
    if not text:
        return ValveSetting(MODE_AUTO, 0, SOURCE_DEFAULT, "unset defaults to auto")
    if text == MODE_AUTO:
        return ValveSetting(MODE_AUTO, 0, SOURCE_OPERATOR, "operator selected auto")
    if text in (MODE_OFF, "never"):
        return ValveSetting(MODE_OFF, 0, SOURCE_OPERATOR, "operator selected off")
    if text == MODE_ON:
        # The fallback can say "never disable", which is not something an
        # explicit ``on`` can mean. Floor it at the smallest batch that is
        # load at all.
        return ValveSetting(
            MODE_ON,
            max(MIN_PINNED_BATCH, int(arch_batch)),
            SOURCE_ARCH_FALLBACK,
            f"on with no batch; GUESSED from topology ({arch_reason})",
        )
    try:
        n = int(text)
    except (TypeError, ValueError):
        return ValveSetting(MODE_OFF, 0, SOURCE_DEFAULT, f"unparseable {raw!r}; never disabling")
    if n <= 0:
        return ValveSetting(MODE_OFF, 0, SOURCE_OPERATOR, "operator pinned 0 (never disable)")
    return ValveSetting(MODE_ON, n, SOURCE_OPERATOR, f"operator pinned batch {n}")
# ---- spec_valve_model.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The speculation load valve's step-cost model of the slate it is serving.

Split out of :mod:`arbi_serve.scheduler.spec_valve`, whose controller calls it.
"""

from __future__ import annotations

from typing import Any

from arbi_serve.scheduler import spec_valve_learn as _learn
from arbi_serve.scheduler import spec_valve_shadow as _shadow
from arbi_serve.scheduler.spec_row_estimate import row_tau
from arbi_serve.scheduler.spec_valve_cost import STEP_MIN, gain_interval
from arbi_serve.scheduler.spec_valve_estimate import BASIS_ESTIMATED
from arbi_serve.scheduler.spec_valve_rows import note_row_taus, pooled_weight, row_read
from arbi_serve.spec_shadow import shadow_available as _shadow_available


def model_arm(valve: Any, est: Any) -> bool | None:
    """The arm the step-cost model picks for the rows now served, or ``None``.

    Tokens/sec per arm is a property of the WORKLOAD as much as of the
    width: a width whose verdict was set on a low-acceptance workload
    serves the next, higher-acceptance one on the plain arm and loses the
    win speculation would have had there. Step cost
    is not: a speculating step at width ``w`` costs ``ratio`` plain steps
    whatever was accepted, and commits ``tau`` tokens per row
    (:func:`~arbi_serve.scheduler.spec_row_estimate.row_tau`). So with both step costs measured at this width, the
    slate speculates iff its rows' own expected ``tau`` beats ``ratio``,
    outside the dead band. Inside it the cell's resting arm holds: the arm
    its last non-probe phase ran, never a probe's, which would otherwise
    outlive the probe whenever the slate reads near parity.

    A row that has not had :data:`MODEL_MIN_PROPOSED` drafts verified has
    no rate yet, so a slate holding one speculates -- that is how a new
    request learns its rate, inside one phase -- unless the cell already
    knows its rows lose (:mod:`~arbi_serve.scheduler.spec_valve_rows`). A
    slate with no rates at all, or a width with no step costs yet, returns
    ``None`` (the evidence/verdict rule decides).
    """
    from arbi_serve.scheduler.spec_valve import DECIDE_MARGIN, MODEL_MIN_PROPOSED, min_read

    valve._learn_rows = frozenset()
    valve._priced = False
    ratio = est.step_cost_ratio()
    if ratio <= 0.0 or not valve._slate:
        return None
    priced, learning, unpriced, kmax, shadowed = [], False, set(), 0, False
    cells = [est.steady] + [e.steady for e in valve._widths.values() if e is not est]
    # A row with no rate yet starts at its cell's warm rate where it can learn its own from shadow reads.
    pool, pooled = (est.steady.rate() if _shadow_available() else None), []
    for req in valve._slate:
        k = int(getattr(getattr(req, "sampling", None), "mtp_k", 0) or 0)
        if k <= 0:
            continue
        kmax = max(kmax, k)
        need = min_read(k)
        tau = row_tau(req, k, need, len(valve._slate))
        if getattr(req, "mtp_row_est", None) is None:
            # Priced on its warm steps when it has enough of them: its
            # lifetime counters carry every cold re-warm the valve caused.
            warm = est.steady.row_tau(getattr(req, "request_id", id(req)), k, need)
            tau = tau if warm is None else warm
        drafts = int(getattr(req, "mtp_proposed", 0) or 0)
        read = _shadow.shadow_read(req, k, _shadow.depth_curve(cells, k), ratio, DECIDE_MARGIN)
        if read is not None:
            # The shadow read is one more observation of the row, weighted by its positions.
            tau, drafts = _shadow.blend(read, tau, drafts)
            shadowed = shadowed or drafts == read[1]
        if tau is None and pool is not None:
            pooled.append((getattr(req, "request_id", id(req)), 1.0 + k * pool, MODEL_MIN_PROPOSED))
            continue
        if tau is None:
            learning = True
            unpriced.add(getattr(req, "request_id", id(req)))
        else:
            priced.append((getattr(req, "request_id", id(req)), tau, drafts))
    note_row_taus(est.row_taus, priced)
    _shadow.advance(valve._slate, est.learn)
    losing = _learn.cell_loses(est, ratio, DECIDE_MARGIN, kmax) or _shadow.shadow_all()
    # A laddered cell that went off on a decisive loss learns its new rows as a losing cell does.
    losing = losing or (est.laddered and est.arm is False and est.off_decisive)
    if losing and pooled:
        # A cell that reads a loss learns new rows as it always has (shadow, or a budgeted window).
        learning = True
        unpriced.update(rid for rid, _tau, _n in pooled)
    else:
        priced += pooled
    if learning:
        if not losing:
            return True
        # A losing cell measures a new row's acceptance plainly where the drafter can
        # (spec_valve_shadow); otherwise it lets the row learn by speculating, priced (spec_valve_learn).
        unpriced -= _shadow.shadow_rows(
            valve._slate, unpriced, est.learn, _learn.LEARN_AFTER_TOKENS
        )
        learn = _learn.learners(valve._slate, unpriced) if est.learn.affords() else frozenset()
        if learn:
            valve._learn_rows = learn
            return True
        if not priced:
            return False  # the cell's rows lose: a new one does not buy a phase to learn it
    if not priced:
        return None
    short = _learn.LEARN_WIN_VERIFIES * kmax
    taus = [
        row_read(est.row_taus, rid, tau, n, kmax, ratio, DECIDE_MARGIN, short)
        for rid, tau, n in priced
    ]
    if losing:
        taus = _learn.cap_short_reads(taus, priced, kmax, ratio)
    gain = (sum(taus) / len(taus)) / ratio
    # The arm follows the point estimate; the interval only decides whether a speculating probe is owed.
    drafts = [n for _rid, _tau, n in priced]
    if est.laddered:
        # A read pooled with the cell's recent requests rests on their drafts too.
        drafts = [
            n + pooled_weight(est.row_taus, rid, n, tau, kmax, ratio, short)
            for rid, tau, n in priced
        ]
    spec_s = est.spec_steps if len(est.spec_steps) >= STEP_MIN else est.spec_step_s
    plain_s = est.plain_steps if len(est.plain_steps) >= STEP_MIN else est.plain_step_s
    estimated = est.plain_basis == BASIS_ESTIMATED
    if estimated:
        # The estimate moves with the speculating step it is read from: its spread is theirs.
        plain_s = [x / ratio for x in spec_s]
    _g, lo, hi = gain_interval(list(zip(taus, drafts, strict=True)), kmax, spec_s, plain_s)
    est.decisive, est.model_gain, valve._priced = hi < 1.0 - DECIDE_MARGIN, gain, True
    if gain > 1.0 + DECIDE_MARGIN:
        # A laddered cell that left speculation on a decisive loss comes back on a decisive win.
        return not (est.laddered and est.arm is False and lo <= 1.0)
    est.off_decisive = est.laddered and hi < 1.0
    if est.off_decisive:
        # Both arms priced on measured wall time: a loss whose whole interval is below parity
        # turns the cell off; the dead band holds only the switch back on.
        return False
    if pooled and gain < 1.0 + DECIDE_MARGIN:
        # Held off the speculating arm by its cell's rate, a new row reads its own from shadow passes.
        _shadow.shadow_rows(
            valve._slate, {rid for rid, _t, _n in pooled}, est.learn, _learn.LEARN_AFTER_TOKENS
        )
    if gain < 1.0 - DECIDE_MARGIN:
        # Against an estimated plain step a cell leaves speculation only on a decisive loss.
        return estimated and not est.decisive
    # Inside the dead band a SETTLED cell holds its resting arm. An unsettled
    # one has no standing evidence to hold -- its resting arm may rest on one
    # early phase -- so it runs the arm the deployment asked for. A losing cell
    # holds plain for a row priced by its shadow read: it switches on a clear win only.
    if losing and shadowed:
        return False
    return valve._resting if est.settled() else True
# ---- spec_valve_probe.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The price of a counterfactual probe, and the probe floor it sets.

A probe spends about one phase on the arm the valve did NOT choose, and over
that phase the server commits ``1 - (probed arm / chosen arm)`` fewer tokens.
At the fixed floor of one probe per :data:`PROBE_PHASES_MIN` phases, which a
cell gathering its first samples sits on, a cell that loses decisively paid
``(1 - gain) / (PROBE_PHASES_MIN + 1)`` of its decode time: 5% at the gain of
0.55 a 64-row verify over a 4k context reads on Flint's 4090, which was that
cell's whole loss against a server without a drafter. The floor therefore
stretches until a probe costs at most :data:`PROBE_COST_BUDGET`.

Only the floor moves. The arm a cell runs follows its evidence from the first
phase pair (``SpecValveController._decide``); a stretched floor delays the
CONFIRMED verdict, which is what ``disable_batch`` reports, and the moment a
changed workload is seen by a cell that loses. A pending drift keeps the old
floor: it is evidence the workload moved, and re-measuring it is what a probe
is for.
"""

from __future__ import annotations

import math

from arbi_serve.scheduler.spec_valve_cells import cell_band

__all__ = ["PROBE_COST_BUDGET", "cold_cell_waits", "priced_probe_floor", "probe_loss"]

#: Share of decode time the floor cadence may spend on the arm not chosen.
PROBE_COST_BUDGET = 0.01


def probe_loss(gain: float) -> float:
    """Throughput a probe gives up, relative to the arm the cell runs.

    ``gain`` is speculation over plain. Below parity the cell runs plain and a
    probe speculates (``1 - gain``); above it the cell speculates and a probe
    runs plain (``1 - 1/gain``). ``0`` when nothing is measured.
    """
    if gain <= 0.0:
        return 0.0
    return 1.0 - gain if gain < 1.0 else 1.0 - 1.0 / gain


def priced_probe_floor(gain: float, *, floor: int, ceiling: int) -> int:
    """Phases between probes so a probe costs at most :data:`PROBE_COST_BUDGET`.

    One probe phase per ``n + 1`` phases costs ``loss / (n + 1)``, so ``n`` is
    ``loss / budget - 1``, held inside ``[floor, ceiling]``.
    """
    n = math.ceil(probe_loss(gain) / PROBE_COST_BUDGET) - 1
    return max(int(floor), min(int(ceiling), n))


def cold_cell_waits(
    cells: dict, bucket: int, phases_since_probe: int, *, margin: float, floor: int, ceiling: int
) -> bool:
    """Whether a cell with no speculating sample keeps the plain arm for now.

    A cell's first speculating phase fetches its counterfactual: a probe in all
    but name. A batch that ramps up and drains passes through narrower widths
    whose cells start cold, and each would buy one such phase, though a loss
    at one width does not imply a loss at another (so it cannot be SEEDED
    away). When every measured cell of the same context band reads a loss past
    the dead band, the most favourable of them prices that phase like a probe
    (:func:`priced_probe_floor`) and the cold cell runs plain until it is due.
    A band with no measured loss, or any measured win, takes it at once.
    """
    band = cell_band(bucket)
    gains = [
        e.gain() for k, e in cells.items() if k != bucket and cell_band(k) == band and e.ready()
    ]
    if not gains:
        return False
    best = max(gains)
    if not 0.0 < best < 1.0 - margin:
        return False
    return phases_since_probe < priced_probe_floor(best, floor=floor, ceiling=ceiling)
# ---- spec_valve_rows.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Whether a cell's new rows speculate once to learn their own acceptance.

A row with no acceptance rate yet speculates for one phase so the step-cost
model (``SpecValveController._model_arm``) can price it. A cell that already
knows the rows it serves lose skips that phase. The question is what "knows"
means, and the cell's phase rings are the wrong instrument at a narrow width:

* A speculating phase scores whatever text its row happened to be writing.
  One row's acceptance moves within a response (reasoning, then a copied
  edit) and between responses to one prompt, so at width 1 the speculating
  ring's phases scatter widely around a plain ring that barely moves.
* The ring's median then lands below the dead band about as often as above
  it, and only probes refresh the ring once the cell runs plain. A cell that
  read a loss off such a median kept every later request on the plain arm,
  including requests that win, until a probe priced at that loss came due.

The unit the arm is chosen for is the row, so the evidence is rows: the last
:data:`ROW_TAU_RING` requests the cell priced, each by its own lifetime
expected tokens per step (``spec_row_estimate.row_tau``). Learning is paid
for like a probe when none of them clearly won against the cell's current
step-cost ratio (:func:`rows_lose`). One that won on a full read is enough to
keep learning freely: the cell serves traffic that can win, and one phase is
what finding out costs. The ring is
short so that a cell whose traffic turned to a losing kind stops paying that
phase after a few requests; one whose traffic turned to a winning kind finds
out at its next probe. The rings still decide when their phase
samples SEPARATE past the dead band (``WidthEstimate.rings_lose``), which a
wide slate's tight phases show from the first pair, and a narrow slate's
scattered ones only on a workload that loses throughout.

The same requests are the prior a row is priced against (:func:`shrunk_tau`).
A response's acceptance is not stationary: a code edit reasons first, at chat's
acceptance, and then copies. Its first phase alone priced it plain for the rest
of the response about one time in five. Pooled with the cell's recent requests,
weighted as one more request, a row leaves the arm its predecessors earned only
when its own drafts outweigh them.
"""

from __future__ import annotations

import math
from statistics import median

__all__ = [
    "ROW_TAU_RING",
    "note_row_taus",
    "own_read_decides",
    "pooled_weight",
    "row_read",
    "rows_lose",
    "shrunk_tau",
]

#: Requests whose last priced tau a cell keeps, and how many must all have lost
#: before a new row stops learning: the floor a stop verdict needs on each ring.
ROW_TAU_RING = 3


def note_row_taus(ring: dict, priced: list[tuple[object, float, int]]) -> None:
    """Fold ``(request_id, tau, drafts verified)`` rows just priced into ``ring``.

    ``ring`` is insertion-ordered by when a request was last priced; only the
    :data:`ROW_TAU_RING` most recent requests are kept, each at its latest read.
    """
    for rid, tau, drafts in priced:
        ring.pop(rid, None)
        ring[rid] = (float(tau), max(0, int(drafts)))
    while len(ring) > ROW_TAU_RING:
        ring.pop(next(iter(ring)))


def rows_lose(ring: dict, ratio: float, margin: float, short: int = 0) -> bool:
    """Whether no recently priced request clearly won at step-cost ``ratio``.

    A cell where none did lets a new row learn only at the probe budget
    (``spec_valve_learn``); one that did lets it learn freely, as it always
    did. A request at parity is not a win: learning a row there costs what
    speculating at parity costs, so it is paid for like a probe. A read on fewer
    than ``short`` drafts -- a short request or learning window -- that wins is no
    evidence either way: a few verifies of a losing response read as one often
    enough, and a cell serving only short winning replies is not losing. Its
    losing reads still count.

    False below :data:`ROW_TAU_RING` priced requests, with no losing read, or with no ratio.
    """
    if ratio <= 0.0 or len(ring) < ROW_TAU_RING:
        return False
    bar = ratio * (1.0 + margin)
    if any(tau > bar and d >= short for tau, d in ring.values()):
        return False  # a full read that won
    return any(tau <= bar for tau, _d in ring.values())


def shrunk_tau(ring: dict, rid: object, tau: float, drafts: int, short: int = 0) -> float:
    """``tau`` from ``drafts`` verified drafts, pooled with the cell's other recent requests.

    The prior is their mean tau, weighted as one request: the median of their
    verified drafts. Reads on fewer than ``short`` drafts -- short learning
    windows -- are left out of it while any longer read is there: one such read
    landing high pulled the next row of a losing cell over the dead band. With
    no other request priced the row stands on its own.
    """
    others = [v for k, v in ring.items() if k != rid]
    others = [v for v in others if v[1] >= short] or others
    if not others:
        return tau
    prior = sum(t for t, _ in others) / len(others)
    weight = median(d for _, d in others)
    total = max(0, int(drafts)) + weight
    return (max(0, int(drafts)) * tau + weight * prior) / total if total > 0 else tau


def own_read_decides(tau: float, drafts: int, k: int, ratio: float, margin: float) -> bool:
    """Whether a row's own ``tau`` on ``drafts`` drafts leaves the dead band by two standard errors."""
    if k <= 0 or drafts <= 0 or ratio <= 0.0:
        return False
    p = min(1.0, max(0.0, (tau - 1.0) / k))
    se = k * math.sqrt(p * (1.0 - p) / drafts)
    return tau - 2.0 * se > ratio * (1.0 + margin) or tau + 2.0 * se < ratio * (1.0 - margin)


def row_read(
    ring: dict,
    rid: object,
    tau: float,
    drafts: int,
    k: int,
    ratio: float,
    margin: float,
    short: int = 0,
) -> float:
    """The row's own ``tau`` once it decides alone (:func:`own_read_decides`), else pooled (:func:`shrunk_tau`)."""
    if own_read_decides(tau, drafts, k, ratio, margin):
        return tau
    return shrunk_tau(ring, rid, tau, drafts, short)


def pooled_weight(
    ring: dict, rid: object, drafts: int, tau: float, k: int, ratio: float, short: int = 0
) -> int:
    """The drafts :func:`row_read`'s prior adds to a row's own read (0 when the row decides alone)."""
    from arbi_serve.scheduler.spec_valve_estimate import DECIDE_MARGIN

    if own_read_decides(tau, drafts, k, ratio, DECIDE_MARGIN):
        return 0
    others = [v for kk, v in ring.items() if kk != rid]
    others = [v for v in others if v[1] >= short] or others
    return int(median(d for _, d in others)) if others else 0
# ---- spec_valve_shadow.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Pricing a new row in a losing cell from its shadow acceptance, without speculating it.

The step-cost model (:mod:`~arbi_serve.scheduler.spec_valve_model`) prices a row
by its expected committed tokens per step. In a cell whose evidence reads a loss
a row with no rate yet used to buy that rate by speculating in a budgeted
learning window (:mod:`~arbi_serve.scheduler.spec_valve_learn`). Where the
drafter can run a shadow pass (:mod:`arbi_serve.spec_shadow`) the
row stays plain instead: its served target probabilities are recorded past its
opening tokens, one drafter pass over the same positions gives the exact depth-1
acceptance, and the depth curve the cell measured on its own warm verifies
extends it to ``tau``. The first read covers
:data:`~arbi_serve.spec_shadow.SHADOW_FIRST` positions; a row whose interval
still reaches into the dead band records on to
:data:`~arbi_serve.spec_shadow.SHADOW_SPAN` (:func:`clear_cut`).
"""

from __future__ import annotations

from typing import Any

from arbi_serve import spec_shadow as _sw

__all__ = [
    "DEPTH_MIN_VERIFIES",
    "SHADOW_DUE_STEPS",
    "SHADOW_Z",
    "advance",
    "blend",
    "clear_cut",
    "depth_curve",
    "ripe",
    "shadow_read",
    "shadow_all",
    "shadow_rows",
    "shadow_tau",
]

#: Warm verifies a depth histogram needs before its shape is used.
DEPTH_MIN_VERIFIES = 32

#: Valve decisions a pass may stay owed before its window is given up (a path that runs none).
SHADOW_DUE_STEPS = 64


def _conditional(hist: list[int]) -> list[float] | None:
    """Per-depth conditional acceptance ``P(n >= j | n >= j - 1)``, ``j = 1..k``."""
    total = sum(hist)
    if total < DEPTH_MIN_VERIFIES:
        return None
    out, reach = [], total
    for j in range(1, len(hist)):
        past = sum(hist[j:])
        out.append(past / reach if reach > 0 else 0.0)
        reach = past
    return out


def depth_curve(cells: list, k: int) -> list[float] | None:
    """The conditional depth curve at draft depth ``k``: the first cell with enough warm verifies, else pooled."""
    pooled = [0] * (k + 1)
    for steady in cells:
        hist = steady.depth.get(k) if steady is not None else None
        if hist is None:
            continue
        curve = _conditional(hist) if steady is cells[0] else None
        if curve is not None:
            return curve
        pooled = [a + b for a, b in zip(pooled, hist, strict=True)]
    return _conditional(pooled)


def shadow_tau(alpha: float, k: int, curve: list[float] | None) -> float:
    """``1 + sum_j prod_{i<=j} a_i``: depth 1 at ``alpha``, deeper depths scaled from ``curve``.

    With no curve every depth takes ``alpha`` (a geometric run).
    """
    alpha = min(1.0, max(0.0, float(alpha)))
    if curve and curve[0] > 0.0:
        rates = [alpha] + [min(1.0, c * alpha / curve[0]) for c in curve[1:k]]
    else:
        rates = [alpha] * k
    tau, run = 1.0, 1.0
    for a in rates[:k]:
        run *= a
        tau += run
    return tau


def shadow_read(
    req: Any, k: int, curve: list[float] | None, ratio: float = 0.0, margin: float = 0.0
) -> tuple[float, int] | None:
    """``(tau, drafts-equivalent)`` from ``req``'s shadow acceptance, or ``None`` before it has one.

    A read short of the window's span counts only when even its interval
    places the row's gain (``tau / ratio``) outside ``1 +- margin``; otherwise
    the window records the rest of its span.
    """
    w = getattr(req, "mtp_shadow", None)
    if w is None or w.alpha is None or w.n <= 0 or w.more:
        return None
    if not w.final and not clear_cut(w, k, curve, ratio, margin):
        w.extend()
        return None
    if w.block:
        return w.tau_at(k), w.n * k
    return shadow_tau(w.alpha, k, curve), w.n * k


#: Standard errors a short read's interval spans on each side.
SHADOW_Z = 2.0


def clear_cut(w: Any, k: int, curve: list[float] | None, ratio: float, margin: float) -> bool:
    """Whether ``w``'s read places the gain outside the dead band at both ends of its interval."""
    if ratio <= 0.0:
        return False
    if w.block:
        tau, se = w.tau_at(k), w.tau_se
        return (tau - SHADOW_Z * se) / ratio > 1.0 + margin or (
            tau + SHADOW_Z * se
        ) / ratio < 1.0 - margin
    lo = shadow_tau(w.alpha - SHADOW_Z * w.se, k, curve) / ratio
    hi = shadow_tau(w.alpha + SHADOW_Z * w.se, k, curve) / ratio
    return lo > 1.0 + margin or hi < 1.0 - margin


def shadow_all() -> bool:
    """``mtp_valve_shadow_all``: every cell prices its new rows by shadow reads, outside the ledger."""
    from arbi_serve.runtime_flags import runtime_flags

    return bool(runtime_flags().mtp_valve_shadow_all)


def blend(read: tuple[float, int], tau: float | None, drafts: int) -> tuple[float, int]:
    """A row's own verified ``tau`` over ``drafts`` pooled with its shadow read."""
    s_tau, s_n = read
    if tau is None or drafts <= 0:
        return s_tau, s_n
    return (s_n * s_tau + drafts * tau) / (s_n + drafts), s_n + drafts


def shadow_rows(slate: list, unpriced: set, ledger: Any, after: int) -> frozenset:
    """Request ids of ``unpriced`` rows a shadow window measures; opens and advances windows.

    A window opens at ``after`` generated tokens while ``ledger`` affords one;
    a pass owed too long is given up.
    """
    if not _sw.shadow_available():
        return frozenset()
    out = set()
    for req in slate:
        rid = getattr(req, "request_id", id(req))
        if rid not in unpriced:
            continue
        w = getattr(req, "mtp_shadow", None)
        if w is None and (ledger.affords() or shadow_all()):
            w = _sw.open_window(req, after)
        if w is None or w.failed:
            continue
        if w.due:
            w.due_steps += 1
            if w.due_steps > SHADOW_DUE_STEPS:
                w.due, w.failed = False, "never_ran"
                _sw.SHADOW_WINDOW.refuse("never_ran")
        if not w.failed:
            out.add(rid)
    return frozenset(out)


def advance(slate: list, ledger: Any) -> None:
    """Act on each slate row's ripe window: place a full one for its pass, charge a measured one."""
    for req in slate:
        w = getattr(req, "mtp_shadow", None)
        if w is None or w not in _sw._RIPE:  # noqa: SLF001
            continue
        _sw._RIPE.discard(w)  # noqa: SLF001
        if w.alpha is not None and not w.charged and not w.more:
            ledger.charge(w.pass_s)
            w.charged = True
        elif not w.done and not w.due and w.rec and len(w.rec) >= w.goal:
            if _sw.resolve_window(req) is None:
                _sw._RIPE.add(w)  # noqa: SLF001 -- its last tokens have not committed yet


def ripe(slate: list) -> bool:
    """Whether a slate row's shadow window waits on the valve (cheap when none does)."""
    if not _sw._RIPE:  # noqa: SLF001
        return False
    return any(getattr(r, "mtp_shadow", None) in _sw._RIPE for r in slate)  # noqa: SLF001
# ---- spec_valve_warm.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The speculating arm's warm-up, read off the drafter's own acceptance.

A switch into speculation opens the speculating arm cold: the valve dropped
the rows' drafts, and a bundled head's own KV holds no cells for the positions
the plain arm decoded, so its acceptance is depressed until its frontier has
moved past that span. Scoring those steps charges the switch to the arm, which
is the bias :mod:`~arbi_serve.scheduler.spec_valve` documents: a real win reads
as parity or a loss. A fixed settle cannot size it; how long the drafter takes
to recover is a property of the drafter and the switch.

So the warm-up is watched. The verified drafts are read in windows of
``window`` drafts (the step-cost model's own floor for trusting an acceptance
rate); the arm is warm once a window's acceptance reaches the cell's steady
acceptance (measured on warm steps only), or, before any steady value exists
or when the drafter recovers to a lower level, once a window no longer rises
over the one before it. Only warm steps are scored, so each arm's estimate
and the steady acceptance the rows are priced on are steady-state reads.

A slate whose rows report no verified drafts carries no signal; the caller
keeps its fixed settle for it.
"""

from __future__ import annotations

from collections import deque
from typing import Any

#: Scored warm windows kept per cell for its steady acceptance.
STEADY_RING = 5


class WarmupWatch:
    """Decides, window by window, when a reopened speculating phase is warm."""

    __slots__ = ("_acc", "_margin", "_prev", "_prop", "_steady", "_window", "warm")

    def __init__(self, *, steady: float | None, window: int, margin: float) -> None:
        self._steady = steady
        self._window = max(1, int(window))
        self._margin = float(margin)
        self._prop = 0
        self._acc = 0
        self._prev: float | None = None
        self.warm = False

    def observe(self, proposed: int, accepted: int) -> bool:
        """Feed one step's verified drafts; ``True`` once the arm is warm."""
        if self.warm:
            return True
        self._prop += max(0, int(proposed))
        self._acc += max(0, int(accepted))
        if self._prop < self._window:
            return False
        rate = self._acc / self._prop
        self._prop = self._acc = 0
        reached = self._steady is not None and rate >= self._steady * (1.0 - self._margin)
        flat = self._prev is not None and rate <= self._prev * (1.0 + self._margin)
        self.warm = reached or flat
        self._prev = rate
        return self.warm


class SteadyAcceptance:
    """A cell's acceptance on warm speculating steps: overall, and per row."""

    __slots__ = ("_rows", "_windows", "depth")

    def __init__(self) -> None:
        self._windows: deque = deque(maxlen=STEADY_RING)
        self._rows: dict[int, list[int]] = {}
        #: Warm verifies by draft depth: ``depth[k][n]`` verifies of ``k`` drafts accepted ``n``.
        self.depth: dict[int, list[int]] = {}

    def record_phase(self, proposed: int, accepted: int) -> None:
        if proposed > 0:
            self._windows.append((int(proposed), int(accepted)))

    def record_row(self, rid: int, proposed: int, accepted: int) -> None:
        if 0 < proposed <= 16 and 0 <= accepted <= proposed:
            hist = self.depth.get(int(proposed))
            if hist is None:
                hist = self.depth[int(proposed)] = [0] * (int(proposed) + 1)
            hist[int(accepted)] += 1
        if proposed > 0:
            cell = self._rows.get(rid)
            if cell is None:
                cell = self._rows[rid] = [0, 0]
            cell[0] += int(proposed)
            cell[1] += int(accepted)

    def forget_rows(self, live: set) -> None:
        for rid in [r for r in self._rows if r not in live]:
            del self._rows[rid]

    def rate(self) -> float | None:
        prop = sum(p for p, _a in self._windows)
        return None if prop <= 0 else sum(a for _p, a in self._windows) / prop

    def row_tau(self, rid: int, k: int, min_proposed: int) -> float | None:
        """``1 + k * accepted / proposed`` over the row's warm steps, once it has enough."""
        cell = self._rows.get(rid)
        if cell is None or cell[0] < min_proposed:
            return None
        return 1.0 + k * cell[1] / cell[0]


def draft_counts(row: Any) -> tuple[int, int] | None:
    """A row's lifetime ``(proposed, accepted)`` verify counters, or ``None`` without them."""
    proposed = getattr(row, "mtp_proposed", None)
    if proposed is None:
        return None
    return int(proposed or 0), int(getattr(row, "mtp_accepted", 0) or 0)


__all__ = ["STEADY_RING", "SteadyAcceptance", "WarmupWatch", "draft_counts"]
# ---- step_budget.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Per-step slate-budget computation for the continuous-batch scheduler.

This is pure host-side arithmetic computed ONCE at the top of each
step, BEFORE the slate-build loops run — it does NOT touch the
per-token ``commit`` accounting where the documented start_pos /
seq_lens off-by-one class lives. ``schedule`` stays the orchestrator:
it calls :func:`compute_step_budget`, unpacks the result, and runs its
continue-running + admit-waiting loops.

The computed knobs:

  * ``chunk_cap_this_step`` — the per-row prefill chunk cap. It is
    ``chunk_prefill`` for every row: the step budget is spent depth-first in
    queue order (see :func:`compute_step_budget`), never divided across the
    competing prefills.
  * ``interactive_present`` — True iff ANY interactive request is in the
    system this step (waiting OR running). Drives the interactive-only
    slate construction (batch fully suspended when interactive present).
  * ``batch_rows_left`` / ``batch_tokens_left`` / ``batch_prefill_cap`` —
    batch-only step-size caps bounding the one in-flight batch step an
    arriving interactive request must wait out.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING

from arbi_serve.engine.request import RequestState
from arbi_serve.scheduler.flex_drain import plan_flex_drain

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request
    from arbi_serve.scheduler.scheduler import Scheduler


@dataclass(slots=True)
class StepBudget:
    """Per-step slate-sizing knobs computed at the top of ``schedule``."""

    chunk_cap_this_step: int
    interactive_present: bool
    batch_rows_left: int | None
    batch_tokens_left: int | None
    batch_prefill_cap: int | None
    #: Cap on a prefill chunk that shares its step with a DECODING row, or
    #: ``None`` when nothing decodes this step (or the knob is off). Applied
    #: by ``schedule`` AFTER the recurrent whole-``chunk_prefill`` override,
    #: which would otherwise restore the full chunk on exactly the hybrid
    #: models this was measured on.
    coadmit_prefill_cap: int | None
    #: The one paused flex prefill row the gentle drain lets advance despite interactive work
    #: (:func:`~arbi_serve.scheduler.flex_drain.plan_flex_drain`), else ``None``.
    flex_drain_row: Request | None = None


def _interactive_present(sched: Scheduler) -> bool:
    """True iff any non-batch request is queued or running.

    Delegates to the scheduler's O(1) counter predicate when it has one;
    schedulers that fabricate ``waiting`` / ``running`` without the
    counter machinery (unit-test doubles) fall back to the exact scan.
    """
    predicate = getattr(sched, "any_interactive_present", None)
    if predicate is not None:
        return bool(predicate())
    return any(not r.is_flex for r in sched.waiting) or any(not r.is_flex for r in sched.running)


def _n_interactive(sched: Scheduler) -> int:
    """Interactive requests that need a slate row: running, waiting, or deferred for a row.

    O(1) off the scheduler's priority-split counters; schedulers that fabricate ``waiting`` /
    ``running`` without them (unit-test doubles) fall back to the exact scan.
    """
    running = getattr(sched, "_n_running_interactive", None)
    waiting = getattr(sched, "_n_waiting_interactive", None)
    deferred = getattr(sched, "_n_deferred_interactive", 0)
    if isinstance(running, int) and isinstance(waiting, int):
        return running + waiting + (deferred if isinstance(deferred, int) else 0)
    return sum(1 for r in sched.waiting if not r.is_flex) + sum(
        1 for r in sched.running if not r.is_flex
    )


def compute_step_budget(sched: Scheduler) -> StepBudget:
    """Compute the per-step slate-sizing knobs for one ``schedule`` call.

    Reads the live ``sched.running`` / ``sched.waiting`` /
    ``sched.batch_cfg`` via the ``sched`` reference.
    """
    batch_cfg = sched.batch_cfg
    # Depth-first FCFS: every prefill row is capped at ``chunk_prefill`` and
    # the step's token budget is handed out in queue order, so the oldest
    # prompt finishes first and the next one takes whatever budget is left.
    # The step carries the same number of tokens as any division of the budget
    # would; what the order decides is WHEN each prompt's last chunk runs.
    # Dividing the budget across K competing prefills (breadth-first) advances
    # all of them together, so every request in a wave reaches its first
    # token at the wave's total prefill time, and the median TTFT equals the
    # worst one. Depth-first completes prompt i after i prompts' worth of
    # prefill, the same ordering vLLM (``max_num_partial_prefills=1``) and
    # SGLang (one chunked request at a time) run.
    chunk_cap_this_step = batch_cfg.chunk_prefill
    decode_tokens_est = sum(1 for r in sched.running if r.state == RequestState.DECODING)
    decode_tokens_est = min(decode_tokens_est, batch_cfg.max_batch)

    # Interactive-always-priority slate construction (opportunistic
    # batch as filler).
    # ====================================================================
    # The conceptual model: interactive is the ABSOLUTE priority for PREFILL
    # compute; flex is opportunistic filler.
    #
    # ``interactive_present`` is True iff ANY interactive request is in
    # the system this step — either still WAITING (un-admitted) OR
    # already RUNNING (prefilling / decoding). When it's True, no flex
    # PREFILL runs: every running flex prefill row is skipped (it keeps
    # its KV pages and resumes when interactive demand clears) and no flex
    # request is admitted from the waiting queue, because a prefill chunk
    # is the compute-heavy forward that would block the interactive
    # request's own prefill. Flex DECODE rows are different: one token
    # per row is cheap, so they keep stepping and share the forward with
    # the interactive rows, riding along on its prefill. They stay under
    # the batch-only step caps below, which bound how many ride along.
    #
    # Worst-case interactive wait (the latency math): an arriving
    # interactive request can't preempt a GPU forward mid-kernel, so it
    # waits at most ONE in-flight batch step. That step is bounded by
    # ``batch_step_max_rows`` / ``batch_step_max_tokens`` below (the
    # batch-only slate is small), so the wait is one SMALL step (a few
    # ms), not one fat 64-way forward (~50-100 ms). The next slate after
    # the wakeup carries no flex prefill by this gate. Total worst-case TTFT
    # ≈ (one small batch step) + (one interactive prefill step plus the
    # riding flex decode rows) ≈ a small multiple of the idle floor.
    #
    # The predicate reads the scheduler's priority-split counters, so it
    # costs the same whether one request is queued or ten thousand are;
    # batch fills the GPU normally when it is False, bounded only by the
    # batch-only step caps.
    interactive_present = _interactive_present(sched)
    # Batch-only step-size caps. They bound a flex-only step, and also how many
    # flex decode rows ride along with interactive work. ``0`` disables a cap.
    batch_step_max_rows = int(getattr(batch_cfg, "batch_step_max_rows", 0) or 0)
    batch_step_max_tokens = int(getattr(batch_cfg, "batch_step_max_tokens", 0) or 0)
    batch_rows_left = batch_step_max_rows if batch_step_max_rows > 0 else None
    if interactive_present:
        # Flex decodes ride along, but only in the slots interactive work leaves: interactive rows
        # (running, waiting, or deferred for a row) come first, so a full batch of flex never holds an
        # interactive arrival out of the slate. Flex rows already running are simply left out of the step.
        ride = max(0, int(batch_cfg.max_batch) - _n_interactive(sched))
        batch_rows_left = ride if batch_rows_left is None else min(batch_rows_left, ride)
    batch_tokens_left = batch_step_max_tokens if batch_step_max_tokens > 0 else None
    # Pillar A — tighter per-batch-PREFILL-chunk cap. Bounds the one
    # fat batch prefill forward that an arriving interactive request
    # would otherwise wait out (8k-prefill → ~34 ms). Falls back to
    # ``batch_step_max_tokens`` when 0. Applies only to batch prefill
    # ``want`` sizing below; decode steps keep their efficient sizing.
    batch_prefill_cap = int(getattr(batch_cfg, "batch_step_max_prefill_tokens", 0) or 0)
    if batch_prefill_cap <= 0:
        batch_prefill_cap = batch_step_max_tokens
    batch_prefill_cap = batch_prefill_cap if batch_prefill_cap > 0 else None

    # Co-admitted prefill cap. Binds only when a row is DECODING this step,
    # because that is the row the fat prefill forward makes wait: it gets one
    # decode step per chunk, so its inter-token time is the chunk's time.
    # ``decode_tokens_est`` is already that count, computed above.
    #
    # Read off the scheduler's LIVE snapshot, not the boot config, so the
    # trade-off can be swept on one boot — and so an operator can back it out
    # of a running server without a restart. Schedulers fabricated by unit
    # tests without the snapshot fall back to off.
    coadmit_cap = int(getattr(sched, "_coadmit_prefill_max_tokens", 0) or 0)
    coadmit_prefill_cap = coadmit_cap if (coadmit_cap > 0 and decode_tokens_est > 0) else None

    return StepBudget(
        chunk_cap_this_step=chunk_cap_this_step,
        interactive_present=interactive_present,
        batch_rows_left=batch_rows_left,
        batch_tokens_left=batch_tokens_left,
        batch_prefill_cap=batch_prefill_cap,
        coadmit_prefill_cap=coadmit_prefill_cap,
        flex_drain_row=plan_flex_drain(sched, interactive_present),
    )
# ---- task_queues.py ----
# SPDX-License-Identifier: Apache-2.0
"""Per-task queues of one engine's waiting requests: priority, latency class, batch cadence.

An engine that serves several tasks in one scheduler (the OCR ``forward`` engine runs
layout, text detection, text recognition and tables; embed, rerank and decide models are to join
the same way) admitted them first come, first served from one queue. A page's layout, which
gates all of its later work, then waited behind whatever OCR crops arrived before it.

A task declares a :class:`TaskPolicy` (its media binding's ``policy``,
:mod:`arbi_serve.multimodal.registry`), the per-model queue settings of a serving system such as
Triton's dynamic batcher:

* ``latency_class``: ``"interactive"`` tasks are admitted before ``"bulk"`` ones;
* ``priority``: within one class, higher first;
* ``max_inflight``: at most this many of the task's requests run at once (``None``: no bound
  beyond the step's own). For a prefill-only task a request runs one step, so this is also the
  task's rows per step: its batch size;
* ``max_wait_ms``: batch cadence. While fewer requests of the task wait than its free
  ``max_inflight`` rows, its oldest may wait this long for batch mates, but only on a step that
  runs other work anyway: a held task never leaves the GPU idle.

The queues are views of ``Scheduler.waiting``, kept by the scheduler's own add/remove helpers
(``scheduler_counters``); ``waiting`` stays the one queue every other path reads. The picker
(``_SelectionMixin._next_waiting_candidate``) takes the best head among the tasks that may admit
this step. The request's own sampling class still comes first, so the interactive-always-priority
gate is untouched. An engine whose model declares no policy has no ``TaskQueues``, and
selection is exactly what it was.
"""

from __future__ import annotations

import itertools
import time
from collections import Counter, deque
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, fields
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request

#: Latency classes, best first.
LATENCY_CLASSES = ("interactive", "bulk")


@dataclass(frozen=True)
class TaskPolicy:
    """How one task's requests are queued, batched and run (see the module docstring)."""

    latency_class: str = "bulk"
    priority: int = 0
    max_inflight: int | None = None
    max_wait_ms: float = 0.0
    exclusive_step: bool = False

    def __post_init__(self) -> None:
        if self.latency_class not in LATENCY_CLASSES:
            raise ValueError(
                f"latency_class must be one of {LATENCY_CLASSES}, not {self.latency_class!r}"
            )
        if self.max_inflight is not None and self.max_inflight < 1:
            raise ValueError("max_inflight must be a positive row count (or None)")
        if self.exclusive_step and self.latency_class != "bulk":
            raise ValueError("only bulk tasks may own an exclusive step")
        if self.max_wait_ms < 0:
            raise ValueError("max_wait_ms must not be negative")

    def rank(self) -> tuple[int, int]:
        """Sort key among tasks: class, then priority (smaller is better)."""
        return LATENCY_CLASSES.index(self.latency_class), -int(self.priority)


#: The policy of a request that names no declared task.
DEFAULT_POLICY = TaskPolicy()


def task_of(req: Any) -> str | None:
    """The task a request belongs to: its ``task_key`` when set, else the one modality its media
    carries (a ``forward``-task request), else ``None``."""
    key = getattr(req, "task_key", None)
    if key:
        return str(key)
    mm = getattr(req, "multimodal", None)
    if mm and len(mm) == 1:
        return next(iter(mm))
    return None


def declared_policies(bindings: Mapping[str, Any] | None) -> dict[str, TaskPolicy]:
    """Each media binding's declared policy (``MediaBinding.policy``); ``{}`` when nothing is
    declared (the engine keeps its one FCFS queue)."""
    return {
        name: b.policy
        for name, b in (bindings or {}).items()
        if getattr(b, "policy", None) is not None
    }


class TaskQueues:
    """The waiting requests split per task (and per sampling class), in arrival order, plus the
    running rows per task. Fed by the scheduler's queue helpers; read by its picker."""

    def __init__(self, policies: Mapping[str, TaskPolicy], clock=time.monotonic) -> None:
        self.revision = 0
        self.policies = dict(policies)
        self._step_active: set[str | None] | None = None
        self.admission_ready = None  # Optional non-consuming quota eligibility.
        self._clock = clock
        self._seq = itertools.count()
        self._front = itertools.count(-1, -1)  # preempted requests re-enter ahead of everyone
        # (is_batch, task) -> deque of (seq, enqueued_at, request)
        self._queues: dict[tuple[bool, str | None], deque] = {}
        self.running: Counter = Counter()
        self._bulk_turn: dict[str | None, int] = {}
        self._turn = itertools.count(1)
        self.held = Counter()  # times a task was held for batch mates (stats)

    def policy(self, task: str | None) -> TaskPolicy:
        return self.policies.get(task, DEFAULT_POLICY) if task is not None else DEFAULT_POLICY

    # ── queue maintenance (the scheduler's add/remove helpers) ───────
    def waiting_added(self, req: Request, *, left: bool = False) -> None:
        self.revision += 1
        if req.is_duplex_frame:
            return  # duplex rows are admitted by their own lane, never by the picker
        key = (bool(req.is_flex), task_of(req))
        q = self._queues.setdefault(key, deque())
        entry = (next(self._front) if left else next(self._seq), self._clock(), req)
        if left:
            q.appendleft(entry)
        else:
            q.append(entry)

    def waiting_removed(self, req: Request) -> None:
        self.revision += 1
        q = self._queues.get((bool(req.is_flex), task_of(req)))
        if not q:
            return
        for i, (_, _, r) in enumerate(q):
            if r is req:
                del q[i]
                return

    def running_added(self, req: Request) -> None:
        self.revision += 1
        task = task_of(req)
        self.running[task] += 1
        if self.policy(task).exclusive_step:
            self._bulk_turn[task] = next(self._turn)

    def running_removed(self, req: Request) -> None:
        self.revision += 1
        task = task_of(req)
        if self.running[task] > 0:
            self.running[task] -= 1
            if not self.running[task] and self._step_active is not None:
                self._step_active.discard(task)

    def rebuild(self, waiting: Iterable[Request], running: Iterable[Request]) -> None:
        """Resynchronise from the scheduler's queues (when the policies arrive late)."""
        self._queues.clear()
        self.running.clear()
        for req in waiting:
            self.waiting_added(req)
        for req in running:
            self.running_added(req)

    def waiting_count(self) -> int:
        return sum(len(q) for q in self._queues.values())

    # ── selection ─────────────────────────────────────────────────────
    def begin_step(self) -> None:
        """Distinguish continuing cohorts from rows admitted by this slate build."""
        self._step_active = {task for task, count in self.running.items() if count}

    def _competing_bulk_ready(self, task, *, interactive_only, slate_has_work, now):
        # Ignore only the running owner's exclusivity here: it is exactly what
        # draining that owner will release. Other structural gates still apply.
        for (is_batch, other), q in self._queues.items():
            if other == task or (is_batch and interactive_only):
                continue
            policy = self.policy(other)
            if policy.latency_class != "bulk":
                continue
            head = self._head(q)
            if head is None:
                continue
            free = (
                None if policy.max_inflight is None else policy.max_inflight - self.running[other]
            )
            if free is not None and free <= 0:
                continue
            if (
                policy.max_wait_ms > 0
                and slate_has_work
                and (free is None or self._ready(other, free) < free)
                and (now - head[1]) * 1000.0 < policy.max_wait_ms
            ):
                continue
            return True
        return False

    def _head(self, q: deque):
        from arbi_serve.engine.request import RequestState

        # a request taken out of ``waiting`` behind the helpers' back (it is no longer WAITING)
        while q and q[0][2].state != RequestState.WAITING:
            q.popleft()
        if not q or self.admission_ready is None:
            return q[0] if q else None
        for entry in q:
            if entry[2].state == RequestState.WAITING and self.admission_ready(entry[2]):
                return entry
        return None

    def pick(self, *, interactive_only: bool, slate_has_work: bool) -> Request | None:
        """The waiting request to try next: the best ``(sampling class, latency class, priority,
        arrival)`` head among the tasks that may admit now, or ``None`` when none may.

        ``interactive_only``: background-priority requests are not candidates. ``slate_has_work``: the
        step runs something anyway, so a task may be held for its batch cadence."""
        now = self._clock()
        best, best_key = None, None
        for (is_batch, task), q in self._queues.items():
            if is_batch and interactive_only:
                continue
            head = self._head(q)
            if head is None:
                continue
            policy = self.policy(task)
            if policy.exclusive_step and any(
                t != task and n > 0 and self.policy(t).latency_class == "bulk"
                for t, n in self.running.items()
            ):
                continue
            if policy.latency_class == "bulk" and any(
                t != task and n > 0 and self.policy(t).exclusive_step
                for t, n in self.running.items()
            ):
                continue
            free = None if policy.max_inflight is None else policy.max_inflight - self.running[task]
            if free is not None and free <= 0:
                continue
            if (
                policy.max_wait_ms > 0
                and slate_has_work
                and (free is None or self._ready(task, free) < free)
                and (now - head[1]) * 1000.0 < policy.max_wait_ms
            ):
                self.held[task] += 1
                continue
            if (
                policy.exclusive_step
                and self.running[task] > 0
                and (self._step_active is None or task in self._step_active)
                and self._competing_bulk_ready(
                    task,
                    interactive_only=interactive_only,
                    slate_has_work=slate_has_work,
                    now=now,
                )
            ):
                # Refilling a partially finished cohort can keep its running
                # count positive forever. Close new admission until it drains;
                # the normal age picker then gives the competing bulk a turn.
                continue
            # Exclusive bulk groups alternate between steps. Priority breaks
            # ties; a continuous OCR stream cannot starve document embedding.
            age = self._bulk_turn.get(task, 0) if policy.exclusive_step else 0
            key = (is_batch, policy.rank()[0], age, policy.rank()[1], head[0])
            if best_key is None or key < best_key:
                best, best_key = head[2], key
        return best

    def must_drain_for_interactive_bulk(self, task: str | None) -> bool:
        """Let an exclusive owner finish when it blocks a higher-priority bulk request.

        An actually runnable interactive request retains its normal priority.
        """
        if not self.policy(task).exclusive_step:
            return False
        if self.pick(interactive_only=True, slate_has_work=True) is not None:
            return False
        return any(
            not is_batch
            and other != task
            and self.policy(other).latency_class == "bulk"
            and self._head(queue) is not None
            for (is_batch, other), queue in self._queues.items()
        )

    def _ready(self, task: str | None, cap: int) -> int:
        """Waiting requests of ``task`` (both classes), counted up to ``cap``."""
        n = 0
        for (_, t), q in self._queues.items():
            if t == task:
                if self.admission_ready is None:
                    n += len(q)
                else:
                    from arbi_serve.engine.request import RequestState

                    n += sum(
                        self.admission_ready(req)
                        for _, _, req in q
                        if req.state == RequestState.WAITING
                    )
                if n >= cap:
                    return n
        return n

    def snapshot(self) -> dict:
        waiting = Counter()
        for (_, task), q in self._queues.items():
            waiting[task] += len(q)
        return {
            str(task): {
                "waiting": waiting[task],
                "running": self.running[task],
                "held": self.held[task],
                **{f.name: getattr(self.policy(task), f.name) for f in fields(TaskPolicy)},
            }
            for task in set(waiting) | set(self.running) | set(self.policies)
        }
# ---- __init__.py ----
# SPDX-License-Identifier: Apache-2.0
"""Sampling utilities operating on ``(K, num_seqs, V)`` logits.

The :class:`Sampler` + :class:`LogitsProcessor` chain is the single
production sampling path. ``XGrammarLogitsProcessor`` is exposed via
lazy attribute access — its underlying ``import xgrammar`` pulls
``transformers``, and structured-generation code paths are only
touched once the engine encounters its first
``response_format``-bearing request.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from arbi_serve.sampler.processors import LogitsProcessor
from arbi_serve.sampler.sampler import Sampler
from arbi_serve.sampler.structured import StructuredOutputsParams

if TYPE_CHECKING:
    from arbi_serve.sampler.xgrammar_processor import (
        XGrammarLogitsProcessor as XGrammarLogitsProcessor,
    )

__all__ = [
    "LogitsProcessor",
    "Sampler",
    "StructuredOutputsParams",
    "XGrammarLogitsProcessor",
]


def __getattr__(name: str) -> Any:
    if name == "XGrammarLogitsProcessor":
        from arbi_serve.sampler.xgrammar_processor import XGrammarLogitsProcessor

        return XGrammarLogitsProcessor
    raise AttributeError(f"module 'arbi_serve.sampler' has no attribute {name!r}")
# ---- _gumbel_argmax_kernel.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Triton ``@triton.jit`` kernels for the counter-based Gumbel-max sampler.

These kernels back the public wrappers in
:mod:`arbi_serve.sampler.gumbel_argmax_triton`; they live in a sibling
module purely to keep each first-party file under the size cap. Import
the public API from ``gumbel_argmax_triton`` — not from here.

See that module's docstring for the sampler's design (single-pass
counter-based Gumbel-max, Philox4x32-10 on-the-fly noise, cross-rank /
SPMD determinism).

``SEED_PTR`` is never specialized: the seed is one scalar load, and a seed
tensor sliced off a batch arrives at an address Triton would key a separate
compile on (16-byte aligned or not), which no boot warm can predict. The
draw kernel's row count and split are runtime values for the same reason as
the GEMMs' rows (:mod:`arbi_serve.kernels.row_sites`).
"""

from __future__ import annotations

import triton
import triton.language as tl
from triton.language.extra import libdevice

# Philox4x32 round constants (Salmon et al., "Parallel Random Numbers:
# As Easy as 1, 2, 3"). Same generator family torch's CUDA RNG uses.
_PHILOX_M0 = 0xD2511F53
_PHILOX_M1 = 0xCD9E8D57
_PHILOX_W0 = 0x9E3779B9  # golden-ratio key bump, lane 0
_PHILOX_W1 = 0xBB67AE85  # sqrt(3)-1 key bump, lane 1

# 2^-23 — maps a uint32's top 23 bits to (0, 1) as ``((x >> 9) + 0.5) * 2^-23``.
# Every such value is exact in fp32, so ``u`` stays strictly inside the open
# interval and ``-log(-log(u))`` is finite. ``(x + 0.5) * 2^-32`` is not: fp32
# rounds every ``x >= 2^32 - 128`` up to ``2^32``, so ``u == 1.0`` and the
# Gumbel is ``+inf``, which picks that vocab entry whatever its logit (a
# ~3e-8 chance per entry, ~0.3% of tokens at a 100k vocab).
_TWO_POW_NEG23 = 1.1920928955078125e-07


@triton.jit
def _philox4x32_lane0(c0, c1, c2, key_lo, key_hi):
    """One Philox4x32-10 draw → a fp32 uniform in the open interval (0, 1).

    ``c0``/``c1``/``c2`` are uint32 tensors seeding counter lanes 0-2
    (lane 3 is zero); ``key_lo/key_hi`` are the Philox key (a 64-bit seed
    split into two uint32). Ten Feistel-style rounds with per-round key
    bumps — the standard Philox4x32-10 used by cuRAND / torch. Returns
    lane-0 of the output mapped to (0, 1) (top 23 bits). All arithmetic is uint32
    (wraps), so the result is bit-identical on every device and every
    rank. Distinct ``(key, c0, c1, c2)`` tuples yield independent draws —
    callers spread (vocab index, row, draw-class) over the counter lanes
    to get decorrelated streams from one seed.
    """
    c3 = tl.zeros_like(c0)
    k0 = key_lo + tl.zeros_like(c0)
    k1 = key_hi + tl.zeros_like(c0)

    # Philox4x32 round + key-bump constants (inlined — Triton @jit cannot
    # read module globals). M0/M1 are the Philox multipliers; W0/W1 the
    # golden-ratio / sqrt(3)-1 key bumps.
    m0 = tl.full(c0.shape, 0xD2511F53, tl.uint32)
    m1 = tl.full(c0.shape, 0xCD9E8D57, tl.uint32)
    w0 = tl.full(c0.shape, 0x9E3779B9, tl.uint32)
    w1 = tl.full(c0.shape, 0xBB67AE85, tl.uint32)

    for _ in tl.static_range(10):
        hi0 = tl.umulhi(m0, c0)
        lo0 = m0 * c0
        hi1 = tl.umulhi(m1, c2)
        lo1 = m1 * c2
        nc0 = hi1 ^ c1 ^ k0
        nc1 = lo1
        nc2 = hi0 ^ c3 ^ k1
        nc3 = lo0
        c0 = nc0
        c1 = nc1
        c2 = nc2
        c3 = nc3
        k0 = k0 + w0
        k1 = k1 + w1

    # Lane-0 uint32 → (0, 1) from its top 23 bits, exact in fp32 (see
    # ``_TWO_POW_NEG23``). 2^-23 = 1.1920928955078125e-07.
    return ((c0 >> 9).to(tl.float32) + 0.5) * 1.1920928955078125e-07


@triton.jit
def _philox_uniform(counter, key_lo, key_hi):
    """Philox4x32-10 uniform keyed on ``(row_seed, vocab_index)`` only.

    ``counter`` seeds counter lane 0 (the vocab index); lanes 1-2 are
    zero. The per-row decode sampler's draw — see
    :func:`_philox4x32_lane0` for the full-counter variant.
    """
    c0 = counter.to(tl.uint32)
    z = tl.zeros_like(c0)
    return _philox4x32_lane0(c0, z, z, key_lo, key_hi)


@triton.jit
def _gumbel_partial_kernel(
    LOGITS,
    SEEDS,
    PART_SCORE,
    PART_IDX,
    BATCH_SIZE,
    SPLIT,
    INDEX_BASE,
    VOCAB_SIZE: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,
):
    """Partial single-pass Gumbel-max argmax over a contiguous vocab chunk.

    Grid is ``(BATCH_SIZE * SPLIT,)``. Program ``pid`` owns row
    ``pid // SPLIT`` and the contiguous vocab chunk ``pid % SPLIT`` (so
    a B=1 decode fans a single row across up to ``SPLIT`` SMs — the whole
    point, since one SM cannot saturate HBM over a 248k-wide row). Each
    program writes its chunk-best ``(score, idx)`` to ``PART_*`` and a
    trivial host-side ``argmax`` over the ``SPLIT`` partials finishes the
    reduction. Contiguous (not strided) chunks keep the per-program tiles
    coalesced AND make lower vocab indices land in lower ``split_id``s, so
    the finishing ``argmax`` inherits a lowest-index tie-break.

    ``INDEX_BASE`` is the global vocab index of column 0: a vocab-parallel
    rank draws its own shard with the noise the whole row has at those
    tokens, so its winner is the whole row's winner whenever it holds it.
    Returned indices stay shard-local.
    """
    pid = tl.program_id(0)
    row_id = pid // SPLIT
    split_id = pid % SPLIT
    if row_id >= BATCH_SIZE:
        return

    seed = tl.load(SEEDS + row_id)  # int64
    key_lo = (seed & 0xFFFFFFFF).to(tl.uint32)
    key_hi = ((seed >> 32) & 0xFFFFFFFF).to(tl.uint32)

    CHUNK = (VOCAB_SIZE + SPLIT - 1) // SPLIT
    start = split_id * CHUNK
    end = tl.minimum(start + CHUNK, VOCAB_SIZE)

    LOGITS_ROW = LOGITS + row_id * VOCAB_SIZE
    best_score = -float("inf")
    best_idx = tl.zeros((), dtype=tl.int64)

    n_tiles = (CHUNK + BLOCK_SIZE - 1) // BLOCK_SIZE
    for t in range(0, n_tiles):
        offs = start + t * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
        mask = offs < end
        logit = tl.load(LOGITS_ROW + offs, mask=mask, other=-float("inf")).to(tl.float32)
        # A tile the top-k / top-p mask emptied cannot hold the winner: every
        # score in it is -inf, and -inf never beats ``best_score``. Skipping
        # its Philox draws changes no output (the noise is keyed by vocab
        # index, not by draw order) and is most of the kernel after a mask:
        # a decode nucleus is a handful of tokens out of the whole vocab.
        if tl.max(logit) != -float("inf"):
            u = _philox_uniform(offs + INDEX_BASE, key_lo, key_hi)
            gumbel = -tl.log(-tl.log(u))
            score = tl.where(mask, logit + gumbel, -float("inf"))

            tile_max = tl.max(score)
            tile_arg = tl.argmax(score, axis=0)
            tile_idx = start + t * BLOCK_SIZE + tile_arg
            take = tile_max > best_score
            best_idx = tl.where(take, tile_idx.to(tl.int64), best_idx)
            best_score = tl.where(take, tile_max, best_score)

    tl.store(PART_SCORE + pid, best_score)
    tl.store(PART_IDX + pid, best_idx)


@triton.jit(do_not_specialize=["SEED_PTR"])
def _seeded_gumbel_partial_kernel(
    SCORES,  # (N_ROWS, V) fp32/bf16/fp16, unit V stride — log-probs or masked logits
    SEED_PTR,  # (1,) int64 device — the rank-agreed step seed
    PART_SCORE,
    PART_IDX,
    N_ROWS,
    SPLIT,
    DRAW_OFFSET: tl.constexpr,
    VOCAB_SIZE: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,
):
    """Partial single-pass Gumbel-max argmax keyed on a DEVICE step seed.

    Like :func:`_gumbel_partial_kernel` but the Philox key is the shared
    step seed read INSIDE the kernel (``tl.load(SEED_PTR)`` — no host
    readback, capture-replay reads whatever ``copy_()`` last wrote) and
    the per-row / per-draw-class decorrelation rides the counter lanes:
    ``(vocab_index, row, DRAW_OFFSET)`` — the same namespacing
    :func:`_residual_gumbel_partial_kernel` uses (verify recovery/bonus
    own ``DRAW_OFFSET = OFFSET_RECOVERY``; the drafter chain passes
    ``OFFSET_DRAFTER + 17 * step``). ``-inf`` score entries (masked-out /
    zero-probability tokens) stay ``-inf`` after the Gumbel add and can
    never win, so the drawn support is exactly the finite-score set.

    Grid, chunking, and tie-break follow :func:`_gumbel_partial_kernel`:
    ``(N_ROWS * SPLIT,)`` programs, contiguous chunks, strictly-greater
    running max ⇒ lowest-index tie-break.
    """
    pid = tl.program_id(0)
    row = pid // SPLIT
    split_id = pid % SPLIT
    if row >= N_ROWS:
        return

    seed = tl.load(SEED_PTR)  # int64
    key_lo = (seed & 0xFFFFFFFF).to(tl.uint32)
    key_hi = ((seed >> 32) & 0xFFFFFFFF).to(tl.uint32)

    CHUNK = (VOCAB_SIZE + SPLIT - 1) // SPLIT
    start = split_id * CHUNK
    end = tl.minimum(start + CHUNK, VOCAB_SIZE)

    ROW = SCORES + row * VOCAB_SIZE
    best_score = -float("inf")
    best_idx = tl.zeros((), dtype=tl.int64)

    n_tiles = (CHUNK + BLOCK_SIZE - 1) // BLOCK_SIZE
    for t in range(0, n_tiles):
        offs = start + t * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
        mask = offs < end
        s = tl.load(ROW + offs, mask=mask, other=-float("inf")).to(tl.float32)

        c0 = offs.to(tl.uint32)
        c1 = tl.zeros_like(c0) + row.to(tl.uint32)
        c2 = tl.zeros_like(c0) + DRAW_OFFSET
        u = _philox4x32_lane0(c0, c1, c2, key_lo, key_hi)
        gumbel = -tl.log(-tl.log(u))
        # ``-inf + gumbel = -inf`` — masked / zero-prob entries never win.
        score = tl.where(mask, s + gumbel, -float("inf"))

        tile_max = tl.max(score)
        tile_arg = tl.argmax(score, axis=0)
        take = tile_max > best_score
        best_idx = tl.where(take, (start + t * BLOCK_SIZE + tile_arg).to(tl.int64), best_idx)
        best_score = tl.where(take, tile_max, best_score)

    tl.store(PART_SCORE + pid, best_score)
    tl.store(PART_IDX + pid, best_idx)


@triton.jit(do_not_specialize=["SEED_PTR"])
def _residual_gumbel_partial_kernel(
    P,  # target probs (dense) OR temperature-scaled logits (IN_LOG_SPACE)
    Q,  # drafter probs, same addressing; read only for rows < KB (dense mode)
    DRAFT,  # (K, B) int drafted tokens; read only for rows < KB (one-hot mode)
    LSE,  # (N_ROWS,) fp32 row logsumexp; read only when IN_LOG_SPACE
    SEED_PTR,  # (1,) int64 device — the rank-agreed step seed
    PART_SCORE,
    PART_IDX,
    PART_PVAL,
    PART_PIDX,
    N_ROWS,
    KB,
    B,
    SPLIT,
    p_stride_k,
    p_stride_b,
    q_stride_k,
    q_stride_b,
    d_stride_k,
    d_stride_b,
    Q_IS_ONEHOT: tl.constexpr,
    IN_LOG_SPACE: tl.constexpr,
    DRAW_OFFSET: tl.constexpr,
    VOCAB_SIZE: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,
    PER_ROW_SEED: tl.constexpr = False,
):
    """Partial single-pass Gumbel-max over the MTP verify residual / bonus rows.

    Flat row layout over ``(K+1, B)``: row ``r = k * B + b``. Rows
    ``r < KB`` (``k < K``) are RESIDUAL rows — the Gumbel-max runs on
    ``log((p - q)+)``, an exact categorical draw from the normalised
    Leviathan-2023 recovery distribution ``(p_target - q_draft)+ / Z``
    (the ``1/Z`` is a per-row constant that drops out of the argmax).
    Rows ``r >= KB`` (``k == K``) are BONUS rows — ``q`` is not read
    (residual = ``p``), giving an exact draw from ``p_target[K]``.
    Zero-residual entries score ``-inf`` and can never win, so the
    drawn support is exactly the positive-residual set.

    ``Q_IS_ONEHOT`` (constexpr — the dense specialization compiles the
    branch out entirely, so the dense path's generated code is unchanged)
    selects the INDEX-FORM point-mass proposal: instead of loading a
    materialized one-hot ``Q`` row, ``q`` is synthesized per lane as
    ``1.0 where offs == DRAFT[k, b] else 0.0`` — exactly the values the
    dense one-hot load would produce, so ``res = max(p - q, 0)`` is
    bit-identical while the ``(K, B, V)`` fp32 q tensor is never built
    or read (the 27B-c8 copy/index lever). ``DRAFT`` is only
    dereferenced on residual rows in one-hot mode.

    ``IN_LOG_SPACE`` (constexpr — the dense-probs specialization compiles
    the branch out, generated code unchanged) selects the FUSED softmax:
    ``P`` then holds temperature-scaled (optionally masked) LOGITS and the
    target prob is computed per lane as ``p = exp(logit - LSE[row])`` using
    the precomputed row ``logsumexp`` — so no dense ``(K+1, B, V)`` probs
    tensor is materialized and no separate full-vocab ``softmax`` launch
    runs before this kernel. A masked-out logit is ``-inf`` (top_k/top_p),
    giving ``p = 0`` exactly, and an out-of-range lane loads ``-inf`` too,
    so the residual support and the degenerate-fallback ``argmax(p)`` are
    identical to the probs path (``exp`` is monotone). Bit-for-bit the
    softmax differs from a materialized ``torch.softmax`` only by float32
    reduction order, which the residual sampler is lossless to
    (Leviathan-2023 Thm 1) and which cannot move the argmax draw.

    The Gumbel noise is generated ON THE FLY from Philox4x32-10 with the
    step seed as the key and ``(vocab_index, row, DRAW_OFFSET)`` on the
    counter lanes — no materialized ``(K+1, B, V)`` noise tensor, and a
    pure function of ``(seed, k, b, v)`` so every SPMD rank draws the
    byte-identical token. ``DRAW_OFFSET`` namespaces this draw class away
    from other Philox consumers keyed on the same seed (the decode
    sampler uses zero counter lanes 1-2).

    Alongside the Gumbel partial, each program tracks its chunk's plain
    ``argmax(p)`` (``PART_PVAL`` / ``PART_PIDX``) — the finishing
    reduction's fallback for a degenerate row whose residual is
    everywhere zero (draft ⊇ target support), matching the eager
    sampler's degenerate contract.

    Grid, chunking, and tie-break follow :func:`_gumbel_partial_kernel`:
    ``(N_ROWS * SPLIT,)`` programs, contiguous chunks, strictly-greater
    running max ⇒ lowest-index tie-break.
    """
    pid = tl.program_id(0)
    row = pid // SPLIT
    split_id = pid % SPLIT
    if row >= N_ROWS:
        return

    k = row // B
    b = row % B
    is_res = row < KB

    if PER_ROW_SEED:
        # Keyed-watermark mode: one seed per (depth, row) flat row, counter
        # lanes 1-2 zeroed below — the layout the model-free detector
        # recomputes (philox_uniform_host: counter (index, 0, 0, 0)).
        seed = tl.load(SEED_PTR + row)  # int64
    else:
        seed = tl.load(SEED_PTR)  # int64
    key_lo = (seed & 0xFFFFFFFF).to(tl.uint32)
    key_hi = ((seed >> 32) & 0xFFFFFFFF).to(tl.uint32)

    CHUNK = (VOCAB_SIZE + SPLIT - 1) // SPLIT
    start = split_id * CHUNK
    end = tl.minimum(start + CHUNK, VOCAB_SIZE)

    P_ROW = P + k * p_stride_k + b * p_stride_b
    Q_ROW = Q + k * q_stride_k + b * q_stride_b
    if Q_IS_ONEHOT:
        # Bonus rows never touch DRAFT (masked scalar load, no deref) —
        # same discipline as the dense path's Q_ROW loads. ``other=-1``
        # can never equal a vocab index, so a (never-read) bonus row's
        # synthesized q is all-zero, matching residual = p.
        draft_tok = tl.load(DRAFT + k * d_stride_k + b * d_stride_b, mask=is_res, other=-1).to(
            tl.int64
        )
    else:
        draft_tok = tl.full((), -1, tl.int64)  # unused in the dense specialization

    if IN_LOG_SPACE:
        # One row-normalizer load; ``p = exp(logit - lse_row)`` per lane
        # below reproduces ``softmax(P_ROW)`` without a materialized probs
        # tensor. ``row < N_ROWS`` is guaranteed (early return above).
        lse_row = tl.load(LSE + row).to(tl.float32)
    else:
        lse_row = tl.zeros((), dtype=tl.float32)  # unused in the probs specialization

    best_score = -float("inf")
    best_idx = tl.zeros((), dtype=tl.int64)
    best_pval = -float("inf")
    best_pidx = tl.zeros((), dtype=tl.int64)

    n_tiles = (CHUNK + BLOCK_SIZE - 1) // BLOCK_SIZE
    for t in range(0, n_tiles):
        offs = start + t * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
        mask = offs < end
        if IN_LOG_SPACE:
            # ``P`` holds scaled logits; out-of-range / masked lanes load
            # ``-inf`` so ``exp(logit - lse) == 0`` there (== softmax's 0).
            logit = tl.load(P_ROW + offs, mask=mask, other=-float("inf")).to(tl.float32)
            p = tl.exp(logit - lse_row)
        else:
            p = tl.load(P_ROW + offs, mask=mask, other=0.0).to(tl.float32)
        if Q_IS_ONEHOT:
            # Synthesized one-hot: 1.0 exactly at the drafted token of a
            # residual row, 0.0 elsewhere — the same values a dense
            # one-hot load returns (masked lanes read 0.0 there too).
            q = tl.where(mask & is_res & (offs.to(tl.int64) == draft_tok), 1.0, 0.0)
        else:
            # Bonus rows never touch Q (mask is all-false there, no deref).
            q = tl.load(Q_ROW + offs, mask=mask & is_res, other=0.0).to(tl.float32)
        res = tl.maximum(p - q, 0.0)

        c0 = offs.to(tl.uint32)
        if PER_ROW_SEED:
            # Keyed-watermark counter layout (index, 0, 0): the per-row
            # seeds carry the decorrelation, and the model-free detector
            # recomputes exactly this uniform from (seed, token_id).
            c1 = tl.zeros_like(c0)
            c2 = tl.zeros_like(c0)
        else:
            c1 = tl.zeros_like(c0) + row.to(tl.uint32)
            c2 = tl.zeros_like(c0) + DRAW_OFFSET
        u = _philox4x32_lane0(c0, c1, c2, key_lo, key_hi)
        gumbel = -tl.log(-tl.log(u))
        # log(0) = -inf (not NaN), so the where() cleanly kills the
        # zero-residual lanes without a clamp.
        score = tl.where(mask & (res > 0.0), tl.log(res) + gumbel, -float("inf"))

        tile_max = tl.max(score)
        tile_arg = tl.argmax(score, axis=0)
        take = tile_max > best_score
        best_idx = tl.where(take, (start + t * BLOCK_SIZE + tile_arg).to(tl.int64), best_idx)
        best_score = tl.where(take, tile_max, best_score)

        pval = tl.where(mask, p, -float("inf"))
        ptile_max = tl.max(pval)
        ptile_arg = tl.argmax(pval, axis=0)
        ptake = ptile_max > best_pval
        best_pidx = tl.where(ptake, (start + t * BLOCK_SIZE + ptile_arg).to(tl.int64), best_pidx)
        best_pval = tl.where(ptake, ptile_max, best_pval)

    tl.store(PART_SCORE + pid, best_score)
    tl.store(PART_IDX + pid, best_idx)
    tl.store(PART_PVAL + pid, best_pval)
    tl.store(PART_PIDX + pid, best_pidx)


@triton.jit(do_not_specialize=["SEED_PTR"])
def _gumbel_at_indices_kernel(
    IDX,  # (N_ROWS, C) int64 — global vocab index per candidate (pad = negative)
    SEED_PTR,  # (1,) int64 device — the rank-agreed step seed
    OUT,  # (N_ROWS, C) fp32 — Gumbel(0,1) noise per candidate
    N_ROWS,
    C,
    DRAW_OFFSET: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,
    PER_ROW_SEED: tl.constexpr = False,
):
    """Gumbel(0,1) noise AT arbitrary global vocab indices, one row/program.

    For candidate ``(row, c)`` with global vocab id ``v = IDX[row, c]``,
    writes ``-log(-log(u))`` where ``u`` is the SAME Philox4x32-10 draw the
    full-vocab recovery/bonus kernel (:func:`_residual_gumbel_partial_kernel`)
    computes at that token: counter lanes ``(c0=v, c1=row, c2=DRAW_OFFSET)``,
    key = the shared step seed. So the noise a compacted row sees at a
    candidate is byte-identical to the noise the gathered full-vocab path
    would have generated at the SAME token — the property that makes the
    shard-resident recovery/bonus draw match the gathered draw.

    ``row`` is the FLAT verify-row index ``k * B + b`` (the caller flattens
    ``(K+1, B, C)`` → ``((K+1)*B, C)``), matching the full-vocab kernel's
    ``row = k*B + b`` counter lane. A negative (pad) index still produces a
    well-defined noise value (uint32-cast wraps); pad candidates carry a
    ``-inf`` residual downstream and are never selected, so the value is
    inert.
    """
    row = tl.program_id(0)
    if row >= N_ROWS:
        return
    if PER_ROW_SEED:
        # Keyed-watermark mode: per-(depth, row) seed, zero counter lanes —
        # the layout the model-free detector recomputes.
        seed = tl.load(SEED_PTR + row)  # int64
    else:
        seed = tl.load(SEED_PTR)  # int64
    key_lo = (seed & 0xFFFFFFFF).to(tl.uint32)
    key_hi = ((seed >> 32) & 0xFFFFFFFF).to(tl.uint32)

    offs = tl.arange(0, BLOCK_SIZE)
    mask = offs < C
    v = tl.load(IDX + row * C + offs, mask=mask, other=0).to(tl.uint32)
    c0 = v
    if PER_ROW_SEED:
        c1 = tl.zeros_like(c0)
        c2 = tl.zeros_like(c0)
    else:
        c1 = tl.zeros_like(c0) + row.to(tl.uint32)
        c2 = tl.zeros_like(c0) + DRAW_OFFSET
    u = _philox4x32_lane0(c0, c1, c2, key_lo, key_hi)
    gumbel = -tl.log(-tl.log(u))
    tl.store(OUT + row * C + offs, gumbel, mask=mask)


@triton.jit
def _softmax_partials_kernel(
    MASKED,  # (N_ROWS, V) fp32 masked logits, unit V stride
    PART_MAX,  # (N_ROWS * SPLIT,) fp32 — per-chunk max
    PART_SUM,  # (N_ROWS * SPLIT,) fp32 — per-chunk Σ exp(x - chunk_max)
    N_ROWS,
    SPLIT,
    VOCAB_SIZE: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,
):
    """Per-chunk online-softmax partials: chunk max + chunk sum-exp
    (relative to the chunk max). Grid ``(N_ROWS * SPLIT,)``, contiguous
    chunks — the finishing host-side reduce combines them into the global
    ``(max, Z)`` per row."""
    pid = tl.program_id(0)
    row = pid // SPLIT
    split_id = pid % SPLIT
    if row >= N_ROWS:
        return
    CHUNK = (VOCAB_SIZE + SPLIT - 1) // SPLIT
    start = split_id * CHUNK
    end = tl.minimum(start + CHUNK, VOCAB_SIZE)
    ROW = MASKED + row * VOCAB_SIZE

    lmax = -float("inf")
    n_tiles = (CHUNK + BLOCK_SIZE - 1) // BLOCK_SIZE
    for t in range(0, n_tiles):
        offs = start + t * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
        mask = offs < end
        x = tl.load(ROW + offs, mask=mask, other=-float("inf")).to(tl.float32)
        lmax = tl.maximum(lmax, tl.max(x))
    lsum = 0.0
    for t in range(0, n_tiles):
        offs = start + t * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
        mask = offs < end
        x = tl.load(ROW + offs, mask=mask, other=-float("inf")).to(tl.float32)
        e = libdevice.exp(x - lmax)
        e = tl.where(mask & (x > -float("inf")), e, 0.0)
        lsum += tl.sum(e)
    tl.store(PART_MAX + pid, lmax)
    tl.store(PART_SUM + pid, lsum)


@triton.jit
def _minp_partials_kernel(
    MASKED,  # (N_ROWS, V) fp32
    ROWMAX,  # (N_ROWS,) fp32 — global row max
    ROWZ,  # (N_ROWS,) fp32 — global softmax denominator
    MINP,  # (N_ROWS,) fp32 — per-row min_p
    PART_MPSUM,  # (N_ROWS * SPLIT,) fp32 — per-chunk kept mass
    N_ROWS,
    SPLIT,
    VOCAB_SIZE: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,
):
    """Per-chunk kept-probability mass for min_p, probs-space (matching
    ``processors.min_p_mask``): keep ``probs ≥ min_p · max(probs)`` where
    ``max(probs) = div_rn(1, Z)`` (the global-max token is always kept by
    top-k / top-p). Rows with ``min_p == 0`` write mass 0 (unused)."""
    pid = tl.program_id(0)
    row = pid // SPLIT
    split_id = pid % SPLIT
    if row >= N_ROWS:
        return
    mp = tl.load(MINP + row)
    if mp <= 0.0:
        tl.store(PART_MPSUM + pid, 0.0)
        return
    M = tl.load(ROWMAX + row)
    Z = tl.load(ROWZ + row)
    thresh = mp * tl.math.div_rn(1.0, Z)
    CHUNK = (VOCAB_SIZE + SPLIT - 1) // SPLIT
    start = split_id * CHUNK
    end = tl.minimum(start + CHUNK, VOCAB_SIZE)
    ROW = MASKED + row * VOCAB_SIZE
    mpsum = 0.0
    n_tiles = (CHUNK + BLOCK_SIZE - 1) // BLOCK_SIZE
    for t in range(0, n_tiles):
        offs = start + t * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
        mask = offs < end
        x = tl.load(ROW + offs, mask=mask, other=-float("inf")).to(tl.float32)
        probs = tl.math.div_rn(libdevice.exp(x - M), Z)
        keep = (probs >= thresh) & mask & (x > -float("inf"))
        mpsum += tl.sum(tl.where(keep, probs, 0.0))
    tl.store(PART_MPSUM + pid, mpsum)


@triton.jit(do_not_specialize=["SEED_PTR", "N_ROWS", "SPLIT"])
def _qwrite_draw_partials_kernel(
    MASKED,  # (N_ROWS, V) fp32
    ROWMAX,  # (N_ROWS,) fp32
    ROWZ,  # (N_ROWS,) fp32
    MINP,  # (N_ROWS,) fp32
    MINP_SUM,  # (N_ROWS,) fp32 — kept mass (unused rows: ignored)
    SEED_PTR,  # (1,) int64 device step seed, or (N_ROWS,) keyed row seeds
    QOUT,  # (N_ROWS, V) fp32 — filtered distribution write-back
    QROWS,  # (N_ROWS,) int64 — QOUT row of each input row (HAS_QROWS)
    PART_SCORE,  # (N_ROWS * SPLIT,) fp32
    PART_IDX,  # (N_ROWS * SPLIT,) int64
    N_ROWS,
    SPLIT,
    MINP_ENABLED: tl.constexpr,
    DRAW_OFFSET: tl.constexpr,
    VOCAB_SIZE: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,
    PER_ROW_SEED: tl.constexpr = False,
    HAS_QROWS: tl.constexpr = False,
):
    """Write ``q`` and draw the token in ONE pass over the masked logits.

    ``q = div_rn(exp(x − max), Z)`` (min_p-renormalised per row when
    enabled + ``min_p > 0``); the draw is a counter-based Philox4x32-10
    Gumbel-max over ``log(q)`` keyed on ``(seed, row, DRAW_OFFSET)`` — the
    IDENTICAL noise + arithmetic ``gumbel_argmax_from_seed_ptr`` uses — with
    a strictly-greater running max (lowest-index tie-break). Contiguous
    chunks make the host finishing ``argmax`` inherit the lowest-index
    tie-break.

    ``PER_ROW_SEED`` selects the keyed-watermark noise instead: one seed per
    row with counter lanes 1-2 zeroed, the layout
    :func:`gumbel_argmax_from_seeds` and the model-free detector
    (``philox_uniform_host``) recompute. Same ``q``, same arithmetic — only
    the noise source differs, so the two modes share this one program rather
    than one masked-softmax tail per draw class."""
    pid = tl.program_id(0)
    row = pid // SPLIT
    split_id = pid % SPLIT
    if row >= N_ROWS:
        return
    if PER_ROW_SEED:
        seed = tl.load(SEED_PTR + row)
    else:
        seed = tl.load(SEED_PTR)
    key_lo = (seed & 0xFFFFFFFF).to(tl.uint32)
    key_hi = ((seed >> 32) & 0xFFFFFFFF).to(tl.uint32)
    M = tl.load(ROWMAX + row)
    Z = tl.load(ROWZ + row)
    minp_active = False
    thresh = 0.0
    mpsum = 1.0
    if MINP_ENABLED:
        mp = tl.load(MINP + row)
        minp_active = mp > 0.0
        if minp_active:
            thresh = mp * tl.math.div_rn(1.0, Z)
            mpsum = tl.load(MINP_SUM + row)
    CHUNK = (VOCAB_SIZE + SPLIT - 1) // SPLIT
    start = split_id * CHUNK
    end = tl.minimum(start + CHUNK, VOCAB_SIZE)
    ROW = MASKED + row * VOCAB_SIZE
    if HAS_QROWS:
        QROW = QOUT + tl.load(QROWS + row) * VOCAB_SIZE
    else:
        QROW = QOUT + row * VOCAB_SIZE

    best_score = -float("inf")
    best_idx = tl.zeros((), dtype=tl.int64)
    n_tiles = (CHUNK + BLOCK_SIZE - 1) // BLOCK_SIZE
    for t in range(0, n_tiles):
        offs = start + t * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
        mask = offs < end
        x = tl.load(ROW + offs, mask=mask, other=-float("inf")).to(tl.float32)
        finite = mask & (x > -float("inf"))
        probs = tl.math.div_rn(libdevice.exp(x - M), Z)
        # ``minp_active`` is a plain False unless ``MINP_ENABLED`` (constexpr)
        # AND the per-row ``min_p > 0``; both guards are needed so a min_p==0
        # row (or the min_p-disabled kernel) skips the renorm entirely.
        if MINP_ENABLED and minp_active:
            keep = (probs >= thresh) & finite
            probs = tl.where(keep, tl.math.div_rn(probs, mpsum), 0.0)
        probs = tl.where(finite, probs, 0.0)
        tl.store(QROW + offs, probs, mask=mask)

        c0 = offs.to(tl.uint32)
        if PER_ROW_SEED:
            c1 = tl.zeros_like(c0)
            c2 = tl.zeros_like(c0)
        else:
            c1 = tl.zeros_like(c0) + row.to(tl.uint32)
            c2 = tl.zeros_like(c0) + DRAW_OFFSET
        u = _philox4x32_lane0(c0, c1, c2, key_lo, key_hi)
        gumbel = -tl.log(-tl.log(u))
        logp = tl.log(probs)  # log(0) = -inf → excluded
        score = tl.where(finite & (probs > 0.0), logp + gumbel, -float("inf"))
        tile_max = tl.max(score)
        tile_arg = tl.argmax(score, axis=0)
        take = tile_max > best_score
        best_idx = tl.where(take, (start + t * BLOCK_SIZE + tile_arg).to(tl.int64), best_idx)
        best_score = tl.where(take, tile_max, best_score)
    tl.store(PART_SCORE + pid, best_score)
    tl.store(PART_IDX + pid, best_idx)


@triton.jit(do_not_specialize=["SPLIT"])
def _softmax_combine_kernel(
    PART_MAX,  # (N_ROWS, SPLIT) fp32 — per-chunk max
    PART_SUM,  # (N_ROWS, SPLIT) fp32 — per-chunk Σ exp(x - chunk_max)
    ROWMAX,  # (N_ROWS,) fp32 out — the row max
    WEIGHTED,  # (N_ROWS, SPLIT) fp32 out — chunk_sum · exp(chunk_max − row_max)
    SPLIT,
    BLOCK_S: tl.constexpr,
):
    """One row of the fused draw's ``(max, Z)`` combine, the terms aten sums.

    ``pm.amax(1)`` then ``part_sum * (pm - row_max).exp()`` in that chain's
    arithmetic: an exact max (NaN-propagating, as ``amax``), an fp32 ``sub.rn``,
    libdevice ``expf`` and a ``mul.rn``. The row SUM is left to aten over these
    terms, so ``Z`` keeps aten's reduction order."""
    row = tl.program_id(0).to(tl.int64)
    offs = tl.arange(0, BLOCK_S)
    mask = offs < SPLIT
    pm = tl.load(PART_MAX + row * SPLIT + offs, mask=mask, other=-float("inf"))
    m = tl.max(pm, axis=0)
    m = tl.where(tl.max((pm != pm).to(tl.int32), axis=0) > 0, float("nan"), m)
    tl.store(ROWMAX + row, m)
    ps = tl.load(PART_SUM + row * SPLIT + offs, mask=mask, other=0.0)
    tl.store(WEIGHTED + row * SPLIT + offs, ps * libdevice.exp(pm - m), mask=mask)


@triton.jit(do_not_specialize=["SPLIT", "STRIDE"])
def _draw_finish_kernel(
    PART_SCORE,  # (N_ROWS, SPLIT) fp32
    PART_IDX,  # (N_ROWS, SPLIT) int64
    TOKENS,  # (N_ROWS,) int64 out, row stride STRIDE
    SPLIT,
    STRIDE,
    BLOCK_S: tl.constexpr,
):
    """``part_idx.gather(1, part_score.argmax(1, keepdim=True))`` for one row.

    aten's argmax: the first maximum wins, and a NaN is greater than every
    number (the first NaN wins). One block-wide reduction, not a walk over
    ``SPLIT``, so a wide draw grid costs no serial tail."""
    row = tl.program_id(0).to(tl.int64)
    offs = tl.arange(0, BLOCK_S)
    live = offs < SPLIT
    v = tl.load(PART_SCORE + row * SPLIT + offs, mask=live, other=-float("inf"))
    nan = live & (v != v)
    m = tl.max(tl.where(nan, -float("inf"), v), axis=0)
    first_max = tl.min(tl.where(live & (v == m), offs, BLOCK_S), axis=0)
    first_nan = tl.min(tl.where(nan, offs, BLOCK_S), axis=0)
    arg = tl.where(first_nan < BLOCK_S, first_nan, first_max)
    tl.store(TOKENS + row * STRIDE, tl.load(PART_IDX + row * SPLIT + arg))
# ---- _spec_verify_kernel.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Device kernels for the fused stochastic verify tail; the host side is
:mod:`arbi_serve.sampler.spec_verify_triton`."""

from __future__ import annotations

from functools import lru_cache

#: Sort key of a candidate that is not kept (above every real key).
_NO_KEY = 1 << 30


@lru_cache(maxsize=1)
def kernels():
    """``(finish, count)`` Triton kernels, built on first use."""
    import triton
    import triton.language as tl
    from triton.language.extra.cuda import libdevice

    from arbi_serve.kernels.softmax_exact import tree_helpers
    from arbi_serve.sampler._gumbel_argmax_kernel import _philox4x32_lane0
    from arbi_serve.sampler._topc_kernel import _topc_scaled, _topc_threshold

    _tree32, _tree32_rows = tree_helpers()
    NO_KEY = tl.constexpr(_NO_KEY)

    @triton.jit
    def _draw_scores(offs, p, live, is_res, x_tok, k, b, Q, QSK, QSB, seed, r,
                     Q_DENSE: tl.constexpr, PER_ROW_SEED: tl.constexpr,
                     DRAW_OFFSET: tl.constexpr):  # fmt: skip
        """``_residual_gumbel_partial_kernel``'s score of each lane: log((p - q)+) + Gumbel."""
        if Q_DENSE:
            q = tl.load(
                Q + k.to(tl.int64) * QSK + b.to(tl.int64) * QSB + offs,
                mask=live & is_res,
                other=0.0,
            )
        else:
            q = tl.where(is_res & (offs.to(tl.int64) == x_tok), 1.0, 0.0)
        res = tl.maximum(p - q, 0.0)
        c0 = offs.to(tl.uint32)
        if PER_ROW_SEED:
            c1 = tl.zeros_like(c0)
            c2 = tl.zeros_like(c0)
        else:
            c1 = tl.zeros_like(c0) + r.to(tl.uint32)
            c2 = tl.zeros_like(c0) + DRAW_OFFSET
        key_lo = (seed & 0xFFFFFFFF).to(tl.uint32)
        key_hi = ((seed >> 32) & 0xFFFFFFFF).to(tl.uint32)
        u = _philox4x32_lane0(c0, c1, c2, key_lo, key_hi)
        gumbel = -tl.log(-tl.log(u))
        return tl.where(live & (res > 0.0), tl.log(res) + gumbel, -float("inf"))

    @triton.jit
    def _dense_row(ROW, INV, temp, thresh, m, row_max, greedy, is_res, x_tok, k, b,
                   Q, QSK, QSB, seed, r, VOCAB_SIZE: tl.constexpr, NVEC: tl.constexpr,
                   TAIL0: tl.constexpr, SCALE: tl.constexpr, Q_DENSE: tl.constexpr,
                   PER_ROW_SEED: tl.constexpr, DRAW_OFFSET: tl.constexpr):  # fmt: skip
        """``(token, softmax sum)`` from a walk of the whole row (the overflow path)."""
        lane = tl.arange(0, 1024)
        tok = tl.zeros((), tl.int64)
        s = tl.full((), 1.0, tl.float32)
        if greedy == 1:
            best = tl.full((), VOCAB_SIZE, tl.int32)
            for t in range(0, VOCAB_SIZE, 1024):
                offs = t + tl.arange(0, 1024)
                x = _topc_scaled(ROW, offs, offs < VOCAB_SIZE, INV, temp, SCALE)
                best = tl.minimum(best, tl.min(tl.where(x == row_max, offs, VOCAB_SIZE)))
            tok = best.to(tl.int64)
        else:
            # softmax_exact's order: thread t folds its vectors' four lanes, then the
            # scalar tail, then the warp and cross-warp trees; a dropped lane adds 0.
            j = tl.arange(0, 4)
            acc = tl.zeros([1024], tl.float32)
            for kk in range(0, NVEC):
                offs = 4 * (lane + 1024 * kk)[:, None] + j[None, :]
                x = _topc_scaled(ROW, offs, offs < VOCAB_SIZE, INV, temp, SCALE)
                if tl.max(tl.max(x, axis=1), axis=0) >= thresh:
                    e = tl.where(x >= thresh, libdevice.exp(x - m), 0.0)
                    ev, od = tl.split(tl.reshape(e, [1024, 2, 2]))
                    e0, e2 = tl.split(ev)
                    e1, e3 = tl.split(od)
                    acc = (((acc + e0) + e1) + e2) + e3
            for off in range(TAIL0, VOCAB_SIZE, 1024):
                idx = off + lane
                x = _topc_scaled(ROW, idx, idx < VOCAB_SIZE, INV, temp, SCALE)
                e = tl.where(x >= thresh, libdevice.exp(x - m), 0.0)
                acc = tl.where(idx < VOCAB_SIZE, acc + e, acc)
            s = _tree32(_tree32_rows(tl.reshape(acc, [32, 32]), 32))
            best_score = tl.full((), -float("inf"), tl.float32)
            best_idx = tl.zeros((), tl.int64)
            best_pval = tl.full((), -float("inf"), tl.float32)
            best_pidx = tl.zeros((), tl.int64)
            for t in range(0, VOCAB_SIZE, 1024):
                offs = t + tl.arange(0, 1024)
                live = offs < VOCAB_SIZE
                x = _topc_scaled(ROW, offs, live, INV, temp, SCALE)
                keep = live & (x >= thresh)
                if tl.max(keep.to(tl.int32)) > 0:
                    p = tl.where(keep, tl.math.div_rn(libdevice.exp(x - m), s), 0.0)
                    score = _draw_scores(offs, p, keep, is_res, x_tok, k, b, Q, QSK, QSB,
                                         seed, r, Q_DENSE, PER_ROW_SEED, DRAW_OFFSET)  # fmt: skip
                    tile_max = tl.max(score)
                    take = tile_max > best_score
                    best_idx = tl.where(take, (t + tl.argmax(score, axis=0)).to(tl.int64), best_idx)
                    best_score = tl.where(take, tile_max, best_score)
                    ptile_max = tl.max(p)
                    ptake = ptile_max > best_pval
                    best_pidx = tl.where(ptake, (t + tl.argmax(p, axis=0)).to(tl.int64), best_pidx)
                    best_pval = tl.where(ptake, ptile_max, best_pval)
            # An everywhere-zero residual commits argmax(p_target).
            tok = tl.where(best_score == -float("inf"), best_pidx, best_idx)
        return tok, s

    @triton.jit(
        do_not_specialize=["SK", "SB", "QSK", "QSB", "DSK", "USK", "B", "KB", "INV", "SEED"]
    )
    def _verify_finish(
        X,  # native verify logits; flat row r = k * B + b at X + k * SK + b * SB
        SK,
        SB,
        PART,  # (rows, SPLIT, CAP) fp32 level-1 top-CAP partials of the scaled rows
        PART_IDX,  # (rows, SPLIT, IDX_CAP) int32 candidate columns
        PART_CNT,  # (rows, SPLIT) int32 candidates per chunk
        KEPT,  # (rows, KEEP_MAX) int32 scratch: the kept columns, compacted in candidate order
        TOPK,  # (rows,) int64 (TOPK_ENABLED)
        TOPP,  # (rows,) fp32 (TOPP_ENABLED)
        INV,  # SCALE == 1: fp32 reciprocal temperature
        TEMPS,  # SCALE == 2: (B,) fp32 per-column temperature
        GREEDY,  # (B,) int32 point-mass-on-argmax columns (HAS_GREEDY)
        Q,  # (K, B, V) fp32 draft probs (Q_DENSE)
        QSK,
        QSB,
        DRAFT,  # (K, B) int64 drafted tokens, unit column stride
        DSK,
        U,  # (K, B) fp32 accept uniforms, unit column stride
        USK,
        SEED,  # (1,) int64 step seed, or (rows,) per-row keys (PER_ROW_SEED)
        TOK_OUT,  # (rows,) int64 recovery (k < K) / bonus (k == K) draw
        ACC_OUT,  # (rows,) int8 accept flag for k < K
        B,
        KB,
        VOCAB_SIZE: tl.constexpr,
        NVEC: tl.constexpr,
        TAIL0: tl.constexpr,
        SPLIT: tl.constexpr,
        SPLIT_BLOCK: tl.constexpr,
        CAP: tl.constexpr,
        PART_BLOCK: tl.constexpr,
        IDX_CAP: tl.constexpr,
        KEEP_MAX: tl.constexpr,
        CAND_BLOCK: tl.constexpr,
        TOPK_ENABLED: tl.constexpr,
        TOPP_ENABLED: tl.constexpr,
        SCALE: tl.constexpr,
        HAS_GREEDY: tl.constexpr,
        Q_DENSE: tl.constexpr,
        PER_ROW_SEED: tl.constexpr,
        DRAW_OFFSET: tl.constexpr,
    ):
        """One verify row: the mask cut, softmax_exact's sum, the accept test and the draw."""
        r = tl.program_id(0)
        k = r // B
        b = r % B
        is_res = r < KB
        ROW = X + k.to(tl.int64) * SK + b.to(tl.int64) * SB
        temp = 1.0
        if SCALE == 2:
            temp = tl.load(TEMPS + b)
        greedy = 0
        if HAS_GREEDY:
            greedy = tl.load(GREEDY + b).to(tl.int32)
        if PER_ROW_SEED:
            seed = tl.load(SEED + r)
        else:
            seed = tl.load(SEED)
        x_tok = tl.zeros((), tl.int64)
        if is_res:
            x_tok = tl.load(DRAFT + k * DSK + b).to(tl.int64)

        thresh, row_max, _handled = _topc_threshold(
            PART, PART, PART, PART, TOPK, TOPP, TOPP, r, 0.0,
            VOCAB_SIZE=VOCAB_SIZE, SPLIT=SPLIT, SPLIT_BLOCK=SPLIT_BLOCK, CAP=CAP,
            PART_BLOCK=PART_BLOCK, TOPK_ENABLED=TOPK_ENABLED, TOPP_ENABLED=TOPP_ENABLED,
            MINP_ENABLED=False, NUCLEUS=False,
        )  # fmt: skip
        # softmax_exact's row max: aten's thread max starts at the lowest finite float.
        m = tl.maximum(row_max, -3.4028234663852886e38)

        # The kept set from the candidates (each chunk's columns >= its CAP-th value),
        # unless the cut falls below a chunk's CAP-th value or a chunk that reaches
        # the cut had more ties at that value than IDX_CAP slots. Walked CAND_BLOCK
        # candidates at a time, the kept columns compacted into KEPT: the whole
        # candidate set held at once spills to local memory.
        n_kept = tl.zeros((), tl.int32)
        n_lost = tl.zeros((), tl.int32)
        g_tok = tl.full((), VOCAB_SIZE, tl.int32)
        for c0 in range(0, SPLIT * IDX_CAP, CAND_BLOCK):
            c = c0 + tl.arange(0, CAND_BLOCK)
            chunk = r * SPLIT + c // IDX_CAP
            cnt = tl.load(PART_CNT + chunk)
            valid = (c % IDX_CAP) < cnt
            lost = (tl.load(PART + chunk * CAP + CAP - 1) > thresh) | (
                (cnt > IDX_CAP) & (tl.load(PART + chunk * CAP) >= thresh)
            )
            n_lost += tl.sum(lost.to(tl.int32))
            v = tl.load(PART_IDX + r * (SPLIT * IDX_CAP) + c, mask=valid, other=0)
            xc = _topc_scaled(ROW, v, valid, INV, temp, SCALE)
            g_tok = tl.minimum(g_tok, tl.min(tl.where(valid & (xc == row_max), v, VOCAB_SIZE)))
            keep = valid & (xc >= thresh)
            slot = n_kept + tl.cumsum(keep.to(tl.int32), axis=0) - 1
            tl.store(KEPT + r * KEEP_MAX + slot, v, mask=keep & (slot < KEEP_MAX))
            n_kept += tl.sum(keep.to(tl.int32))
        sparse = (n_lost == 0) & (n_kept <= KEEP_MAX)

        if sparse:
            if greedy == 1:
                tok = g_tok.to(tl.int64)
                s = tl.full((), 1.0, tl.float32)
            else:
                tl.debug_barrier()  # KEPT's stores, visible to the whole program
                j = tl.arange(0, KEEP_MAX)
                live = j < n_kept
                v = tl.load(KEPT + r * KEEP_MAX + j, mask=live, other=0, cache_modifier=".cg")
                xc = _topc_scaled(ROW, v, live, INV, temp, SCALE)
                # Thread t of softmax_exact folds its columns in key order; adding a
                # kept column's term at its place in that order is the whole sum.
                # Key: (thread t, its fold position o), from which the column follows.
                q4 = v // 4
                vec = v < TAIL0
                t_of = tl.where(vec, q4 % 1024, (v - TAIL0) % 1024)
                o_of = tl.where(vec, (q4 // 1024) * 4 + v % 4, NVEC * 4 + (v - TAIL0) // 1024)
                key = tl.where(live, (t_of << 8) | o_of, NO_KEY)
                lane = tl.arange(0, 1024)
                acc = tl.zeros([1024], tl.float32)
                for _i in range(0, n_kept):
                    kmin = tl.min(key)
                    key = tl.where(key == kmin, NO_KEY, key)
                    t_i = kmin >> 8
                    o_i = kmin & 0xFF
                    col = tl.where(o_i < NVEC * 4, 4 * (t_i + 1024 * (o_i // 4)) + o_i % 4,
                                   TAIL0 + (o_i - NVEC * 4) * 1024 + t_i)  # fmt: skip
                    xi = _topc_scaled(ROW, col, True, INV, temp, SCALE)
                    acc = tl.where(lane == t_i, acc + libdevice.exp(xi - m), acc)
                s = _tree32(_tree32_rows(tl.reshape(acc, [32, 32]), 32))
                p = tl.where(live, tl.math.div_rn(libdevice.exp(xc - m), s), 0.0)
                score = _draw_scores(v, p, live, is_res, x_tok, k, b, Q, QSK, QSB, seed, r,
                                     Q_DENSE, PER_ROW_SEED, DRAW_OFFSET)  # fmt: skip
                best = tl.max(score)
                pbest = tl.max(p)
                # Lowest column on a tie; an everywhere-zero residual commits argmax(p).
                tok = tl.where(
                    best == -float("inf"),
                    tl.min(tl.where(live & (p == pbest), v, VOCAB_SIZE)),
                    tl.min(tl.where(score == best, v, VOCAB_SIZE)),
                ).to(tl.int64)
        else:
            tok, s = _dense_row(ROW, INV, temp, thresh, m, row_max, greedy, is_res, x_tok, k,
                                b, Q, QSK, QSB, seed, r, VOCAB_SIZE, NVEC, TAIL0, SCALE,
                                Q_DENSE, PER_ROW_SEED, DRAW_OFFSET)  # fmt: skip

        tl.store(TOK_OUT + r, tok)
        if is_res:
            if greedy == 1:
                p_x = tl.where(x_tok == tok, 1.0, 0.0)
            else:
                xv = _topc_scaled(ROW, x_tok, (x_tok >= 0) & (x_tok < VOCAB_SIZE), INV, temp, SCALE)
                p_x = tl.where(xv >= thresh, tl.math.div_rn(libdevice.exp(xv - m), s), 0.0)
            u_acc = tl.load(U + k * USK + b)
            if Q_DENSE:
                q_x = tl.load(Q + k.to(tl.int64) * QSK + b.to(tl.int64) * QSB + x_tok)
                accept = (u_acc * q_x) <= p_x
            else:
                accept = u_acc <= p_x
            tl.store(ACC_OUT + r, accept.to(tl.int8))

    @triton.jit(do_not_specialize=["K", "B"])
    def _verify_count(ACC, OUT, K, B):
        """First rejected slot per column, ``K`` when every slot accepts."""
        b = tl.program_id(0)
        count = K
        found = 0
        for k in range(0, K):
            first = (found == 0) & (tl.load(ACC + k * B + b) == 0)
            count = tl.where(first, k, count)
            found = tl.where(first, 1, found)
        tl.store(OUT + b, count.to(tl.int64))

    return _verify_finish, _verify_count
# ---- _topc_kernel.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Device kernels for the fanned-out top_k/top_p/min_p threshold mask.

Two launches, both gridded over ``(rows x vocab-chunk)`` so a ``B = 1``
decode row occupies every SM. :mod:`arbi_serve.sampler.topc_mask` holds the
host-side dispatch and the rationale; nothing here is imported directly.
"""

from __future__ import annotations

import triton
import triton.language as tl


@triton.jit
def _topc_scaled(ROW, offs, live, INV, temp, SCALE: tl.constexpr):
    """fp32 tile of ``ROW``: as stored, ``* INV`` (aten's scalar divide) or ``/ temp``; dead lanes -inf."""
    x = tl.load(ROW + offs, mask=live, other=0.0).to(tl.float32)
    if SCALE == 1:
        x = x * INV
    elif SCALE == 2:
        x = tl.math.div_rn(x, temp)
    return tl.where(live, x, -float("inf"))


@triton.jit(do_not_specialize=["SRC_SK", "SRC_SB", "SRC_B", "INV"])
def _topc_partials_kernel(
    LOGITS,  # (N_ROWS, VOCAB_SIZE) fp32, unit vocab stride
    PART,  # (N_ROWS, SPLIT, CAP) fp32 — per-chunk top-CAP, descending
    PART_MAX,  # (N_ROWS, SPLIT) fp32 — per-chunk max (WRITE_MASS only)
    PART_MASS,  # (N_ROWS, SPLIT) fp32 — per-chunk sum(exp(v - chunk max))
    SRC_SK,  # SCALE != 0: row ``k * SRC_B + b`` reads ``LOGITS + k * SRC_SK + b * SRC_SB``
    SRC_SB,
    SRC_B,
    INV,  # SCALE == 1: fp32 reciprocal temperature
    TEMPS,  # SCALE == 2: (SRC_B,) fp32 per-column temperature
    PART_IDX,  # (N_ROWS, SPLIT, IDX_CAP) int32 — chunk columns >= its CAP-th value
    PART_CNT,  # (N_ROWS, SPLIT) int32 — how many there were (may exceed IDX_CAP)
    VOCAB_SIZE: tl.constexpr,
    SPLIT: tl.constexpr,
    CHUNK: tl.constexpr,
    CAP: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,
    N_TILES: tl.constexpr,
    WRITE_MASS: tl.constexpr,
    SCALE: tl.constexpr = 0,
    IDX_CAP: tl.constexpr = 0,
):
    """Per-chunk exact top-``CAP`` — the only pass that reads all of ``V``.

    Grid is ``(N_ROWS * SPLIT,)``: program ``pid`` owns row ``pid // SPLIT``
    and the contiguous vocab chunk ``pid % SPLIT``, so a single decode row
    fans across ``SPLIT`` SMs instead of crawling one.

    A chunk wider than one tile is folded by a running merge — the top-``CAP``
    of ``(running top-CAP) || (this tile's top-CAP)`` is the top-``CAP`` of
    everything seen, by the same union argument the two levels rest on — so
    ``BLOCK_SIZE`` bounds the register footprint independently of how wide
    the vocabulary is. At the served width ``N_TILES == 1`` and the loop
    compiles away entirely.

    ``WRITE_MASS`` adds the chunk's softmax mass in its own max's units, which
    is what lets a nucleus be taken against the WHOLE row rather than against
    the candidates: a ``top_p`` with no ``top_k`` renormalises over every
    token, and no candidate set can supply that denominator. It rides this
    pass because the denominator needs exactly the bytes the selection is
    already reading — a separate mass pass would double the only full-``V``
    read the design has.
    """
    pid = tl.program_id(0)
    row_id = pid // SPLIT
    split_id = pid % SPLIT

    start = split_id * CHUNK
    end = tl.minimum(start + CHUNK, VOCAB_SIZE)
    if SCALE == 0:
        LOGITS_ROW = LOGITS + row_id * VOCAB_SIZE
        temp = 1.0
    else:
        col = row_id % SRC_B
        LOGITS_ROW = LOGITS + (row_id // SRC_B).to(tl.int64) * SRC_SK + col.to(tl.int64) * SRC_SB
        temp = 1.0
        if SCALE == 2:
            temp = tl.load(TEMPS + col)

    offs = start + tl.arange(0, BLOCK_SIZE)
    live = offs < end
    x = _topc_scaled(LOGITS_ROW, offs, live, INV, temp, SCALE)
    top = tl.topk(x, CAP)  # (CAP,) descending
    if WRITE_MASS:
        # Shifting by the chunk's OWN max keeps every ``exp`` inside fp32
        # range whatever the row's dynamic span; the level-2 reduction
        # rescales the chunk sums onto the row max, which is the standard
        # online-softmax regrouping and costs one multiply per chunk.
        cmax = tl.max(x)
        cmass = tl.sum(tl.where(live & (x > -float("inf")), tl.exp(x - cmax), 0.0))
    for t in range(1, N_TILES):
        offs = start + t * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
        live = offs < end
        x = _topc_scaled(LOGITS_ROW, offs, live, INV, temp, SCALE)
        # ``can_reorder``: the concatenation feeds a selection, which is
        # order-invariant in the VALUES it returns.
        top = tl.topk(tl.cat(top, tl.topk(x, CAP), can_reorder=True), CAP)
        if WRITE_MASS:
            nmax = tl.maximum(cmax, tl.max(x))
            # An all--inf tile leaves ``nmax`` at -inf, and ``exp(-inf - -inf)``
            # is NaN, so the rescale is gated on a finite max rather than
            # written as a bare multiply.
            rescale = tl.where(cmax > -float("inf"), tl.exp(cmax - nmax), 0.0)
            cmass = cmass * rescale + tl.sum(
                tl.where(live & (x > -float("inf")), tl.exp(x - nmax), 0.0)
            )
            cmax = nmax

    tl.store(PART + pid * CAP + tl.arange(0, CAP), top)
    if WRITE_MASS:
        tl.store(PART_MAX + pid, cmax)
        tl.store(PART_MASS + pid, cmass)
    if IDX_CAP > 0:
        # Columns of every value >= the chunk's CAP-th, in column order: a superset
        # of the chunk's share of any cut at or above the row's CAP-th value.
        cut = tl.min(top)
        n = tl.zeros((), tl.int32)
        for t in range(0, N_TILES):
            offs = start + t * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
            live = offs < end
            hit = live & (_topc_scaled(LOGITS_ROW, offs, live, INV, temp, SCALE) >= cut)
            pos = n + tl.cumsum(hit.to(tl.int32), axis=0) - 1
            tl.store(PART_IDX + pid * IDX_CAP + pos, offs, mask=hit & (pos < IDX_CAP))
            n += tl.sum(hit.to(tl.int32))
        tl.store(PART_CNT + pid, n)


@triton.jit
def _order_key(v):
    """fp32 -> uint32 whose unsigned order is the values' order."""
    u = v.to(tl.uint32, bitcast=True)
    # ``u ^ 0xFFFFFFFF`` is ``~u`` (the same xor); the interpreter's ``~`` rejects uint32.
    return tl.where((u >> 31) != 0, u ^ 0xFFFFFFFF, u | 0x80000000)


@triton.jit
def _radix_digit(key, prefix, remaining, SHIFT: tl.constexpr, FIRST: tl.constexpr, N: tl.constexpr):
    """One 8-bit step of the ``remaining``-th largest key under ``prefix``'s higher bits."""
    bins = tl.arange(0, 256)
    if FIRST:
        match = tl.full((N,), 1, tl.int1)
    else:
        match = (key >> (SHIFT + 8)) == (prefix >> (SHIFT + 8))
    digit = ((key >> SHIFT) & 255).to(tl.int32)
    hist = tl.histogram(tl.where(match, digit, 0), 256)
    hist = hist - tl.where(bins == 0, tl.sum((~match).to(tl.int32)), 0)
    suffix = tl.sum(hist) - tl.cumsum(hist, 0) + hist  # keys at or above each digit
    d = tl.max(tl.where(suffix >= remaining, bins, -1))
    remaining = remaining - tl.sum(tl.where(bins > d, hist, 0))
    return prefix | (d.to(tl.uint32) << SHIFT), remaining


@triton.jit
def _top_cap(pv, SCRATCH, N: tl.constexpr, CAP: tl.constexpr):
    """``tl.topk(pv, CAP)``: the CAP largest values, descending, as a multiset.

    A radix select finds the CAP-th largest key in four 8-bit histogram steps; the
    values above it are compacted into ``SCRATCH`` (column order), the rest of the
    CAP slots take the CAP-th value, and those CAP values are sorted. The multiset
    is the one ``tl.topk`` returns, so the sorted vector is the same (for rows
    without NaN), at a fraction of a sort over all ``N``.
    """
    key = _order_key(pv)
    prefix = tl.zeros((), tl.uint32)
    remaining = tl.zeros((), tl.int32) + CAP
    prefix, remaining = _radix_digit(key, prefix, remaining, 24, True, N)
    prefix, remaining = _radix_digit(key, prefix, remaining, 16, False, N)
    prefix, remaining = _radix_digit(key, prefix, remaining, 8, False, N)
    prefix, remaining = _radix_digit(key, prefix, remaining, 0, False, N)
    above = key > prefix
    tl.store(SCRATCH + tl.cumsum(above.to(tl.int32), 0) - 1, pv, mask=above)
    cap = tl.arange(0, CAP)
    kth = tl.max(tl.where(key == prefix, pv, -float("inf")))
    tl.store(
        SCRATCH + cap, tl.zeros((CAP,), tl.float32) + kth, mask=cap >= tl.sum(above.to(tl.int32))
    )
    tl.debug_barrier()
    return tl.sort(tl.load(SCRATCH + cap), descending=True)


@triton.jit
def _topc_threshold(
    PART,  # (N_ROWS, SPLIT, CAP) fp32 — the level-1 partials
    PART_MAX,  # (N_ROWS, SPLIT) fp32 — per-chunk max (NUCLEUS only)
    PART_MASS,  # (N_ROWS, SPLIT) fp32 — per-chunk mass (NUCLEUS only)
    SCRATCH,  # RADIX: (CAP,) fp32 — this program's own staging for the level-2 selection
    K,
    P,
    MP,
    row_id,
    MARGIN,  # relative slack the nucleus decision must clear to be served
    VOCAB_SIZE: tl.constexpr,
    SPLIT: tl.constexpr,
    SPLIT_BLOCK: tl.constexpr,
    CAP: tl.constexpr,
    PART_BLOCK: tl.constexpr,
    TOPK_ENABLED: tl.constexpr,
    TOPP_ENABLED: tl.constexpr,
    MINP_ENABLED: tl.constexpr,
    NUCLEUS: tl.constexpr,
    RADIX: tl.constexpr = False,
):
    """Row keep-threshold ``T`` and row max, from the level-1 partials.

    The union of the per-chunk top-``CAP`` sets contains the row's global
    top-``CAP`` (a chunk can contribute at most ``CAP`` members to it), so
    one more ``tl.topk`` over the ``SPLIT * CAP`` partials is the EXACT
    global top-``CAP`` — no approximation anywhere in the selection.

    The whole filter chain then collapses to a single scalar: top_k, top_p
    and min_p each cut the row at a value, ``keep iff logit >= T`` with
    ``T`` the largest of the three cuts. Each cut is placed AT a real logit
    value rather than strictly between two, which is what makes the kept
    set match the pivot kernel's on an exact tie: both keep the whole tie
    group at the cut.

    Cheap enough (a ``CAP``-wide reduction over one ``PART_BLOCK`` tile)
    that every masking program recomputes it rather than reading it from a
    grid-``(N_ROWS,)`` kernel — which would reintroduce the single-CTA step
    this whole design exists to remove.

    ``NUCLEUS`` covers the row shape a candidate set cannot bound on its own:
    ``top_p`` active with ``top_k`` DISABLED, where the nucleus renormalises
    over the whole vocabulary and may run past the capacity. Two things make
    it exact rather than approximate. The denominator comes from the per-chunk
    masses, so it is the row's true softmax normaliser and not the candidates'
    — and the row is SERVED only when the candidates provably contain the
    boundary, with margin. ``handled = 0`` says they do not, and the caller's
    escalation re-derives that row from the row itself.

    The second return, ``handled``, is what keeps this honest under fp32. The
    boundary is where a cumulative mass crosses ``p``; two implementations
    summing the same terms in different orders disagree about that crossing
    when the boundary token's own mass is comparable to the summation error.
    ``MARGIN`` is the relative slack the crossing must clear on BOTH sides —
    below it, no arithmetic that differs by less than ``MARGIN`` can pick a
    different boundary, so the served kept set is the same set the row-serial
    search would have produced, and above it the row is not served at all.
    """
    poffs = tl.arange(0, PART_BLOCK)
    pmask = poffs < SPLIT * CAP
    pv = tl.load(PART + row_id * (SPLIT * CAP) + poffs, mask=pmask, other=-float("inf"))
    if RADIX:  # (CAP,) descending — the row's global top-CAP
        top = _top_cap(pv, SCRATCH, PART_BLOCK, CAP)
    else:
        top = tl.topk(pv, CAP)
    row_max = tl.max(top)
    row_mass = 0.0
    if NUCLEUS:
        soffs = tl.arange(0, SPLIT_BLOCK)
        smask = soffs < SPLIT
        cmax = tl.load(PART_MAX + row_id * SPLIT + soffs, mask=smask, other=-float("inf"))
        cmass = tl.load(PART_MASS + row_id * SPLIT + soffs, mask=smask, other=0.0)
        row_mass = tl.sum(
            tl.where(smask & (cmax > -float("inf")), cmass * tl.exp(cmax - row_max), 0.0)
        )
    thresh, handled = _topc_cut(
        top,
        row_max,
        row_mass,
        K,
        P,
        MP,
        row_id,
        MARGIN,
        VOCAB_SIZE=VOCAB_SIZE,
        CAP=CAP,
        TOPK_ENABLED=TOPK_ENABLED,
        TOPP_ENABLED=TOPP_ENABLED,
        MINP_ENABLED=MINP_ENABLED,
        NUCLEUS=NUCLEUS,
    )
    return thresh, row_max, handled


@triton.jit
def _topc_cut(
    top,  # (CAP,) fp32 — a row's top-CAP logits, descending
    row_max,
    row_mass,  # the row's softmax mass in ``row_max`` units (NUCLEUS only)
    K,
    P,
    MP,
    row_id,
    MARGIN,
    VOCAB_SIZE: tl.constexpr,
    CAP: tl.constexpr,
    TOPK_ENABLED: tl.constexpr,
    TOPP_ENABLED: tl.constexpr,
    MINP_ENABLED: tl.constexpr,
    NUCLEUS: tl.constexpr,
):
    """``(T, handled)``: the keep threshold the filter chain sets on a descending top-CAP vector."""
    rank = tl.arange(0, CAP)
    thresh = -float("inf")
    keep_k = top > -float("inf")
    topk_live = 0
    handled = 1
    if TOPK_ENABLED:
        k = tl.load(K + row_id).to(tl.int32)
        # ``k >= VOCAB_SIZE`` is the DISABLED encoding, not a cap of the
        # whole vocab — the same guard the pivot kernel opens with. Without
        # it a disabled row would be cut at the capacity-th logit.
        if k < VOCAB_SIZE:
            topk_live = 1
            kk = tl.minimum(tl.maximum(k, 1), CAP)
            # The k-th largest value. Below it nothing survives; AT it the
            # whole tie group does, which is the pivot kernel's behaviour.
            t_k = tl.sum(tl.where(rank == kk - 1, top, 0.0))
            keep_k = top >= t_k
            thresh = tl.maximum(thresh, t_k)

    if TOPP_ENABLED:
        p = tl.load(P + row_id)
        # An all--inf row has no finite max to renormalise against; it also
        # has nothing to keep, so leave it uncut rather than divide by zero.
        if p < 1.0 and row_max > -float("inf"):
            # Nucleus over the top_k survivors, renormalised — the same
            # "smallest prefix whose cumulative mass reaches p" rule, read
            # off a descending vector instead of searched for by pivot.
            e = tl.where(keep_k, tl.exp(top - row_max), 0.0)
            cand_mass = tl.sum(e)
            # A live top_k has already truncated the distribution, so its
            # survivors ARE the denominator; a disabled one renormalises over
            # the whole row, which only the per-chunk masses can supply.
            denom = cand_mass
            if NUCLEUS:
                denom = tl.where(topk_live == 1, cand_mass, row_mass)
            probs = e / denom
            exclusive = tl.cumsum(probs, axis=0) - probs
            keep_p = keep_k & (exclusive < p)
            t_p = tl.min(tl.where(keep_p, top, float("inf")))
            thresh = tl.maximum(thresh, t_p)
            if NUCLEUS and topk_live == 0:
                # Mass kept AT the cut and mass kept strictly above it.
                # The cut is right when the first reaches the target and
                # the second does not; it is SERVABLE when both verdicts
                # clear the slack, because then no summation order that
                # differs by less than the slack can move the cut.
                target = p * denom
                slack = MARGIN * denom
                at = tl.sum(tl.where(top >= t_p, e, 0.0))
                above = tl.sum(tl.where(top > t_p, e, 0.0))
                ok = (
                    (cand_mass >= target + slack)
                    & (at >= target + slack)
                    & (above + slack <= target)
                )
                handled = tl.where(ok, 1, 0)

    if MINP_ENABLED:
        mp = tl.load(MP + row_id).to(tl.float32)
        if mp > 0.0 and row_max > -float("inf"):
            # keep iff logit >= max + log(min_p) — the logit-space rewrite
            # the eager chain and the pivot kernel both use.
            thresh = tl.maximum(thresh, row_max + tl.log(mp))

    # An unservable row must arrive at the escalation UNTOUCHED: the search it
    # runs there reads the row's own mass, so a partial cut here would move
    # the denominator and answer a different question.
    thresh = tl.where(handled == 1, thresh, -float("inf"))
    return thresh, handled


@triton.jit
def _topc_mask_kernel(
    LOGITS,  # (N_ROWS, VOCAB_SIZE) fp32 — masked IN PLACE
    PART,  # (N_ROWS, SPLIT, CAP) fp32
    PART_MAX,  # (N_ROWS, SPLIT) fp32 — per-chunk max (NUCLEUS only)
    PART_MASS,  # (N_ROWS, SPLIT) fp32 — per-chunk mass (NUCLEUS only)
    SCRATCH,  # (N_ROWS * SPLIT, CAP) fp32 — one level-2 staging row per program
    K,
    P,
    MP,
    PART_SUM,  # (N_ROWS * SPLIT,) fp32 — per-chunk sum(exp(logit - row_max))
    OUT_MAX,  # (N_ROWS,) fp32 — the row max, for the host-side LSE finish
    OUT_P,  # (N_ROWS,) fp32 — residual top_p for the escalation (NUCLEUS only)
    MARGIN,
    MASK_VALUE: tl.constexpr,
    VOCAB_SIZE: tl.constexpr,
    SPLIT: tl.constexpr,
    SPLIT_BLOCK: tl.constexpr,
    CHUNK: tl.constexpr,
    CAP: tl.constexpr,
    PART_BLOCK: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,
    N_TILES: tl.constexpr,
    TOPK_ENABLED: tl.constexpr,
    TOPP_ENABLED: tl.constexpr,
    MINP_ENABLED: tl.constexpr,
    NUCLEUS: tl.constexpr,
    WRITE_LSE: tl.constexpr,
):
    """Apply the row threshold to one vocab chunk; optionally sum for the LSE.

    Same ``(N_ROWS * SPLIT,)`` grid as the partials pass. Only the DROPPED
    lanes are written — kept lanes already hold their original fp32 value,
    so a kept logit is bit-identical to its input by construction.

    Under ``NUCLEUS`` the kernel also publishes ``OUT_P``: the ``top_p`` each
    row still owes. A served row owes nothing and gets ``1.0`` — the DISABLED
    encoding — so the escalation launch that follows walks straight past it,
    and an unservable row gets its ``top_p`` back unchanged and untouched
    logits to apply it to. Routing by a DEVICE value is what keeps the pair
    capturable: the launch shapes never move, so the same recorded graph
    serves whatever the next ``copy_()`` puts in the parameter buffers.
    """
    pid = tl.program_id(0)
    row_id = pid // SPLIT
    split_id = pid % SPLIT

    thresh, row_max, handled = _topc_threshold(
        PART,
        PART_MAX,
        PART_MASS,
        SCRATCH + pid * CAP,
        K,
        P,
        MP,
        row_id,
        MARGIN,
        VOCAB_SIZE=VOCAB_SIZE,
        SPLIT=SPLIT,
        SPLIT_BLOCK=SPLIT_BLOCK,
        CAP=CAP,
        PART_BLOCK=PART_BLOCK,
        TOPK_ENABLED=TOPK_ENABLED,
        TOPP_ENABLED=TOPP_ENABLED,
        MINP_ENABLED=MINP_ENABLED,
        NUCLEUS=NUCLEUS,
        RADIX=True,
    )
    if NUCLEUS and split_id == 0:
        p_owed = tl.load(P + row_id) if TOPP_ENABLED else 1.0
        tl.store(OUT_P + row_id, tl.where(handled == 1, 1.0, p_owed))

    start = split_id * CHUNK
    end = tl.minimum(start + CHUNK, VOCAB_SIZE)
    LOGITS_ROW = LOGITS + row_id * VOCAB_SIZE
    masked = tl.full((BLOCK_SIZE,), MASK_VALUE, tl.float32)

    sum_exp = 0.0
    for t in range(0, N_TILES):
        offs = start + t * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
        mask = offs < end
        ptr = LOGITS_ROW + offs
        x = tl.load(ptr, mask=mask, other=-float("inf")).to(tl.float32)
        keep = x >= thresh
        # Only the DROPPED lanes are written: a kept logit is then bit-identical
        # to its input by construction, not by careful arithmetic.
        tl.store(ptr, masked, mask=mask & ~keep)
        if WRITE_LSE:
            sum_exp += tl.sum(tl.where(mask & keep, tl.exp(x - row_max), 0.0))

    if WRITE_LSE:
        tl.store(PART_SUM + pid, sum_exp)
        if split_id == 0:
            tl.store(OUT_MAX + row_id, row_max)
# ---- _topk_exact.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Exact repair when the top-k heuristic cannot prove its boundary."""

import triton
import triton.language as tl

from arbi_serve.sampler._topp_exact import _f32_to_ordered_key, _ordered_key_to_f32


@triton.jit
def _exact_topk_pivot(PTR, n, n_tiles, k, hi_value, BLOCK: tl.constexpr):
    """Strict pivot below the kth value, plus the retained group's statistics.

    A float midpoint can never admit a tie at the search's lower bound.
    Integer-key bisection instead terminates at a representable value. The
    count excluding the smallest retained tie group proves an early exit;
    common minimum-boundary ties finish in the initial pass.
    """
    minimum = float("inf")
    total = tl.full((), 0, tl.uint32)
    minimum_count = tl.full((), 0, tl.uint32)
    for tile in range(n_tiles):
        col = tile * BLOCK + tl.arange(0, BLOCK)
        value = tl.load(PTR + col, col < n, other=-float("inf")).to(tl.float32)
        valid = (col < n) & (value > -float("inf"))
        tile_min = tl.min(tl.where(valid, value, float("inf")), 0)
        tile_count = tl.sum((valid & (value == tile_min)).to(tl.uint32), 0)
        minimum_count = tl.where(
            tile_min < minimum,
            tile_count,
            minimum_count + tl.where(tile_min == minimum, tile_count, 0),
        )
        minimum = tl.minimum(minimum, tile_min)
        total += tl.sum(valid.to(tl.uint32), 0)
    boundary = minimum
    count = total
    tie_count = minimum_count
    done = (total >= k) & (total - minimum_count < k)
    lo = _f32_to_ordered_key(minimum)
    hi = _f32_to_ordered_key(hi_value)
    while (done == 0) & (lo < hi):
        mid = lo + (hi - lo + 1) // 2
        threshold = _ordered_key_to_f32(mid)
        count_mid = tl.full((), 0, tl.uint32)
        min_kept = float("inf")
        min_count = tl.full((), 0, tl.uint32)
        for tile in range(n_tiles):
            col = tile * BLOCK + tl.arange(0, BLOCK)
            value = tl.load(PTR + col, col < n, other=-float("inf")).to(tl.float32)
            keep = (col < n) & (value >= threshold) & (value > -float("inf"))
            tile_min = tl.min(tl.where(keep, value, float("inf")), 0)
            tile_count = tl.sum((keep & (value == tile_min)).to(tl.uint32), 0)
            min_count = tl.where(
                tile_min < min_kept,
                tile_count,
                min_count + tl.where(tile_min == min_kept, tile_count, 0),
            )
            min_kept = tl.minimum(min_kept, tile_min)
            count_mid += tl.sum(keep.to(tl.uint32), 0)
        if count_mid >= k:
            lo = mid
            boundary = min_kept
            count = count_mid
            tie_count = min_count
            done = count_mid - min_count < k
        else:
            hi = mid - 1
    # The last successful threshold retains the boundary group even when
    # bisection ends without its early-exit proof firing.
    key = _f32_to_ordered_key(boundary)
    key = tl.where(boundary == 0.0, tl.full((), 0x7FFFFFFF, tl.uint32), key)
    return _ordered_key_to_f32(key - 1), count, boundary, tie_count
# ---- _topk_topp_kernel.py ----
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Fused Top-K + Top-P Triton ``@jit`` kernels — vendored from vLLM.

The device-side kernels for the combined top-k / top-p sampler live here;
:mod:`arbi_serve.sampler.topk_topp_triton` holds the host-side dispatch,
caches, and the public ``apply_top_k_top_p_triton`` /
``sample_top_k_top_p_triton`` wrappers, keeping each file small.
See that module's docstring for the full vendoring rationale, the
arbi-serve epilogues (``SAMPLE`` / ``MINP_ENABLED`` / ``WRITE_LSE``) and
provenance. Nothing here is re-exported directly; import the wrappers.
"""

from __future__ import annotations

import triton
import triton.language as tl

from arbi_serve.sampler._topk_exact import _exact_topk_pivot
from arbi_serve.sampler._topp_exact import _nucleus_pivot


@triton.jit
def _update_min_larger_stats(data, above_mask, min_larger, num_min_larger, sentinel):
    """Update running (min, count) of values above a pivot across tiles."""
    tile_min = tl.min(tl.where(above_mask, data, sentinel))
    tile_eq = above_mask & (data == tile_min)
    tile_cnt = tl.sum(tile_eq)
    is_new = tile_min < min_larger
    is_same = tile_min == min_larger
    num_min_larger = tl.where(is_new, tile_cnt, num_min_larger + tile_cnt * is_same)
    min_larger = tl.minimum(min_larger, tile_min)
    return min_larger, num_min_larger


@triton.jit
def _topk_topp_kernel(
    LOGITS,
    BUFFER,
    PERCENTILE_TO_STD_TABLE,
    NORMAL_CDF_TO_SIGMA_TABLE,
    K,
    P,
    MP,
    NOISE,
    OUT_TOKENS,
    OUT_LSE,
    BATCH_SIZE,
    VOCAB_SIZE: tl.constexpr,
    MASK_VALUE: tl.constexpr,
    BLOCK_SIZE: tl.constexpr,
    BLOCK_SIZE_TRUNC: tl.constexpr,
    TOPK_ENABLED: tl.constexpr,
    TOPP_ENABLED: tl.constexpr,
    MINP_ENABLED: tl.constexpr,
    SAMPLE: tl.constexpr,
    WRITE_LSE: tl.constexpr,
    NUCLEUS_WINDOW: tl.constexpr = 12.0,
):
    NUM_TILES: tl.constexpr = (VOCAB_SIZE + BLOCK_SIZE - 1) // BLOCK_SIZE
    pid = tl.program_id(0)
    num_programs = tl.num_programs(0)
    for row_id in tl.range(pid, BATCH_SIZE, num_programs):
        LOGITS_ROW = LOGITS + row_id * VOCAB_SIZE
        BUFFER_ROW = BUFFER + pid * VOCAB_SIZE

        final_pivot = -float("inf")
        duplicate_logit = float("inf")
        num_duplicate_logit = tl.zeros((), dtype=tl.uint32)
        num_keep = tl.zeros((), dtype=tl.uint32)
        num_kept = tl.zeros((), dtype=tl.uint32)

        max_logit = -float("inf")
        min_logit = float("inf")

        if TOPK_ENABLED:
            k = tl.load(K + row_id)
            if k < VOCAB_SIZE:
                # Zeroth pass: Compute avg and std from a sample block
                offs = tl.arange(0, BLOCK_SIZE)
                mask_n = offs < VOCAB_SIZE
                logits_blk0 = tl.load(LOGITS_ROW + offs, mask=mask_n, other=-float("inf")).to(
                    tl.float32
                )
                finite_mask = (logits_blk0 > -float("inf")) & mask_n
                num_finite = tl.sum(finite_mask)
                finite_logits = tl.where(finite_mask, logits_blk0, 0.0)
                avg_logit = tl.where(num_finite > 0, tl.sum(finite_logits) / num_finite, 0.0)
                sq_avg_logit = tl.where(
                    num_finite > 0,
                    tl.sum(finite_logits * finite_logits) / num_finite,
                    0.0,
                )
                std_logit = tl.sqrt(tl.maximum(sq_avg_logit - avg_logit * avg_logit, 0.0))

                percentile = tl.cast(k / VOCAB_SIZE * 200, tl.uint32)
                percentile = tl.minimum(percentile, 199)
                sigma = tl.load(PERCENTILE_TO_STD_TABLE + percentile)
                sigma = sigma + tl.abs(sigma) * -0.15
                outlier_pivot = avg_logit + std_logit * sigma
                num_outliers = tl.zeros((), dtype=tl.uint32)

                num_finite_total = tl.zeros((), dtype=tl.uint32)
                for i in range(0, NUM_TILES):
                    offs_n = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
                    mask_n = offs_n < VOCAB_SIZE
                    logits_blk = tl.load(LOGITS_ROW + offs_n, mask=mask_n, other=-float("inf")).to(
                        tl.float32
                    )

                    max_logit = tl.maximum(max_logit, tl.max(logits_blk))
                    finite_blk_mask = logits_blk > -float("inf")
                    finite_blk = tl.where(finite_blk_mask, logits_blk, float("inf"))
                    min_logit = tl.minimum(min_logit, tl.min(finite_blk))
                    num_finite_total += tl.sum(finite_blk_mask & mask_n)

                    outlier_mask = (logits_blk > outlier_pivot) & mask_n
                    cumulative_pos = tl.cast(tl.cumsum(outlier_mask) - 1 + num_outliers, tl.int32)
                    num_outliers += tl.sum(outlier_mask)
                    write_pos = tl.where(outlier_mask, cumulative_pos, -1)
                    tl.store(BUFFER_ROW + write_pos, logits_blk, mask=outlier_mask)
                # The searches below read the compacted outliers back with the
                # BLOCK_SIZE_TRUNC layout, across threads: barrier first (see
                # the top_p compaction).
                tl.debug_barrier()

                min_logit = tl.minimum(min_logit, max_logit)

                # Second passes: Ternary search for pivots
                num_iters = 0
                k_pivot = float("inf")
                k_pivots_num = tl.zeros((), dtype=tl.uint32)
                min_larger = float("inf")
                num_min_larger = tl.zeros((), dtype=tl.uint32)
                if num_outliers > k:
                    max_range = max_logit
                    min_range = outlier_pivot
                    search_range = tl.cast(num_outliers, tl.int32)
                    search_iters = tl.cast(
                        (num_outliers + BLOCK_SIZE_TRUNC - 1) // BLOCK_SIZE_TRUNC,
                        tl.int32,
                    )
                    found_pivot = 0
                    while found_pivot == 0:
                        k_pivot_0 = (max_range - min_range) * 1.0 / 3.0 + min_range
                        k_pivots_num_0 = tl.zeros((), dtype=tl.uint32)
                        min_larger_0 = float("inf")
                        num_min_larger_0 = tl.zeros((), dtype=tl.uint32)

                        k_pivot_1 = (max_range - min_range) * 2.0 / 3.0 + min_range
                        k_pivots_num_1 = tl.zeros((), dtype=tl.uint32)
                        min_larger_1 = float("inf")
                        num_min_larger_1 = tl.zeros((), dtype=tl.uint32)

                        for i in range(0, search_iters):
                            offs_n = i * BLOCK_SIZE_TRUNC + tl.arange(0, BLOCK_SIZE_TRUNC)
                            mask_n_2 = offs_n < search_range
                            logits_blk2 = tl.load(
                                BUFFER_ROW + offs_n, mask=mask_n_2, other=-float("inf")
                            )

                            above_0 = logits_blk2 > k_pivot_0
                            above_1 = logits_blk2 > k_pivot_1
                            k_pivots_num_0 += tl.sum(above_0)
                            k_pivots_num_1 += tl.sum(above_1)

                            min_larger_0, num_min_larger_0 = _update_min_larger_stats(
                                logits_blk2,
                                above_0,
                                min_larger_0,
                                num_min_larger_0,
                                float("inf"),
                            )
                            min_larger_1, num_min_larger_1 = _update_min_larger_stats(
                                logits_blk2,
                                above_1,
                                min_larger_1,
                                num_min_larger_1,
                                float("inf"),
                            )

                        if k_pivots_num_0 >= k and k_pivots_num_0 - num_min_larger_0 < k:
                            k_pivot = k_pivot_0
                            k_pivots_num = k_pivots_num_0
                            min_larger = min_larger_0
                            num_min_larger = num_min_larger_0
                            found_pivot = 1
                        if k_pivots_num_1 >= k and k_pivots_num_1 - num_min_larger_1 < k:
                            k_pivot = k_pivot_1
                            k_pivots_num = k_pivots_num_1
                            min_larger = min_larger_1
                            num_min_larger = num_min_larger_1
                            found_pivot = 1

                        if k_pivots_num_1 > k:
                            min_range = k_pivot_1
                        elif k_pivots_num_0 > k:
                            min_range = k_pivot_0

                        if k_pivots_num_0 < k:
                            max_range = k_pivot_0
                        elif k_pivots_num_1 < k:
                            max_range = k_pivot_1

                        num_iters += 1
                        if found_pivot == 0 and (
                            num_iters >= 18 or tl.abs(min_range - max_range) < 1e-9
                        ):
                            k_pivot, k_pivots_num, min_larger, num_min_larger = _exact_topk_pivot(
                                BUFFER_ROW,
                                search_range,
                                search_iters,
                                k,
                                max_logit,
                                BLOCK=BLOCK_SIZE_TRUNC,
                            )
                            found_pivot = 1
                else:
                    max_range = max_logit
                    min_range = min_logit
                    found_pivot = 0
                    while found_pivot == 0:
                        k_pivot_0 = (max_range - min_range) * 1.0 / 4.0 + min_range
                        k_pivots_num_0 = tl.zeros((), dtype=tl.uint32)
                        min_larger_0 = float("inf")
                        num_min_larger_0 = tl.zeros((), dtype=tl.uint32)

                        k_pivot_1 = (max_range - min_range) * 2.0 / 4.0 + min_range
                        k_pivots_num_1 = tl.zeros((), dtype=tl.uint32)
                        min_larger_1 = float("inf")
                        num_min_larger_1 = tl.zeros((), dtype=tl.uint32)

                        for i in range(0, NUM_TILES):
                            offs_n = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
                            mask_n = offs_n < VOCAB_SIZE
                            logits_blk2 = tl.load(
                                LOGITS_ROW + offs_n, mask=mask_n, other=-float("inf")
                            )

                            above_0 = logits_blk2 > k_pivot_0
                            above_1 = logits_blk2 > k_pivot_1
                            k_pivots_num_0 += tl.sum(above_0)
                            k_pivots_num_1 += tl.sum(above_1)

                            min_larger_0, num_min_larger_0 = _update_min_larger_stats(
                                logits_blk2,
                                above_0,
                                min_larger_0,
                                num_min_larger_0,
                                float("inf"),
                            )
                            min_larger_1, num_min_larger_1 = _update_min_larger_stats(
                                logits_blk2,
                                above_1,
                                min_larger_1,
                                num_min_larger_1,
                                float("inf"),
                            )

                        if k_pivots_num_0 >= k and k_pivots_num_0 - num_min_larger_0 < k:
                            k_pivot = k_pivot_0
                            k_pivots_num = k_pivots_num_0
                            min_larger = min_larger_0
                            num_min_larger = num_min_larger_0
                            found_pivot = 1
                        if k_pivots_num_1 >= k and k_pivots_num_1 - num_min_larger_1 < k:
                            k_pivot = k_pivot_1
                            k_pivots_num = k_pivots_num_1
                            min_larger = min_larger_1
                            num_min_larger = num_min_larger_1
                            found_pivot = 1

                        if k_pivots_num_1 > k:
                            min_range = k_pivot_1
                        elif k_pivots_num_0 > k:
                            min_range = k_pivot_0

                        if k_pivots_num_0 < k:
                            max_range = k_pivot_0
                        elif k_pivots_num_1 < k:
                            max_range = k_pivot_1

                        num_iters += 1
                        if found_pivot == 0 and (
                            num_iters >= 18 or tl.abs(min_range - max_range) < 1e-9
                        ):
                            k_pivot, k_pivots_num, min_larger, num_min_larger = _exact_topk_pivot(
                                LOGITS_ROW,
                                VOCAB_SIZE,
                                NUM_TILES,
                                k,
                                max_logit,
                                BLOCK=BLOCK_SIZE,
                            )
                            found_pivot = 1

                duplicate_logit = min_larger
                num_duplicate_logit = num_min_larger
                num_keep = num_duplicate_logit - (k_pivots_num - k)
                num_kept = tl.zeros((), dtype=tl.uint32)

                final_pivot = k_pivot if num_finite_total > k else -float("inf")

                if TOPP_ENABLED and num_finite_total > k:
                    p = tl.load(P + row_id)
                    if p < 1.0:
                        # EXACT nucleus over the top_k survivors, by bisection
                        # on the IEEE754 ordered key (#1523). The top_k cut is
                        # ``logit > k_pivot`` and the nucleus can only narrow
                        # it, so the returned pivot enforces both at once.
                        #
                        # The candidate buffer holds the outlier LOGITS. It
                        # contains the whole top_k kept set exactly when the
                        # k-search itself ran over it (``num_outliers > k``
                        # puts k_pivot at or above the outlier threshold);
                        # otherwise the kept set can reach below that
                        # threshold and the full row is the candidate set.
                        p_search_range = tl.cast(num_outliers, tl.int32)
                        p_search_iters = tl.cast(
                            (num_outliers + BLOCK_SIZE_TRUNC - 1) // BLOCK_SIZE_TRUNC,
                            tl.int32,
                        )
                        # Mass of the top_k survivors — the distribution the
                        # nucleus is taken against, since top_k renormalises.
                        z_kept = 0.0
                        if num_outliers > k:
                            for i in range(0, p_search_iters):
                                offs_n = i * BLOCK_SIZE_TRUNC + tl.arange(0, BLOCK_SIZE_TRUNC)
                                m2 = offs_n < p_search_range
                                v2 = tl.load(BUFFER_ROW + offs_n, mask=m2, other=-float("inf"))
                                z_kept += tl.sum(
                                    tl.where(m2 & (v2 > k_pivot), tl.exp(v2 - max_logit), 0.0)
                                )
                            final_pivot = _nucleus_pivot(
                                BUFFER_ROW,
                                p_search_range,
                                p_search_iters,
                                k_pivot,
                                max_logit,
                                max_logit,
                                p * z_kept,
                                BLOCK=BLOCK_SIZE_TRUNC,
                            )
                        else:
                            for i in range(0, NUM_TILES):
                                offs_n = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
                                m2 = offs_n < VOCAB_SIZE
                                v2 = tl.load(LOGITS_ROW + offs_n, mask=m2, other=-float("inf")).to(
                                    tl.float32
                                )
                                z_kept += tl.sum(
                                    tl.where(m2 & (v2 > k_pivot), tl.exp(v2 - max_logit), 0.0)
                                )
                            final_pivot = _nucleus_pivot(
                                LOGITS_ROW,
                                VOCAB_SIZE,
                                NUM_TILES,
                                k_pivot,
                                max_logit,
                                max_logit,
                                p * z_kept,
                                BLOCK=BLOCK_SIZE,
                            )
                        # ``logit > pivot`` already admits every tie at the
                        # boundary, so nothing is left for the duplicate
                        # bookkeeping to trim. Retiring the SENTINEL rather
                        # than the counters is deliberate: no finite logit is
                        # within 1e-9 of +inf, so the mask pass keeps its
                        # duplicate branch and that branch matches nothing.
                        # Zeroing the counters instead would retype them —
                        # ``num_keep`` arrives from the top_k search as int64
                        # here and as uint32 in the top_p-only block — and
                        # Triton rejects a branch that redefines a variable's
                        # type. The interpreter does not.
                        duplicate_logit = float("inf")

        if TOPP_ENABLED and final_pivot == -float("inf"):
            p = tl.load(P + row_id)
            if p < 1.0:
                offs = tl.arange(0, BLOCK_SIZE)
                mask_n = offs < VOCAB_SIZE
                logits_blk0 = tl.load(LOGITS_ROW + offs, mask=mask_n, other=-float("inf")).to(
                    tl.float32
                )
                finite_mask = (logits_blk0 > -float("inf")) & mask_n
                num_finite = tl.sum(finite_mask)
                finite_logits = tl.where(finite_mask, logits_blk0, 0.0)
                avg_logit = tl.where(num_finite > 0, tl.sum(finite_logits) / num_finite, 0.0)
                sq_avg_logit = tl.where(
                    num_finite > 0,
                    tl.sum(finite_logits * finite_logits) / num_finite,
                    0.0,
                )
                std_logit = tl.sqrt(tl.maximum(sq_avg_logit - avg_logit * avg_logit, 0.0))
                max_sample = avg_logit + std_logit * 10.0

                idx = tl.cast(p * 200, tl.int32)
                idx = tl.maximum(0, tl.minimum(idx, 199))
                sigma = tl.load(NORMAL_CDF_TO_SIGMA_TABLE + idx)
                sigma = sigma + tl.abs(sigma) * -0.25
                outlier_pivot = avg_logit + std_logit * sigma

                # Compact the candidate LOGITS — not their probabilities, so
                # the search stays in logit space — and accumulate their mass,
                # which is what decides whether they can hold the nucleus at
                # all. The statistical outlier threshold is a COST heuristic
                # only: if it cuts too high the branch below re-searches the
                # whole row, so it can never change the answer.
                #
                # The row's max and total mass ride the same pass: both depend
                # only on the sample block's statistics, never on each other,
                # and each accumulates tile by tile in the order the separate
                # pass used, so the sums are the same fp32 values.
                sum_exp_logits = 0.0
                sum_outlier = 0.0
                num_outliers = tl.zeros((), dtype=tl.uint32)
                for i in range(0, NUM_TILES):
                    offs_n = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
                    mask_n = offs_n < VOCAB_SIZE
                    logits_blk = tl.load(LOGITS_ROW + offs_n, mask=mask_n, other=-float("inf")).to(
                        tl.float32
                    )
                    max_logit = tl.maximum(max_logit, tl.max(logits_blk))
                    exp_blk = tl.exp(logits_blk - max_sample)
                    sum_exp_logits += tl.sum(tl.where(mask_n, exp_blk, 0.0))
                    outlier_mask = (logits_blk > outlier_pivot) & mask_n
                    sum_outlier += tl.sum(tl.where(outlier_mask, exp_blk, 0.0))
                    cumulative_pos = tl.cast(tl.cumsum(outlier_mask) - 1 + num_outliers, tl.int32)
                    num_outliers += tl.sum(outlier_mask)
                    write_pos = tl.where(outlier_mask, cumulative_pos, -1)
                    tl.store(BUFFER_ROW + write_pos, logits_blk, mask=outlier_mask)
                # The scratch row was just written with the BLOCK_SIZE thread
                # layout and every read below uses BLOCK_SIZE_TRUNC, so each
                # element is read by a different thread than wrote it. Global
                # stores are not visible across warps without a CTA barrier:
                # a read can return the previous launch's value, and the kept
                # set then depends on stale scratch.
                tl.debug_barrier()

                target = p * sum_exp_logits
                if sum_outlier >= target:
                    # Narrow the candidates to the logits within
                    # NUCLEUS_WINDOW of the row max, behind the outliers in
                    # the same scratch row. The outlier cut is a normal-
                    # theory estimate and keeps thousands of logits for a
                    # nucleus of a handful; every search pass walks them.
                    # The window is a cost heuristic like the outlier cut:
                    # its mass is checked against ``target`` and, short of
                    # it, the search runs over the full outlier set.
                    n_out = tl.cast(num_outliers, tl.int32)
                    out_iters = tl.cast(
                        (num_outliers + BLOCK_SIZE_TRUNC - 1) // BLOCK_SIZE_TRUNC, tl.int32
                    )
                    n_near = tl.zeros((), dtype=tl.int32)
                    sum_near = 0.0
                    if 2 * n_out <= VOCAB_SIZE:
                        near_cut = max_logit - NUCLEUS_WINDOW
                        for i in range(0, out_iters):
                            offs_n = i * BLOCK_SIZE_TRUNC + tl.arange(0, BLOCK_SIZE_TRUNC)
                            m2 = offs_n < n_out
                            v2 = tl.load(BUFFER_ROW + offs_n, mask=m2, other=-float("inf"))
                            near = m2 & (v2 >= near_cut)
                            sum_near += tl.sum(tl.where(near, tl.exp(v2 - max_sample), 0.0))
                            pos = tl.cast(tl.cumsum(near.to(tl.int32)) - 1 + n_near, tl.int32)
                            n_near += tl.sum(near.to(tl.int32))
                            tl.store(BUFFER_ROW + n_out + tl.where(near, pos, 0), v2, mask=near)
                        # Same hazard: the search reads the compacted window
                        # back across threads.
                        tl.debug_barrier()
                    if n_near > 0 and sum_near >= target:
                        final_pivot = _nucleus_pivot(
                            BUFFER_ROW + n_out,
                            n_near,
                            (n_near + BLOCK_SIZE_TRUNC - 1) // BLOCK_SIZE_TRUNC,
                            -float("inf"),
                            max_sample,
                            max_logit,
                            target,
                            BLOCK=BLOCK_SIZE_TRUNC,
                        )
                    else:
                        final_pivot = _nucleus_pivot(
                            BUFFER_ROW,
                            n_out,
                            out_iters,
                            -float("inf"),
                            max_sample,
                            max_logit,
                            target,
                            BLOCK=BLOCK_SIZE_TRUNC,
                        )
                else:
                    final_pivot = _nucleus_pivot(
                        LOGITS_ROW,
                        VOCAB_SIZE,
                        NUM_TILES,
                        -float("inf"),
                        max_sample,
                        max_logit,
                        target,
                        BLOCK=BLOCK_SIZE,
                    )
                duplicate_logit = float("inf")

        # Sixth pass: Apply mask and store final output.
        if not (final_pivot < max_logit):
            final_pivot = -float("inf")
        elif final_pivot != -float("inf"):
            for i in range(0, NUM_TILES):
                offs_n = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
                mask_n = offs_n < VOCAB_SIZE
                logits_blk = tl.load(LOGITS_ROW + offs_n, mask=mask_n, other=-float("inf")).to(
                    tl.float32
                )
                keep_mask = (logits_blk > final_pivot) & mask_n

                if num_keep < num_duplicate_logit:
                    duplicate_mask = (logits_blk == duplicate_logit) & mask_n
                    duplicate_count = tl.cumsum(duplicate_mask) + num_kept
                    duplicate_keep_mask = (duplicate_count <= num_duplicate_logit) & duplicate_mask
                    duplicate_remove_mask = duplicate_mask & ~duplicate_keep_mask
                    num_kept += tl.sum(duplicate_keep_mask)
                    keep_mask = keep_mask & (~duplicate_remove_mask)

                logits_blk = tl.where(keep_mask, logits_blk, MASK_VALUE)
                tl.store(LOGITS_ROW + offs_n, logits_blk, mask=mask_n)

        # min-p / LSE epilogue (arbi-serve; constexpr-gated — the disabled
        # specialization compiles this block out entirely, so the plain
        # top-k/top-p mask's generated code is unchanged).
        #
        #   * MINP_ENABLED: per-row min-p on the (already top-k/top-p
        #     masked) row via the logit-space rewrite
        #     ``keep iff logit >= max_logit + log(min_p)`` — exactly
        #     ``_vectorized_min_p_mask``'s ``masked_fill_(logits < thresh)``
        #     form. Because top-k / top-p always keep the row argmax, the
        #     masked row's max equals the global ``max_logit`` the mask
        #     passes already computed (same reuse argument as SAMPLE); the
        #     renormalisation over the shrunken kept set happens implicitly
        #     in whatever softmax/logsumexp consumes the row.
        #   * WRITE_LSE: the masked-row ``logsumexp`` (``log(sum(exp(l -
        #     max))) + max`` in fp32) stored to ``OUT_LSE[row]`` — the
        #     normalizer the fused MTP rejection sampler needs, produced
        #     HERE so no separate ``torch.logsumexp`` launch runs. Masked
        #     lanes hold ``-inf`` (MASK_VALUE; asserted host-side), so
        #     ``exp`` contributes exactly 0 for them.
        #
        # Both share ONE extra pass over V (mask + accumulate fused).
        if MINP_ENABLED or WRITE_LSE:
            # Row max over the masked row. Reuse ``max_logit`` when a mask
            # pass computed it (top-k / top-p keep the argmax, so the
            # masked max equals it — bit-exact); an unmasked row (both
            # filters disabled / no-op) still needs the explicit pass.
            if max_logit == -float("inf"):
                for i in range(0, NUM_TILES):
                    offs_n = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
                    mask_n = offs_n < VOCAB_SIZE
                    logits_blk = tl.load(LOGITS_ROW + offs_n, mask=mask_n, other=-float("inf")).to(
                        tl.float32
                    )
                    max_logit = tl.maximum(max_logit, tl.max(logits_blk))

            minp_pivot = -float("inf")
            if MINP_ENABLED:
                mp = tl.load(MP + row_id).to(tl.float32)
                if mp > 0.0:
                    # keep iff logit >= max + log(mp); drop strict-below,
                    # matching ``_vectorized_min_p_mask``'s ``logits <
                    # thresh`` masked_fill. ``mp <= 0`` rows keep the
                    # -inf pivot → nothing drops (disabled row).
                    minp_pivot = max_logit + tl.log(mp)

            sum_exp = 0.0
            for i in range(0, NUM_TILES):
                offs_n = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
                mask_n = offs_n < VOCAB_SIZE
                logits_blk = tl.load(LOGITS_ROW + offs_n, mask=mask_n, other=-float("inf")).to(
                    tl.float32
                )
                if MINP_ENABLED:
                    drop = logits_blk < minp_pivot
                    logits_blk = tl.where(drop, MASK_VALUE, logits_blk)
                    # Write only the newly-dropped lanes (the kept lanes
                    # already hold their value; halves the write traffic).
                    tl.store(LOGITS_ROW + offs_n, logits_blk, mask=mask_n & drop)
                if WRITE_LSE:
                    exp_blk = tl.exp(logits_blk - max_logit)
                    exp_blk = tl.where(mask_n, exp_blk, 0.0)
                    sum_exp += tl.sum(exp_blk)
            if WRITE_LSE:
                tl.store(OUT_LSE + row_id, tl.log(sum_exp) + max_logit)

        # Seventh pass (SAMPLE only): fold softmax -> Gumbel-max -> argmax
        # into the kernel so the masked logits never round-trip to Python.
        #
        # Exact equivalence with the unfused chain
        #   probs = softmax(masked_logits);  token = argmax(probs / noise)
        # is preserved op-for-op:
        #   * row max over the (now masked-in-place) LOGITS_ROW,
        #   * fp32 sum_exp = sum(exp(logit - max)) (softmax denominator Z),
        #   * per-element score = (exp(logit - max) / Z) / noise — the
        #     identical two fp32 divides the unfused path does,
        #   * argmax with first-index (lowest-index) tie-break, matching
        #     torch.argmax. The running reduction across tiles keeps the
        #     lowest global index by only adopting a tile whose max is
        #     STRICTLY greater than the running best.
        # The NOISE row is the caller-supplied Exp(1) draw (rank-symmetric
        # SPMD); the kernel never generates noise itself.
        if SAMPLE:
            NOISE_ROW = NOISE + row_id * VOCAB_SIZE

            # Row max over the masked logits (softmax shift).
            #
            # Pass-reduction (item 2): top-k / top-p ALWAYS keep the single
            # highest logit (it is in every top-k set and starts every
            # top-p nucleus), so the max over the MASKED logits equals the
            # global ``max_logit`` already computed in the top-k / top-p
            # first pass. Reuse it and skip a full read pass over V. When no
            # mask ran (pure-temperature SAMPLE, ``max_logit`` still -inf)
            # we still need the explicit pass. Bit-exact: same fp32 value
            # the dedicated max pass would have produced.
            if max_logit != -float("inf"):
                sample_max = max_logit
            else:
                sample_max = -float("inf")
                for i in range(0, NUM_TILES):
                    offs_n = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
                    mask_n = offs_n < VOCAB_SIZE
                    logits_blk = tl.load(LOGITS_ROW + offs_n, mask=mask_n, other=-float("inf")).to(
                        tl.float32
                    )
                    sample_max = tl.maximum(sample_max, tl.max(logits_blk))

            # Softmax denominator Z = sum(exp(logit - max)) in fp32.
            sample_sum = 0.0
            for i in range(0, NUM_TILES):
                offs_n = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
                mask_n = offs_n < VOCAB_SIZE
                logits_blk = tl.load(LOGITS_ROW + offs_n, mask=mask_n, other=-float("inf")).to(
                    tl.float32
                )
                exp_blk = tl.exp(logits_blk - sample_max)
                exp_blk = tl.where(mask_n, exp_blk, 0.0)
                sample_sum += tl.sum(exp_blk)

            # argmax(probs / noise) with lowest-index tie-break.
            best_score = -float("inf")
            best_idx = tl.zeros((), dtype=tl.int64)
            for i in range(0, NUM_TILES):
                offs_n = i * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
                mask_n = offs_n < VOCAB_SIZE
                logits_blk = tl.load(LOGITS_ROW + offs_n, mask=mask_n, other=-float("inf")).to(
                    tl.float32
                )
                noise_blk = tl.load(NOISE_ROW + offs_n, mask=mask_n, other=1.0)
                probs_blk = tl.exp(logits_blk - sample_max) / sample_sum
                score_blk = probs_blk / noise_blk
                score_blk = tl.where(mask_n, score_blk, -float("inf"))
                # Lowest-index argmax within this tile.
                tile_max = tl.max(score_blk)
                tile_argmax = tl.argmax(score_blk, axis=0)
                tile_idx = i * BLOCK_SIZE + tile_argmax
                # Adopt only on a STRICTLY greater max so earlier tiles
                # (lower indices) win ties — matches torch.argmax.
                take = tile_max > best_score
                best_idx = tl.where(take, tile_idx.to(tl.int64), best_idx)
                best_score = tl.where(take, tile_max, best_score)

            tl.store(OUT_TOKENS + row_id, best_idx)
# ---- _topp_exact.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Exact top_p nucleus boundary, by bisection on the IEEE754 ordered key.

WHY THIS EXISTS. The vendored Qrita kernel finds its ``top_p`` cut with a
ternary search over the CONTINUOUS probability range, capped at 18 iterations
with a ``1e-9`` convergence floor, falling back to the interval MIDPOINT when
neither probe satisfies its acceptance test in budget. Ternary search narrows
by ~1/3 per step, so 18 steps from ``[0, 1]`` bottoms out at ~``1.4e-9`` —
exactly the floor. When two adjacent probabilities near the nucleus boundary
are closer than that, the search cannot separate them and the midpoint lands
on whichever side the interval happened to straddle. The kept set then comes
out too small or too large — both occur — on rows whose boundary sits inside a
plateau of near-identical logits, which is what a real ``lm_head`` produces
over a 248k vocabulary.

The fix is not more iterations. More iterations makes the search exact IN
PRACTICE, which is a claim about inputs rather than about the algorithm, and
it still carries a tolerance constant that has to be argued about.

WHAT THIS DOES INSTEAD. IEEE754 floats, reinterpreted through the standard
order-preserving transform, are a CONTIGUOUS RANGE OF INTEGERS. Bisecting
that integer range is bisecting the set of representable values, so it
terminates on an exact float in at most 32 steps with **no tolerance
constant anywhere** — the loop ends when ``lo == hi``, not when an interval
gets small enough.

The search runs in LOGIT space, never probability space, for the same reason:
the mask compares logits, so a boundary found among probabilities would have
to come back through ``log(p * Z) + max``, and that round-trip reintroduces a
ULP of slop at precisely the boundary being fixed. Bisecting logits directly
yields a threshold that IS a representable logit, and the returned pivot is
its exact predecessor, so ``logit > pivot`` reproduces ``logit >= threshold``
with no arithmetic in between.

COST, and the mistake worth recording. A first version bisected the key range
unconditionally and MEASURED 44% SLOWER on top_p-only rows. The pass-count
argument behind it — "24-32 cheap passes against ~36 expensive ones" — was
wrong about the baseline: the upstream ternary search is DATA-ADAPTIVE and
exits the moment its acceptance test can prove a pivot, which on ordinary
rows happens in a handful of iterations, nowhere near its 18-iteration cap.
Comparing worst case against worst case hid that the common case was cheap.

So the fix is
not to be unconditionally exact, it is to keep the early exit and make it
sound. The loop below carries the same proof-of-boundary test, in one pass
instead of the upstream's two, and only falls through to full bisection on
the rows where the old search would have given up and guessed."""

from __future__ import annotations

import triton
import triton.language as tl


@triton.jit
def _f32_to_ordered_key(x):
    """Map fp32 to a uint32 whose integer order matches float order.

    Non-negative floats keep their bit pattern with the sign bit set;
    negative floats are complemented. ``^`` rather than ``~`` because Triton's
    interpreter rejects the negative intermediate that ``~`` produces on an
    unsigned type.
    """
    b = x.to(tl.uint32, bitcast=True)
    return tl.where(b >= 0x80000000, b ^ 0xFFFFFFFF, b ^ 0x80000000)


@triton.jit
def _ordered_key_to_f32(u):
    """Inverse of :func:`_f32_to_ordered_key`."""
    b = tl.where(u >= 0x80000000, u ^ 0x80000000, u ^ 0xFFFFFFFF)
    return b.to(tl.float32, bitcast=True)


@triton.jit
def _nucleus_pivot(
    PTR,  # candidate logits, contiguous
    n,  # number of valid entries in PTR
    n_tiles,  # tiles of BLOCK needed to cover n
    floor_pivot,  # only logits STRICTLY above this are candidates (e.g. the top_k cut)
    shift,  # exp shift; must match the one ``target`` was accumulated with
    hi_val,  # a logit known to be a candidate and >= every other (the row max)
    target,  # p * (total mass of the FULL distribution, in exp(. - shift) units)
    BLOCK: tl.constexpr,
):
    """Pivot such that ``logit > pivot`` is exactly the ``top_p`` nucleus.

    The nucleus is the smallest set of highest-probability tokens whose mass
    reaches ``p``, with the whole tie group at the boundary included. Mass is
    monotone in the threshold, so the boundary is the LARGEST logit ``L``
    whose kept mass still reaches ``target``, and bisection on the ordered key
    finds it exactly.

    ``target`` is passed rather than derived from the candidates because the
    candidate set is often a SUBSET of the row (the outlier buffer). The
    nucleus is defined against the full distribution's mass, so deriving it
    locally would renormalise against the subset and cut in the wrong place.

    Returns the predecessor of ``L``, so the caller's existing
    ``logit > pivot`` mask keeps ``logit >= L`` — every tie at ``L``
    included, with no duplicate bookkeeping.
    """
    # One pass for the low end of the bracket. The high end is supplied: the
    # row max is a candidate under any floor, so it always brackets above.
    lo_val = float("inf")
    for i in range(0, n_tiles):
        offs = i * BLOCK + tl.arange(0, BLOCK)
        m = offs < n
        v = tl.load(PTR + offs, mask=m, other=-float("inf")).to(tl.float32)
        lo_val = tl.minimum(lo_val, tl.min(tl.where(m & (v > floor_pivot), v, float("inf"))))

    lo = _f32_to_ordered_key(lo_val)
    hi = _f32_to_ordered_key(hi_val)
    boundary = lo_val
    done = 0
    # Invariant: the mass kept at threshold ``lo`` is >= target. It holds at
    # entry because ``lo_val`` keeps every candidate, and the caller only
    # takes this path when the candidates carry at least ``target``. Every
    # step moves ``lo`` only to a threshold that still satisfies it.
    while done == 0 and lo < hi:
        mid = lo + (hi - lo + 1) // 2
        thr = _ordered_key_to_f32(mid)
        s = 0.0
        min_kept = float("inf")
        for i in range(0, n_tiles):
            offs = i * BLOCK + tl.arange(0, BLOCK)
            m = offs < n
            v = tl.load(PTR + offs, mask=m, other=-float("inf")).to(tl.float32)
            keep = m & (v > floor_pivot) & (v >= thr)
            s += tl.sum(tl.where(keep, tl.exp(v - shift), 0.0))
            min_kept = tl.minimum(min_kept, tl.min(tl.where(keep, v, float("inf"))))
        if s >= target:
            lo = mid
            # EARLY EXIT, and it is what makes this affordable. Dropping the
            # single smallest kept logit already takes the mass below target,
            # so no threshold above ``min_kept`` can reach it and ``min_kept``
            # IS the boundary — proved, not approximated, so the remaining
            # steps are skipped rather than guessed.
            #
            # Using one element rather than its whole tie group makes this a
            # SUFFICIENT test, never a necessary one: a tie group weighs at
            # least as much as one of its members, so the test can only fail
            # to fire, never fire wrongly. When it does not fire the loop
            # keeps bisecting and still lands exactly — which is precisely the
            # plateau case this kernel exists to get right.
            if s - tl.exp(min_kept - shift) < target:
                boundary = min_kept
                done = 1
        else:
            hi = mid - 1
    if done == 0:
        boundary = _ordered_key_to_f32(lo)
    # The predecessor key of +0.0 is -0.0, which the caller's ``logit >
    # pivot`` treats as EQUAL to +0.0 -- it would drop the boundary itself,
    # and with it the row max when that is 0.0 (the caller then keeps the
    # whole row). Step from -0.0 instead: its predecessor is the largest
    # negative subnormal, strictly below both zeros.
    bkey = _f32_to_ordered_key(boundary)
    bkey = tl.where(boundary == 0.0, tl.full((), 0x7FFFFFFF, tl.uint32), bkey)  # key(-0.0)
    return _ordered_key_to_f32(bkey - 1)
# ---- _triton_util.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Shared host-side helpers for the sampler Triton kernels.

Small pure-Python utilities used by both :mod:`topk_topp_triton` and
:mod:`gumbel_argmax_triton` to size Triton launch grids. Kept in one
place so the two kernel files don't each carry a private copy.
"""

from __future__ import annotations

import torch


def next_pow2(n: int) -> int:
    """Smallest power of 2 ``>= n`` (``>= 1``)."""
    return 1 if n < 1 else 1 << (n - 1).bit_length()


_SM_COUNT_CACHE: dict[int, int] = {}


def num_sm(device: torch.device) -> int:
    """Number of streaming multiprocessors on the given CUDA device (cached)."""
    idx = device.index if device.index is not None else 0
    n = _SM_COUNT_CACHE.get(idx)
    if n is None:
        n = torch.cuda.get_device_properties(idx).multi_processor_count
        _SM_COUNT_CACHE[idx] = n
    return n
# ---- _watermark_kernel.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Triton kernels for the watermark context cache's per-step device work.

The eager torch expression of :meth:`WatermarkContextCache.row_seeds` /
``advance`` (ring gather, SplitMix64 hash chain, Bloom check+insert,
seed select, ring shift) is ~20 tiny elementwise/gather/scatter launches
per decode step. Each is microseconds of device work but ~5-10 us of
launch overhead — measurable against a small model's ~2 ms step. These
kernels collapse the whole path to TWO launches (seed+Bloom, then the
post-sample ring advance), bit-identical to the torch path.

All 64-bit arithmetic runs in uint64 (native logical shifts, wrapping
mul/add) and matches the pure-Python reference in
:mod:`arbi_serve.sampler.watermark` — parity-covered by the same tests
that pin the torch path.
"""

from __future__ import annotations

import triton
import triton.language as tl


@triton.jit
def _splitmix64(x):
    """One SplitMix64 step on a uint64 value (wrapping, logical shifts)."""
    x = x + tl.full((), 0x9E3779B97F4A7C15, tl.uint64)
    x = (x ^ (x >> 30)) * tl.full((), 0xBF58476D1CE4E5B9, tl.uint64)
    x = (x ^ (x >> 27)) * tl.full((), 0x94D049BB133111EB, tl.uint64)
    return x ^ (x >> 31)


@triton.jit
def _wm_fold_token(h, t, j):
    """Fold context token ``t`` at window position ``j`` into hash ``h``."""
    gj = tl.full((), 0x9E3779B97F4A7C15, tl.uint64) * j.to(tl.uint64)
    return _splitmix64(h ^ _splitmix64(t.to(tl.uint64, bitcast=True) + gj))


@triton.jit
def _wm_bloom_probe(BLOOM, row, h, do_insert, W: tl.constexpr):
    """Two-probe Bloom membership on context hash ``h`` for cache ``row``.

    Returns the pre-insert "seen" verdict; inserts the probes only when
    ``do_insert`` is true (predicated store — the check side is free of
    writes so speculative contexts never poison the filter).
    """
    seen = tl.full((), 1, tl.int32) == 1
    for c in tl.static_range(2):
        if c == 0:
            probe = tl.full((), 0xA24BAED4963EE407, tl.uint64)
        else:
            probe = tl.full((), 0x9FB21C651E98DF25, tl.uint64)
        g = _splitmix64(h ^ probe)
        bit = g & tl.full((), W * 64 - 1, tl.uint64)
        widx = (bit >> 6).to(tl.int64, bitcast=True)
        m = (tl.full((), 1, tl.uint64) << (bit & tl.full((), 63, tl.uint64))).to(
            tl.int64, bitcast=True
        )
        word = tl.load(BLOOM + row * W + widx)
        seen = seen & ((word & m) != 0)
        if do_insert:
            tl.store(BLOOM + row * W + widx, word | m)
    return seen


@triton.jit
def _wm_seed_kernel(
    RING,  # (rows, H) int64 — per-request last-H token windows
    BLOOM,  # (rows, W) int64 — per-request seen-context bit sets
    ROWS,  # (B,) int64 — slate index -> cache row
    BASE,  # (B,) int64 — fallback seeds for masked (repeated) contexts
    OUT,  # (B,) int64 — resulting per-row Philox seeds
    KEY,  # (1,) int64 — the watermark key (bit pattern)
    H: tl.constexpr,
    W: tl.constexpr,
):
    """Hash the context window, Bloom check+insert, select seed. Grid (B,)."""
    b = tl.program_id(0)
    row = tl.load(ROWS + b)

    h = tl.load(KEY).to(tl.uint64, bitcast=True)
    for j in tl.static_range(H):
        t = tl.load(RING + row * H + j)
        h = _wm_fold_token(h, t, tl.full((), j, tl.int64))
    seed = (h & tl.full((), 0x7FFFFFFFFFFFFFFF, tl.uint64)).to(tl.int64, bitcast=True)

    seen = _wm_bloom_probe(BLOOM, row, h, tl.full((), 1, tl.int32) == 1, W)

    base = tl.load(BASE + b)
    tl.store(OUT + b, tl.where(seen, base, seed))


@triton.jit
def _wm_mtp_seed_kernel(
    RING,  # (rows, H) int64 — per-request last-H COMMITTED token windows
    BLOOM,  # (rows, W) int64 — per-request seen-context bit sets
    ROWS,  # (B,) int64 — slate index -> cache row
    DRAFT,  # (K, B) int64 — this step's drafted tokens
    POS,  # (rows,) int64 — per-row committed length (absolute position base)
    SALT,  # (rows,) int64 — per-row unkeyed salt
    OUT,  # (D_COUNT * B,) int64 — seeds for depths D_START..D_START+D_COUNT-1
    KEY,  # (1,) int64 — the watermark key (bit pattern)
    KEEP,  # (B,) bool — False rows take the unkeyed seed at every depth (read iff HAS_KEEP)
    B,
    d_stride_k,
    d_stride_b,
    H: tl.constexpr,
    W: tl.constexpr,
    D_START: tl.constexpr,
    D_COUNT: tl.constexpr,
    HAS_KEEP: tl.constexpr,
):
    """Watermark seeds for ``D_COUNT`` depths from ``D_START``. Grid (B,).

    Depth ``d``'s context is the last ``H`` of (committed ring ++
    ``DRAFT[0:d]``) — the residual draw at the first rejected depth ``d``
    sees exactly this context because the accepted prefix IS the drafted
    prefix, and the bonus draw (depth ``K``) sees all ``K`` drafted
    tokens. A depth's hash reads only tokens, never another depth's hash
    or seed, so any contiguous depth range is computable on its own: the
    verify tail takes ``D_START=0, D_COUNT=K+1``, a drafter's slot-``s``
    seeds take ``D_START=s, D_COUNT=1``. Bloom is CHECK-ONLY here (a
    masked depth falls back to the row's UNKEYED seed at that absolute
    position: ``splitmix64(salt ^ splitmix64(pos + d + REMIX))``, the same
    value the drafter that proposed the token derived); inserts happen at
    commit, for the depths that were actually consumed.

    ``OUT`` is indexed by the depth's OFFSET in the range, while the
    fallback keys on the ABSOLUTE depth — so a sliced range yields
    exactly the rows a full sweep would have put at ``d * B + b``.
    """
    b = tl.program_id(0)
    row = tl.load(ROWS + b)
    key = tl.load(KEY).to(tl.uint64, bitcast=True)
    salt = tl.load(SALT + row).to(tl.uint64, bitcast=True)
    base_pos = tl.load(POS + row).to(tl.uint64, bitcast=True)
    keyed = tl.full((), 1, tl.int1)
    if HAS_KEEP:
        keyed = tl.load(KEEP + b) != 0

    for i in tl.static_range(D_COUNT):
        d = D_START + i
        h = key
        for j in tl.static_range(H):
            pos = d + j  # index into (ring ++ draft[0:d]), oldest-first tail of H
            if pos < H:
                t = tl.load(RING + row * H + pos)
            else:
                t = tl.load(DRAFT + (pos - H) * d_stride_k + b * d_stride_b)
            h = _wm_fold_token(h, t, tl.full((), j, tl.int64))
        seed = (h & tl.full((), 0x7FFFFFFFFFFFFFFF, tl.uint64)).to(tl.int64, bitcast=True)

        seen = _wm_bloom_probe(BLOOM, row, h, tl.full((), 0, tl.int32) == 1, W)
        # Repeated-context fallback: a per-(depth, row) remix of the step
        # seed — decorrelated across rows and depths, rank-agreed, and
        # laid out for the zero-lane counter the keyed kernels use.
        position = base_pos + tl.full((), d, tl.uint64)
        base_u = _splitmix64(
            salt ^ _splitmix64(position + tl.full((), 0xC2B2AE3D27D4EB4F, tl.uint64))
        )
        base = (base_u & tl.full((), 0x7FFFFFFFFFFFFFFF, tl.uint64)).to(tl.int64, bitcast=True)
        tl.store(OUT + i * B + b, tl.where(seen | (not keyed), base, seed))


@triton.jit
def _wm_mtp_advance_kernel(
    RING,  # (rows, H) int64
    BLOOM,  # (rows, W) int64
    ROWS,  # (B,) int64
    COMMITTED,  # (KP1, B) int64 — committed tokens: drafted prefix then recovery/bonus
    NACC,  # (B,) int64 — accepted drafted count n; n+1 tokens committed
    POS,  # (rows,) int64 — per-row committed length, advanced by n+1
    KEY,  # (1,) int64
    _B,
    c_stride_k,
    c_stride_b,
    H: tl.constexpr,
    W: tl.constexpr,
    KP1: tl.constexpr,
    INSERT_BLOOMS: tl.constexpr = True,
):
    """Commit an MTP verify step into the watermark state. Grid (B,).

    Bloom-inserts the contexts actually consumed (depths ``0..n`` — the
    accepted-drafted draws plus the recovery/bonus draw), then advances
    the ring by the ``n+1`` committed tokens. Contexts for depths
    ``<= n`` are windows over (ring ++ committed prefix), which for the
    accepted prefix is identical to the drafted prefix the seed kernel
    hashed — so the inserted hashes match the seeds that were served.
    """
    b = tl.program_id(0)
    row = tl.load(ROWS + b)
    n = tl.load(NACC + b)
    key = tl.load(KEY).to(tl.uint64, bitcast=True)

    if INSERT_BLOOMS:
        for d in tl.static_range(KP1):
            if d <= n:
                h = key
                for j in tl.static_range(H):
                    pos = d + j
                    if pos < H:
                        t = tl.load(RING + row * H + pos)
                    else:
                        t = tl.load(COMMITTED + (pos - H) * c_stride_k + b * c_stride_b)
                    h = _wm_fold_token(h, t, tl.full((), j, tl.int64))
                _wm_bloom_probe(BLOOM, row, h, tl.full((), 1, tl.int32) == 1, W)

    # Ring advance by n+1 tokens: new[j] = (ring ++ committed[0:n+1])[n+1+j].
    # Reads always sit AHEAD of this program's writes (n+1+j > j), so the
    # in-place interleaved shift is hazard-free within the row.
    for j in tl.static_range(H):
        pos = n + 1 + tl.full((), j, tl.int64)
        if pos < H:
            v = tl.load(RING + row * H + pos)
        else:
            v = tl.load(COMMITTED + (pos - H) * c_stride_k + b * c_stride_b)
        tl.store(RING + row * H + j, v)
    tl.store(POS + row, tl.load(POS + row) + n + 1)


@triton.jit
def _wm_advance_kernel(
    RING,  # (rows, H) int64
    ROWS,  # (B,) int64
    SAMPLED,  # (B,) int64 — this step's merged sampled tokens
    POS,  # (rows,) int64 — per-row committed length, advanced by 1
    H: tl.constexpr,
):
    """Shift each slate row's window left, append the sampled token, and
    advance the row's committed length."""
    b = tl.program_id(0)
    row = tl.load(ROWS + b)
    for j in tl.static_range(H - 1):
        v = tl.load(RING + row * H + j + 1)
        tl.store(RING + row * H + j, v)
    tok = tl.load(SAMPLED + b)
    tl.store(RING + row * H + H - 1, tok)
    tl.store(POS + row, tl.load(POS + row) + 1)
# ---- accept_count_triton.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The rejection sampler's per-row accept count in one launch, bit-identical.

The Leviathan accept test of ``_mtp_sample_residual_philox_kernel`` gathered
``p`` (and ``q``) at the drafted tokens, compared ``u * q <= p``, and reduced
the first mismatch per column through an ``any`` / ``argmax`` / ``where`` chain:
about ten launches around a (K, B) problem. Here one program per column walks
its K slots and stops at the first rejection. The arithmetic is the same:
gathered fp32 values, one ``mul.rn``, the same comparison, and the count is
``K`` when every slot accepts. ``tests/test_accept_count_triton.py`` holds it to
``torch.equal`` against the chain.
"""

from __future__ import annotations

from functools import lru_cache

import torch


@lru_cache(maxsize=1)
def _kernel():
    import triton
    import triton.language as tl

    @triton.jit(do_not_specialize=["K", "SPK", "SPB", "SQK", "SQB", "STK", "SUK"])
    def _accept_count(P, Q, TOK, U, OUT, K, SPK, SPB, SQK, SQB, STK, SUK, HAS_Q: tl.constexpr):
        b = tl.program_id(0).to(tl.int64)
        count = K
        found = 0
        for k in range(0, K):
            x = tl.load(TOK + k * STK + b).to(tl.int64)
            p = tl.load(P + k * SPK + b * SPB + x)
            u = tl.load(U + k * SUK + b)
            if HAS_Q:
                accept = (u * tl.load(Q + k * SQK + b * SQB + x)) <= p
            else:
                accept = u <= p
            first = (found == 0) & (accept == 0)
            count = tl.where(first, k, count)
            found = tl.where(first, 1, found)
        tl.store(OUT + b, count.to(tl.int64))

    return _accept_count


def accepted_count(
    main_probs: torch.Tensor,  # (K+1, B, V) fp32
    draft_probs: torch.Tensor | None,  # (K, B, V) fp32, or None = point mass
    draft_tokens: torch.Tensor,  # (K, B) int
    uniforms: torch.Tensor,  # (K, B) fp32
) -> torch.Tensor | None:
    """``(B,)`` int64 accepted-prefix length, or ``None`` when the operands are
    not the layout this reproduces (the caller runs the chain)."""
    kp1, b, v = main_probs.shape
    k = kp1 - 1
    if (
        torch.compiler.is_compiling()
        or not main_probs.is_cuda
        or k <= 0
        or main_probs.dtype != torch.float32
        or main_probs.stride(-1) != 1
        or uniforms.dtype != torch.float32
        or uniforms.shape != (k, b)
        or uniforms.stride(-1) != 1
        or draft_tokens.shape != (k, b)
        or draft_tokens.stride(-1) != 1
        or (
            draft_probs is not None
            and (draft_probs.dtype != torch.float32 or draft_probs.stride(-1) != 1)
        )
    ):
        return None
    out = torch.empty((b,), dtype=torch.int64, device=main_probs.device)
    q = draft_probs if draft_probs is not None else main_probs
    _kernel()[(b,)](
        main_probs, q, draft_tokens, uniforms, out, k,
        main_probs.stride(0), main_probs.stride(1), q.stride(0), q.stride(1),
        draft_tokens.stride(0), uniforms.stride(0), HAS_Q=draft_probs is not None, num_warps=1,
    )  # fmt: skip
    return out


@lru_cache(maxsize=1)
def _commit_kernel():
    import triton
    import triton.language as tl

    @triton.jit(do_not_specialize=["K", "B", "SD"])
    def _committed_tokens(SAMPLED, DRAFT, NACC, OUT, K, B, SD, BLOCK: tl.constexpr):
        k = tl.program_id(0)
        b = tl.arange(0, BLOCK)
        m = b < B
        sampled = tl.load(SAMPLED + k * B + b, mask=m)
        if k < K:
            draft = tl.load(DRAFT + k * SD + b, mask=m).to(sampled.dtype)
            take = k < tl.load(NACC + b, mask=m, other=0)
            sampled = tl.where(take, draft, sampled)
        tl.store(OUT + k * B + b, sampled, mask=m)

    return _committed_tokens


def committed_tokens(
    sampled: torch.Tensor,  # (K+1, B) contiguous
    draft: torch.Tensor,  # (K, B)
    num_accepted: torch.Tensor,  # (B,)
) -> torch.Tensor | None:
    """``sampled`` with each row's accepted slots replaced by its drafts (``where(k < n,
    draft, sampled)``, cast to ``sampled``'s dtype), or ``None`` off the layout."""
    if (
        torch.compiler.is_compiling()
        or not sampled.is_cuda
        or sampled.dim() != 2
        or not sampled.is_contiguous()
        or draft.dim() != 2
        or draft.stride(-1) != 1
        or draft.shape[1] != sampled.shape[1]
        or draft.shape[0] >= sampled.shape[0] + 1
        or num_accepted.shape != (sampled.shape[1],)
        or not num_accepted.is_contiguous()
        or sampled.dtype.is_floating_point
        or draft.dtype.is_floating_point
    ):
        return None
    import triton

    kp1, b = (int(x) for x in sampled.shape)
    out = torch.empty_like(sampled)
    if kp1 and b:
        _commit_kernel()[(kp1,)](
            sampled, draft, num_accepted, out, int(draft.shape[0]), b, draft.stride(0),
            BLOCK=max(16, triton.next_power_of_2(b)), num_warps=1,
        )  # fmt: skip
    return out
# ---- force_stop.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Stop an in-flight request by forcing its stop token.

THE STOP IS ADDRESSED, NOT INFERRED FROM A CONNECTION. Cancelling by transport
teardown asks a chain of layers to notice that a socket died, and each link
answers late or not at all: a streaming generator learns of a disconnect only
when it is resumed (so never during prefill), Starlette's
``Request.is_disconnected()`` polls ``receive()`` inside an already-cancelled
scope, and closing an HTTP stream from a ``finally`` that is running *because*
of a ``CancelledError`` is itself cancelled before it reaches the socket.
Measured against this engine, a run whose natural length was 52.3 s and whose
client was killed at 10 s finished at 51.2 s: the cancel arrived after the work
it was cancelling.

So this does what the thinking budget already does for ``</think>`` — it forces
a token. The row is masked to a stop id on the next sampling step, the terminal
check sees a stop, and the request ENDS THE WAY IT WOULD HAVE ENDED ANYWAY:
a real ``finish_reason``, usage reported, KV released down the ordinary path,
the trace written. A torn-down connection gives none of that.

WHAT IT CANNOT DO ON ITS OWN, and what :func:`stop_now` therefore does
about it: a logits processor runs only where there are logits, and a
mid-prefill chunk samples nothing (``step_variants``: "a prefill row on its
FINAL chunk … a mid-prefill chunk samples None"). A request that has not yet
produced its first token cannot be stopped by forcing a token, so
:func:`stop_now` CANCELS that row by id instead (the same surface the HTTP
disconnect path uses) and reports ``how="cancelled"`` — a dropped request,
not a clean finish. The disconnect path in
:mod:`arbi_serve.server.routes._request_ctx` covers the same window for
clients that go away on their own.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from arbi_serve.flag_truth import path_counter

if TYPE_CHECKING:  # pragma: no cover - typing only
    import torch

    from arbi_serve.engine.request import Request

#: Fires when an operator's stop is armed on a live request. Its own counter,
#: distinct from the thinking budget's: both force a token, and a reader who
#: cannot tell an intervention from a configured lever engaging cannot answer
#: either "is the cap doing anything" or "did somebody stop this".
request_stopped_by_operator = path_counter("request_stopped_by_operator")


def stop_token_for(req: Request, stop_ids: tuple[int, ...]) -> int | None:
    """The id this row must emit this step, or ``None``.

    Duck-typed on ``force_stop_now`` so an engine test double without the field
    reads as "not stopping" rather than raising inside the sampler.
    """
    if not stop_ids:
        return None
    if not getattr(req, "force_stop_now", False):
        return None
    return int(stop_ids[0])


def mask_verify_slate_force_stop(
    logits: torch.Tensor,  # (K+1, B, W) — masked in place
    requests: Any,
    stop_ids: Any,
    *,
    window: Any = None,
) -> None:
    """Mask verify position ``p == 0`` to the forced stop id.

    A free function for the same reason the thinking budget's is: the mask can
    then be driven against a slate directly in a test, without a sampler.

    Under a vocab-parallel ``window`` every rank bans its whole slice — the ban
    is the vocabulary minus one token — and only the rank that OWNS the forced
    id reopens it, so the finite value lands exactly once across the group.
    """
    from arbi_serve.sampler.vocab_window import window_bounds

    if not stop_ids:
        return
    ids = tuple(int(t) for t in stop_ids)
    lo, hi = window_bounds(window, logits.shape[-1])
    neg_inf = float("-inf")
    for col, req in enumerate(requests):
        if req is None:
            continue
        forced = stop_token_for(req, ids)
        if forced is None:
            continue
        logits[0, col, :] = neg_inf
        if lo <= forced < hi:
            logits[0, col, forced - lo] = 0.0


class ForceStopGuard:
    """Logits processor forcing a stop token for rows an operator stopped.

    Mirrors :class:`~arbi_serve.sampler.thinking_budget.ThinkingBudgetGuard`:
    the row is masked to ``-inf`` and only the forced id reopened, at a FINITE
    constant rather than its original logit — a model that assigned the stop id
    ``-inf`` would otherwise leave an all-``-inf`` row, where argmax and softmax
    are both undefined.

    One bool read per row, and the common case (nobody stopping) returns the
    logits untouched, so an unused guard costs a comparison per row per step.
    """

    def __init__(self, stop_ids: tuple[int, ...], *, vocab_size: int) -> None:
        self._stop_ids = tuple(int(t) for t in stop_ids)
        self._vocab_size = int(vocab_size)

    def __call__(self, logits: torch.Tensor, requests: list[Request]) -> torch.Tensor:
        if not self._stop_ids:
            return logits
        forced: list[tuple[int, int]] = []
        for i, req in enumerate(requests):
            if req is None:
                continue
            tok = stop_token_for(req, self._stop_ids)
            if tok is not None:
                forced.append((i, tok))
        if not forced:
            return logits
        import torch as _torch

        out = logits.clone()
        neg_inf = float("-inf")
        for i, tok in forced:
            forced_col = _torch.full_like(out[:, i, :], neg_inf)
            forced_col[:, tok] = 0.0
            out[:, i, :] = forced_col
        return out

    def verify_slate_reads_drafts(self, requests: Any) -> bool:
        """The slate form does not read the draft tokens.

        :meth:`apply_to_verify_slate` constrains ``p == 0`` only and deletes
        its ``drafts_per_row`` argument unread, so answering the base
        protocol's default here would ask the verify path to pull every row's
        drafts off the device — a blocking host copy on every decode step, for
        a value this processor never looks at. This guard is attached whenever
        the tokenizer has a stop id, which is every real boot, so the default
        is the one answer it must not inherit.
        """
        del requests
        return False

    def apply_to_verify_slate(
        self,
        logits: torch.Tensor,  # (K+1, B, W) — masked in place
        requests: Any,
        drafts_per_row: Any,
        *,
        window: Any = None,
    ) -> None:
        """Force the stop id at the IMMEDIATE verify position.

        WITHOUT THIS THE STOP DOES NOT REACH A SPECULATING BOOT. The
        shard-resident verify draw does not call ``__call__``; it asks each
        processor whether it constrains the slate and then calls this. A guard
        that answers True here and cannot write is worse than one that never
        claimed to — and the whole shipped configuration on this box speculates,
        so the plain path is the one that would almost never run.

        Only ``p == 0`` is constrained: it is the position whose context is the
        committed history, so it is where the stop must land. The row's drafts
        at ``p > 0`` are then rejected against it and exactly the stop is
        emitted.
        """
        del drafts_per_row  # only p == 0 is constrained
        mask_verify_slate_force_stop(logits, requests, self._stop_ids, window=window)

    def constrains_verify_slate(self, requests: Any) -> bool:
        """Whether any column is being forced to stop this step.

        Keyed on the same read the mask makes, so the verify slate and the mask
        cannot disagree about which rows are constrained.
        """
        if not self._stop_ids:
            return False
        return any(
            r is not None and stop_token_for(r, self._stop_ids) is not None for r in requests
        )


def stop_now(eng: Any, *, request_id: str) -> dict:
    """Ask one in-flight request to stop generating and finish.

    Arms :attr:`~arbi_serve.engine.request.Request.force_stop_now`; the guard
    forces a stop id on the next sampling step and the terminal check honours
    it — including under ``ignore_eos``, which declares the MODEL's stop
    uninteresting rather than declaring the request unstoppable.

    ONE ENDPOINT FOR BOTH PHASES. The caller sends one request and the engine
    chooses: a row that has produced a token is stopped by forcing one, a row
    that has not is cancelled by id. ``how`` reports which happened, so the
    outcome is legible without the caller ever having had to pick.

    Refuses rather than no-ops, and says which:

      * the tokenizer publishes no stop id, so there is no token to force;
      * the request is not running (matched by the caller's own
        ``X-Request-ID`` first, then its request uid);
      * it has not produced a token yet, so no sampling step exists to carry
        the forced id — the disconnect path covers that window, and reporting
        success here would promise a stop that lands only when prefill ends.
    """
    from arbi_serve.sampler.thinking_budget import _find_request

    stop_ids = tuple(getattr(getattr(eng, "tokenizer", None), "stop_token_ids", ()) or ())
    if not stop_ids:
        return {
            "stopped": False,
            "reason": "this tokenizer publishes no stop token, so there is none to force",
        }
    scheduler = getattr(eng, "scheduler", None)
    # WAITING TOO. A request that has not been scheduled yet is exactly the one
    # a caller most wants to drop, and looking only at ``running`` reported it
    # as "not running" -- a refusal that is both useless and, for a request
    # visibly mid-prefill on the timeline, untrue.
    pool = list(getattr(scheduler, "waiting", None) or ()) + list(
        getattr(scheduler, "running", None) or ()
    )
    req = _find_request(pool, request_id)
    if req is None:
        return {"stopped": False, "how": "", "reason": f"request {request_id!r} is not in flight"}
    if getattr(req, "force_stop_now", False):
        return {"stopped": True, "how": "forced_stop_token", "reason": "already stopping"}

    # ONE CALL, AND THE ENGINE PICKS THE MECHANISM. A caller cannot know which
    # phase a request is in -- it changes between reading the timeline and
    # sending the request -- so making them choose is making them race.
    #
    # A row that has produced a token is stopped by FORCING one: it ends the way
    # it would have ended anyway, with a real finish_reason, usage reported, KV
    # released down the ordinary path and its trace written.
    #
    # A row that has not cannot be: a logits processor runs only where there are
    # logits, and a mid-prefill chunk samples nothing. That one is CANCELLED by
    # id instead -- the same surface the HTTP disconnect path uses, so a
    # prefilling request is dropped rather than reported unstoppable.
    if getattr(req, "output_token_ids", None) or ():
        req.force_stop_now = True
        request_stopped_by_operator.fired = 1
        return {"stopped": True, "how": "forced_stop_token", "reason": ""}

    cancel = getattr(eng, "cancel_by_id", None)
    if cancel is None:
        return {
            "stopped": False,
            "how": "",
            "reason": (
                f"request {request_id!r} has produced no token yet, so no forced stop can "
                "reach it, and this engine exposes no cancel_by_id to drop it with"
            ),
        }
    cancel(int(getattr(req, "request_id", 0)), "stopped by operator")
    request_stopped_by_operator.fired = 1
    # A cancel is NOT a clean finish and does not claim to be: the caller gets a
    # dropped request rather than a finish_reason, which is the honest outcome
    # for work that had produced nothing to finish with.
    return {"stopped": True, "how": "cancelled", "reason": ""}
# ---- gumbel_argmax_triton.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Single-pass counter-based Gumbel-max sampler (no-filter stochastic decode).

The default decode shape (``temperature > 0``, ``top_p = 1``, ``top_k``
unset, ``min_p = 0``) is a plain categorical draw from
``softmax(logits)``. The classic way to draw it is Gumbel-max:

    token = argmax_v( logit_v + g_v ),   g_v = -log(-log(u_v)),  u_v ~ U(0,1)

which is EXACTLY a categorical draw from ``softmax(logit)`` — no softmax
normalization, no sort, no top-k/top-p pivot search needed (the ``-max``
and ``/Z`` of softmax are constants that drop out of the argmax).

This module fuses that into ONE pass over the vocab:

  * the per-element Gumbel noise ``g_v`` is generated ON THE FLY from a
    **counter-based Philox4x32 RNG** keyed on ``(row_seed, vocab_index)``
    — so there is NO materialized ``(B, V)`` noise tensor and NO separate
    softmax pass;
  * a running argmax over the vocab tiles emits one token per row.

Cross-rank determinism (SPMD / TP). Because the noise is a pure function
of ``(row_seed, vocab_index)`` and ``row_seed`` is rank-agreed (derived
from the request's ``(seed, position)`` — the same source
``rank_symmetric.gumbel_exp_noise`` used), every TP rank generates
byte-identical noise and therefore selects the byte-identical token with
NO noise tensor exchanged between ranks. The single-process (c=1) path
uses the same kernel with a per-step seed drawn from the sampler-private
generator.

Distribution note. This is exact Gumbel-max = exact categorical from
``softmax(logits)``; it is the SAME distribution as the vendored
``_topk_topp_kernel`` Gumbel tail, not a bit-identical reproduction of a
specific ``torch`` noise draw. Temperature is folded into ``logits`` by
``apply_temperature`` upstream, so this kernel sees pre-scaled logits.

The ``@triton.jit`` kernels backing these wrappers live in the sibling
module :mod:`arbi_serve.sampler._gumbel_argmax_kernel` (split out purely
to keep each first-party file under the size cap); import the public API
from here.
"""

from __future__ import annotations

import torch

from arbi_serve.sampler._gumbel_argmax_kernel import (
    _draw_finish_kernel,
    _gumbel_at_indices_kernel,
    _gumbel_partial_kernel,
    _minp_partials_kernel,
    _qwrite_draw_partials_kernel,
    _residual_gumbel_partial_kernel,
    _seeded_gumbel_partial_kernel,
    _softmax_combine_kernel,
    _softmax_partials_kernel,
)
from arbi_serve.sampler._triton_util import next_pow2 as _next_pow2
from arbi_serve.sampler._triton_util import num_sm as _num_sm


def gumbel_argmax_from_seeds(
    logits: torch.Tensor,  # (B, V) fp32/bf16/fp16, CUDA
    row_seeds: torch.Tensor,  # (B,) int64 — per-row rank-agreed Philox seed
    *,
    block_size: int | None = None,
    index_base: int = 0,
) -> torch.Tensor:
    """Single-pass counter-based Gumbel-max sample → ``(B,)`` int64 tokens.

    Draws one token per row as ``argmax_v(logit_v + Gumbel(row_seed, v))``
    with the Gumbel noise generated on the fly (no materialized noise
    tensor, no separate softmax). ``row_seeds`` is the per-row Philox key:
    supply the rank-agreed ``(seed, position)``-derived seed for SPMD
    cross-rank determinism, or a per-step private-generator draw for the
    single-process path.

    ``logits`` is read-only (unlike the in-place top-k/top-p kernels).

    ``index_base`` keys the noise as if column 0 were that vocab index (one
    rank's vocab shard, :mod:`arbi_serve.sampler.vocab_shard_draw`); the
    returned indices are columns of ``logits``.
    """
    assert logits.ndim == 2
    assert logits.is_cuda
    assert logits.dtype in (torch.float32, torch.bfloat16, torch.float16)
    B, V = logits.shape
    out = logits.new_empty((B,), dtype=torch.int64)
    if B == 0:
        return out

    row_seeds = row_seeds.to(device=logits.device, dtype=torch.int64)
    assert row_seeds.shape == (B,), f"row_seeds {tuple(row_seeds.shape)} != ({B},)"

    # Fan each row across as many SMs as we can without oversubscribing:
    # total programs ~= SM count. B rows share the SMs, so SPLIT chunks
    # per row = SMs / B (>=1). At B=1 the single decode row spans every SM.
    num_sm = _num_sm(logits.device)
    split = max(1, num_sm // B)
    if block_size is None:
        # When each row already owns a full SM (split==1, large batch),
        # wider tiles amortize per-tile overhead; when a row is fanned
        # across SMs (small batch), each chunk is ~one tile so a smaller
        # tile keeps register pressure down. Measured ~28 µs (B=1) /
        # ~206 µs (B=128) on a 4090 at V=248320.
        block_size = 4096 if split == 1 else 2048
    # Cap SPLIT so each chunk is at least one full tile — more splits than
    # tiles just wastes programs on empty chunks.
    max_split = max(1, (V + block_size - 1) // block_size)
    split = min(split, max_split)

    n_programs = B * split
    part_score = logits.new_empty((n_programs,), dtype=torch.float32)
    part_idx = logits.new_empty((n_programs,), dtype=torch.int64)

    _gumbel_partial_kernel[(n_programs,)](
        logits,
        row_seeds,
        part_score,
        part_idx,
        B,
        split,
        int(index_base),
        VOCAB_SIZE=V,
        BLOCK_SIZE=block_size,
    )

    if split == 1:
        return part_idx

    # Finishing reduction: pick the winning chunk per row. Lowest-index
    # tie-break is inherited from contiguous chunking (lower vocab idx ⇒
    # lower split_id ⇒ first max under ``argmax``). Ties are measure-zero
    # under continuous Gumbel noise anyway.
    ps = part_score.view(B, split)
    pi = part_idx.view(B, split)
    win = ps.argmax(dim=1, keepdim=True)  # (B, 1)
    return pi.gather(1, win).squeeze(1)


def gumbel_argmax_from_seed_ptr(
    scores: torch.Tensor,  # (B, V) fp32/bf16/fp16, CUDA, contiguous
    seed_dev: torch.Tensor,  # (1,) int64, CUDA — the step seed
    *,
    draw_offset: int,
    block_size: int | None = None,
) -> torch.Tensor:
    """Single-pass counter-Gumbel sample keyed on a device seed → ``(B,)`` int64.

    Draws ``argmax_v(score_v + Gumbel(seed, row, v, draw_offset))`` per
    row — an exact categorical draw from ``softmax(scores)`` (pass
    per-row log-probs or masked logits; ``-inf`` entries are excluded
    from the support). Unlike :func:`gumbel_argmax_from_seeds` the Philox
    key is a single SHARED step seed read in-kernel from ``seed_dev``
    (no per-row seed tensor, no host readback — capture-safe), with
    ``(row, draw_offset)`` on the counter lanes for decorrelation. The
    noise is a pure function of ``(seed, row, v, draw_offset)``, so every
    SPMD/TP rank draws the byte-identical token from the rank-agreed
    seed with no exchange.

    ``draw_offset`` namespaces the draw class on counter lane 2 —
    distinct consumers sharing a step seed pass distinct offsets (the
    verify recovery/bonus kernel owns ``OFFSET_RECOVERY``; the drafter
    chain passes ``OFFSET_DRAFTER + 17 * step`` so the K chained calls'
    draws don't alias). Callers guarantee each row has at least one
    finite score (an all ``-inf`` row returns index 0).

    ``scores`` is read-only.
    """
    assert scores.ndim == 2 and scores.is_cuda
    assert scores.stride(-1) == 1, "scores vocab dim must be unit-stride"
    assert seed_dev.is_cuda and seed_dev.dtype == torch.int64 and seed_dev.numel() == 1
    B, V = scores.shape
    out = scores.new_empty((B,), dtype=torch.int64)
    if B == 0:
        return out
    if scores.stride(0) != V:
        scores = scores.contiguous()

    # Same fan-out heuristic as :func:`gumbel_argmax_from_seeds`.
    num_sm = _num_sm(scores.device)
    split = max(1, num_sm // B)
    if block_size is None:
        block_size = 4096 if split == 1 else 2048
    max_split = max(1, (V + block_size - 1) // block_size)
    split = min(split, max_split)

    n_programs = B * split
    part_score = scores.new_empty((n_programs,), dtype=torch.float32)
    part_idx = scores.new_empty((n_programs,), dtype=torch.int64)

    _seeded_gumbel_partial_kernel[(n_programs,)](
        scores,
        seed_dev,
        part_score,
        part_idx,
        B,
        split,
        DRAW_OFFSET=int(draw_offset),
        VOCAB_SIZE=V,
        BLOCK_SIZE=block_size,
    )

    if split == 1:
        return part_idx

    # Finishing reduction — same lowest-index tie-break inheritance as
    # :func:`gumbel_argmax_from_seeds` (contiguous chunking).
    ps = part_score.view(B, split)
    pi = part_idx.view(B, split)
    win = ps.argmax(dim=1, keepdim=True)  # (B, 1)
    return pi.gather(1, win).squeeze(1)


def residual_bonus_gumbel_from_seed(
    p_target: torch.Tensor,  # (K+1, B, V) fp32 CUDA probs, OR scaled logits if in_log_space
    draft_probs: torch.Tensor | None,  # (K, B, V) fp32 CUDA q_full, or None = one-hot
    seed_dev: torch.Tensor,  # (1,) int64, CUDA — the step seed
    *,
    draft_tokens: torch.Tensor | None = None,  # (K, B) int, CUDA — required iff one-hot
    in_log_space: bool = False,  # True → p_target holds scaled logits; softmax in-kernel
    lse: torch.Tensor | None = None,  # (K+1, B) fp32 CUDA row logsumexp — required iff in_log_space
    draw_offset: int = 1,
    block_size: int | None = None,
) -> torch.Tensor:
    """Single-pass counter-based recovery + bonus draws → ``(K+1, B)`` int64.

    Row ``k < K`` of the result is an exact categorical draw from the
    normalised Leviathan-2023 residual
    ``(p_target[k] - draft_probs[k])+ / Z`` (falling back to
    ``argmax(p_target[k])`` when the residual is everywhere zero); row
    ``K`` is an exact draw from ``p_target[K]``. The Gumbel noise is
    generated in-kernel from Philox keyed on ``(seed, row, vocab_index)``
    — no materialized ``(K+1, B, V)`` noise tensor, no separate softmax
    or full-vocab argmax pass, and byte-identical across ranks for the
    same seed (SPMD determinism without a noise exchange).

    ``draft_probs=None`` selects the INDEX-FORM point-mass proposal:
    ``q[k, b, v] = 1`` iff ``v == draft_tokens[k, b]``, synthesized per
    lane inside the kernel (constexpr-specialized; the dense
    specialization's generated code is unchanged). Bit-identical residual
    values to loading a densified one-hot; ``draft_tokens`` is required
    then and ignored in dense mode.

    ``seed_dev`` is read INSIDE the kernel (``tl.load``), so no host
    readback of a device seed and — once the surrounding eager tail is
    captured — a graph replay reads whatever ``copy_()`` last wrote into
    the buffer. ``draw_offset`` namespaces the draw class on a counter
    lane; distinct consumers sharing a seed pass distinct offsets.

    ``in_log_space=True`` fuses the softmax: ``p_target`` then holds the
    temperature-scaled (optionally top_k/top_p-masked) verify LOGITS and
    ``lse`` the precomputed ``(K+1, B)`` row ``logsumexp``, so the kernel
    computes ``p = exp(logit - lse)`` per lane — no dense ``(K+1, B, V)``
    probs tensor and no separate ``softmax`` launch. The drawn tokens are
    distributionally identical (softmax reduction-order aside, which the
    argmax draw is invariant to).

    ``p_target`` / ``draft_probs`` may be non-contiguous leading-dim
    slices of a persistent scratch pool (unit stride required only on the
    vocab dim). All operands are read-only.
    """
    assert p_target.ndim == 3
    assert p_target.is_cuda and seed_dev.is_cuda
    assert p_target.stride(-1) == 1, "p_target vocab dim must be unit-stride"
    Kp1, B, V = p_target.shape
    K = Kp1 - 1
    if in_log_space:
        assert lse is not None, (
            "residual_bonus_gumbel_from_seed: in_log_space=True requires the "
            "(K+1, B) row logsumexp `lse`"
        )
        assert lse.shape == (Kp1, B), f"lse {tuple(lse.shape)} != (K+1, B)=({Kp1}, {B})"
    onehot = draft_probs is None
    if onehot:
        assert draft_tokens is not None, (
            "residual_bonus_gumbel_from_seed: draft_probs=None (point-mass "
            "proposal) requires draft_tokens"
        )
        assert K == 0 or (draft_tokens.ndim == 2 and draft_tokens.shape == (K, B)), (
            f"draft_tokens {tuple(draft_tokens.shape)} != (K, B)=({K}, {B})"
        )
    else:
        assert draft_probs.ndim == 3
        assert draft_probs.shape == (K, B, V), (
            f"draft_probs {tuple(draft_probs.shape)} != (K, B, V)=({K}, {B}, {V})"
        )
        assert K == 0 or draft_probs.stride(-1) == 1, "draft_probs vocab dim must be unit-stride"
    n_rows = Kp1 * B
    # A (1,) seed is the classic scalar step seed (counter lanes carry
    # row + draw_offset); an (n_rows,) seed tensor selects the keyed-
    # watermark mode: one seed per (depth, row) flat row, zero lanes.
    per_row_seed = seed_dev.numel() != 1
    assert seed_dev.dtype == torch.int64 and (
        seed_dev.numel() == 1 or seed_dev.numel() == n_rows
    ), f"seed_dev numel {seed_dev.numel()} must be 1 or (K+1)*B={n_rows}"
    # Same fan-out heuristic as :func:`gumbel_argmax_from_seeds`: total
    # programs ~= SM count, so a small verify slate (c=1: K+1 rows) spans
    # every SM instead of leaving one program crawling 248k entries.
    num_sm = _num_sm(p_target.device)
    split = max(1, num_sm // n_rows)
    if block_size is None:
        block_size = 4096 if split == 1 else 2048
    max_split = max(1, (V + block_size - 1) // block_size)
    split = min(split, max_split)

    n_programs = n_rows * split
    part_score = p_target.new_empty((n_programs,), dtype=torch.float32)
    part_idx = p_target.new_empty((n_programs,), dtype=torch.int64)
    part_pval = p_target.new_empty((n_programs,), dtype=torch.float32)
    part_pidx = p_target.new_empty((n_programs,), dtype=torch.int64)

    if onehot:
        # Dummy Q pointer (never dereferenced under Q_IS_ONEHOT=True — the
        # constexpr compiles the dense load out); DRAFT carries the tokens.
        q_arg, q_sk, q_sb = p_target, 0, 0
        draft_int = draft_tokens.to(dtype=torch.int64)
        d_arg = draft_int
        d_sk = draft_int.stride(0) if K > 0 else 0
        d_sb = draft_int.stride(1) if K > 0 else 0
    else:
        # Dummy DRAFT pointer (never dereferenced under Q_IS_ONEHOT=False).
        q_arg = draft_probs
        q_sk = draft_probs.stride(0) if K > 0 else 0
        q_sb = draft_probs.stride(1) if K > 0 else 0
        d_arg, d_sk, d_sb = seed_dev, 0, 0

    if in_log_space:
        # Contiguous flat (K+1, B) row-major == the kernel's row = k*B + b.
        lse_arg = lse.contiguous().reshape(-1)
    else:
        lse_arg = seed_dev  # dummy pointer (never dereferenced under IN_LOG_SPACE=False)

    _residual_gumbel_partial_kernel[(n_programs,)](
        p_target,
        q_arg,
        d_arg,
        lse_arg,
        seed_dev,
        part_score,
        part_idx,
        part_pval,
        part_pidx,
        n_rows,
        K * B,
        B,
        split,
        p_target.stride(0),
        p_target.stride(1),
        q_sk,
        q_sb,
        d_sk,
        d_sb,
        Q_IS_ONEHOT=onehot,
        IN_LOG_SPACE=in_log_space,
        DRAW_OFFSET=int(draw_offset),
        VOCAB_SIZE=V,
        BLOCK_SIZE=block_size,
        PER_ROW_SEED=per_row_seed,
    )

    ps = part_score.view(n_rows, split)
    pi = part_idx.view(n_rows, split)
    win = ps.argmax(dim=1, keepdim=True)  # (n_rows, 1)
    tokens = pi.gather(1, win).squeeze(1)  # (n_rows,)
    best = ps.gather(1, win).squeeze(1)  # (n_rows,)

    # Degenerate fallback: a row whose residual is everywhere zero has
    # every partial at -inf; commit argmax(p_target) for it instead (the
    # draft distribution covers the target — any recovery is fine, the
    # eager sampler's contract picks the target's mode).
    fb_v = part_pval.view(n_rows, split)
    fb_i = part_pidx.view(n_rows, split)
    fwin = fb_v.argmax(dim=1, keepdim=True)
    fallback = fb_i.gather(1, fwin).squeeze(1)
    degenerate = best == float("-inf")
    tokens = torch.where(degenerate, fallback, tokens)
    return tokens.view(Kp1, B)


def gumbel_noise_at_indices(
    cand_idx: torch.Tensor,  # (K+1, B, C) int64 global vocab ids, CUDA
    seed_dev: torch.Tensor,  # (1,) int64 CUDA — the step seed
    *,
    draw_offset: int,
) -> torch.Tensor:
    """Full-vocab-identical Gumbel noise sampled AT candidate indices.

    Returns a ``(K+1, B, C)`` fp32 tensor whose ``[k, b, c]`` entry is the
    Gumbel(0,1) noise the counter-based full-vocab recovery/bonus kernel
    (:func:`residual_bonus_gumbel_from_seed`) generates at token
    ``cand_idx[k, b, c]`` for flat row ``k*B + b`` — so the shard-resident
    recovery/bonus draw over the compacted candidates draws from the SAME
    per-token noise realization as the gathered path, byte-for-byte, with
    no materialized ``(K+1, B, V)`` noise tensor and no host readback.

    ``draw_offset`` namespaces the draw class on counter lane 2 (the
    verify recovery/bonus tail passes ``OFFSET_RECOVERY``). ``seed_dev`` is
    read in-kernel, so a captured verify tail replays against whatever
    ``copy_()`` last wrote.
    """
    assert cand_idx.ndim == 3 and cand_idx.is_cuda
    assert cand_idx.dtype == torch.int64
    Kp1, B, C = cand_idx.shape
    n_rows = Kp1 * B
    # (1,) = scalar step seed; (n_rows,) = keyed-watermark per-row seeds.
    per_row_seed = seed_dev.numel() != 1
    assert (
        seed_dev.is_cuda
        and seed_dev.dtype == torch.int64
        and (seed_dev.numel() == 1 or seed_dev.numel() == n_rows)
    ), f"seed_dev numel {seed_dev.numel()} must be 1 or (K+1)*B={n_rows}"
    idx_flat = cand_idx.reshape(n_rows, C).contiguous()
    out = idx_flat.new_empty((n_rows, C), dtype=torch.float32)
    if n_rows == 0 or C == 0:
        return out.view(Kp1, B, C)
    block = _next_pow2(C)
    _gumbel_at_indices_kernel[(n_rows,)](
        idx_flat,
        seed_dev,
        out,
        n_rows,
        C,
        DRAW_OFFSET=int(draw_offset),
        BLOCK_SIZE=block,
        PER_ROW_SEED=per_row_seed,
    )
    return out.view(Kp1, B, C)


# ─── Fused drafter tail: softmax + min_p + counter-Gumbel draw ────────
#
# The drafter's per-step draw, after the (in-place, bit-identical) Qrita
# top-k / top-p mask, is
#     probs = softmax(masked);  [probs = min_p_mask(probs);]
#     q_chain = probs;  token = argmax(log(probs) + Gumbel(seed,row,offset))
# — in the unfused chain: ``torch.softmax`` + optional ``min_p_mask`` +
# ``.log()`` + ``gumbel_argmax_from_seed_ptr``. This fuses that whole tail
# into a single multi-SM operation (partial kernels + tiny finishing
# reduces) that fans the B=1 decode row across every SM (a lone program
# crawling a 152k-wide row is the cost the fan-out removes), generates the
# Gumbel noise in-kernel (capture-safe, no materialised noise tensor), and
# emits both the drawn token AND the ``q`` distribution the verify residual
# sampler consumes — in ONE pass over the masked logits for the draw.
#
# Bit-equivalence with the unfused tail: ``libdevice.exp`` (== ATen
# ``std::exp``) + ``tl.math.div_rn`` (== torch ``/``) + ``tl.log``
# (== torch.log) match torch element-for-element; the softmax reduction
# ORDER differs from ``torch.softmax``'s warp-shuffle tree, so ``q`` can
# differ by a few fp32 ULPs, but the drawn TOKEN and the kept SUPPORT are
# bit-identical (the ``−log Z`` softmax shift is a per-row constant under
# the Gumbel argmax — measured 0 token-flips / 0 support-diffs across the
# temperature × top_k × top_p grid incl. crafted boundary ties), and the
# residual sampler is lossless for any ``q`` (Leviathan-2023 Thm 1).


def fused_softmax_minp_gumbel_from_masked(
    masked: torch.Tensor,  # (B, V) fp32 CUDA — Qrita-masked logits (contiguous vocab)
    seed_dev: torch.Tensor,  # (1,) int64 CUDA — step seed (tl.load-ed in-kernel)
    *,
    draw_offset: int,
    min_p: torch.Tensor | None = None,  # (B,) fp32 CUDA per-row min_p (None disables)
    row_seeds: torch.Tensor | None = None,  # (B,) int64 CUDA — keyed per-row seeds
    block_size: int | None = None,
    q_out: torch.Tensor | None = None,  # (B, V) fp32 contiguous destination for q
    q_rows: torch.Tensor | None = None,  # (B,) int64 rows of a wider q_out
    tokens_out: torch.Tensor | None = None,  # (B,) int64 destination (any row stride)
) -> tuple[torch.Tensor, torch.Tensor]:
    """Fused multi-SM drafter tail → ``(tokens (B,), q (B, V))``.

    ``q_out`` is where ``q`` is written when the caller owns its destination
    (a block walk's persistent ``(S, rows, V)`` buffer row), so the vocab-wide
    fp32 ``q`` is written once instead of written here and copied there.
    ``tokens_out`` receives the drawn tokens (a column of a caller's block).
    ``q_rows`` places row ``i`` of the draw at ``q_out[q_rows[i]]`` (a block that
    realizes a subset of the buffer's columns); the other rows are not touched.

    Fans the (typically B=1) decode row across every SM: per-chunk
    online-softmax partials → global ``(max, Z)`` reduce → optional min_p
    kept-mass reduce → one q-write + counter-Gumbel draw pass → finishing
    argmax. Byte-matches the unfused ``torch.softmax`` [+ ``min_p_mask``] +
    ``gumbel_argmax_from_seed_ptr`` tail on the drawn TOKEN + kept SUPPORT
    (q within a few fp32 ULPs; lossless for the residual sampler). All
    reduces are capturable torch ops (no host readback); ``seed_dev`` is
    read in-kernel, so the captured chain replays against whatever
    ``copy_()`` last wrote.

    ``row_seeds`` selects the KEYED-WATERMARK draw instead of the step seed:
    one seed per row with zero counter lanes, the layout
    :func:`gumbel_argmax_from_seeds` and the model-free detector recompute.
    ``q`` does not depend on which mode ran — the keyed draw is this tail
    with a different Gumbel stream, not a different filtered distribution.

    The mode is its OWN argument rather than a shape test on ``seed_dev``,
    because ``B == 1`` is the common decode width: a ``(1,)`` keyed seed and
    a ``(1,)`` step seed are indistinguishable by shape, and reading one as
    the other would silently draw from the wrong noise stream on exactly the
    slate the drafter runs most.
    """
    assert masked.ndim == 2 and masked.is_cuda
    assert masked.stride(-1) == 1, "masked vocab dim must be unit-stride"
    B, V = masked.shape
    per_row_seed = row_seeds is not None
    if per_row_seed:
        assert row_seeds.dtype == torch.int64 and row_seeds.shape == (B,), (
            f"fused_softmax_minp_gumbel_from_masked: row_seeds "
            f"{tuple(row_seeds.shape)} != ({B},) int64"
        )
        seed_dev = row_seeds
    if masked.dtype != torch.float32:
        masked = masked.to(torch.float32)
    tokens = (
        tokens_out
        if tokens_out is not None and tokens_out.shape == (B,) and tokens_out.dtype == torch.int64
        else masked.new_empty((B,), dtype=torch.int64)
    )
    if q_out is None:
        q_out, q_rows = torch.empty((B, V), dtype=torch.float32, device=masked.device), None
    elif (
        q_out.shape != ((B, V) if q_rows is None else (q_out.shape[0], V))
        or (q_rows is not None and (q_rows.shape != (B,) or q_rows.dtype != torch.int64))
        or q_out.dtype != torch.float32
        or not q_out.is_contiguous()
        or q_out.device != masked.device
    ):
        raise ValueError(
            f"fused_softmax_minp_gumbel_from_masked: q_out {tuple(q_out.shape)} "
            f"{q_out.dtype} must be a contiguous ({B}, {V}) fp32 tensor on {masked.device}"
        )
    if B == 0:
        return tokens, q_out

    num_sm = _num_sm(masked.device)
    if block_size is None:
        split, block_size, draw_split, draw_block = fused_draw_geometry(B, V, num_sm)
    else:
        split = min(max(1, num_sm // B), max(1, (V + block_size - 1) // block_size))
        draw_split, draw_block = split, block_size
    n_programs = B * split

    part_max = masked.new_empty((n_programs,), dtype=torch.float32)
    part_sum = masked.new_empty((n_programs,), dtype=torch.float32)
    _softmax_partials_kernel[(n_programs,)](
        masked, part_max, part_sum, B, split, VOCAB_SIZE=V, BLOCK_SIZE=block_size
    )
    # Global (max, Z) per row: M = max chunk max; Z = Σ chunk_sum·exp(chunk_max − M).
    # One launch for the combine's elementwise terms; the row sum stays aten's
    # (``_softmax_combine_kernel``), so Z is reduced in aten's order. The block
    # spans the widest split (``num_sm``), so one compile serves every batch.
    row_max = masked.new_empty((B,), dtype=torch.float32)
    weighted = masked.new_empty((B, split), dtype=torch.float32)
    _softmax_combine_kernel[(B,)](
        part_max, part_sum, row_max, weighted, split, BLOCK_S=_next_pow2(num_sm)
    )
    row_z = weighted.sum(dim=1)  # (B,)

    minp_enabled = min_p is not None
    if minp_enabled:
        assert min_p.shape == (B,)
        min_p = min_p.to(device=masked.device, dtype=torch.float32)
        part_mpsum = masked.new_empty((n_programs,), dtype=torch.float32)
        _minp_partials_kernel[(n_programs,)](
            masked, row_max, row_z, min_p, part_mpsum, B, split, VOCAB_SIZE=V, BLOCK_SIZE=block_size
        )
        minp_sum = part_mpsum.view(B, split).sum(dim=1)  # (B,)
    else:
        min_p = masked  # dummy pointer (unread when MINP_ENABLED is False)
        minp_sum = masked  # dummy pointer

    part_score = masked.new_empty((B * draw_split,), dtype=torch.float32)
    part_idx = masked.new_empty((B * draw_split,), dtype=torch.int64)
    _qwrite_draw_partials_kernel[(B * draw_split,)](
        masked,
        row_max,
        row_z,
        min_p,
        minp_sum,
        seed_dev,
        q_out,
        q_rows if q_rows is not None else q_out,
        part_score,
        part_idx,
        B,
        draw_split,
        MINP_ENABLED=minp_enabled,
        # The keyed mode zeroes counter lanes 1-2, so DRAW_OFFSET is unread
        # there. Passing it anyway would specialize one kernel per drafted
        # depth on a value none of them reads — S compiles for one program.
        DRAW_OFFSET=0 if per_row_seed else int(draw_offset),
        VOCAB_SIZE=V,
        BLOCK_SIZE=draw_block,
        PER_ROW_SEED=per_row_seed,
        HAS_QROWS=q_rows is not None,
    )
    if draw_split == 1:
        if tokens is not tokens_out:
            return part_idx, q_out
        tokens.copy_(part_idx)
        return tokens, q_out
    _draw_finish_kernel[(B,)](
        part_score, part_idx, tokens, draw_split, tokens.stride(0), BLOCK_S=_next_pow2(draw_split)
    )
    return tokens, q_out


#: Column tiles one q-write + draw program may take, widest first.
_DRAW_BLOCKS = (2048, 1024, 512)
#: Waves of the device's SMs the q-write + draw grid is sized to fill.
_DRAW_WAVES = 2


def fused_draw_geometry(rows: int, vocab: int, num_sm: int) -> tuple[int, int, int, int]:
    """``(split, block, draw_split, draw_block)`` of :func:`fused_softmax_minp_gumbel_from_masked`.

    ``split``/``block`` chunk the softmax partials, whose chunking is the order ``Z`` is
    summed in. The q write and the draw are elementwise in ``q`` and chunk-invariant in
    the token (lowest index within a chunk, first chunk on a tie), so they take their own
    grid: one tile per program, the widest tile whose grid still fills ``_DRAW_WAVES``
    waves, the narrowest tile the floor."""
    split = max(1, num_sm // rows)
    block = 4096 if split == 1 else 2048
    split = min(split, max(1, -(-vocab // block)))
    draw_block = next(
        (b for b in _DRAW_BLOCKS if rows * -(-vocab // b) >= _DRAW_WAVES * num_sm),
        _DRAW_BLOCKS[-1],
    )
    return split, block, -(-vocab // draw_block), draw_block
# ---- harmony_grammar.py ----
# SPDX-License-Identifier: Apache-2.0
"""Harmony-shaped xgrammar structural tags for gpt-oss forced tool calls and ``response_format``."""

from __future__ import annotations

import json
from typing import Any

from arbi_serve.engine.request import ResponseFormat

#: Harmony control tokens, pinned as tokens so their BPE spelling can never stand in for them.
SPECIALS = (
    "<|start|>",
    "<|end|>",
    "<|message|>",
    "<|channel|>",
    "<|constrain|>",
    "<|return|>",
    "<|call|>",
    "<|endoftext|>",
)


def _analysis(st: Any) -> Any:
    """One ``analysis`` message and the next assistant header: free reasoning, no control tokens."""
    return st.SequenceFormat(
        elements=[
            st.TokenFormat(token="<|channel|>"),
            st.ConstStringFormat(value="analysis"),
            st.TokenFormat(token="<|message|>"),
            st.AnyTokensFormat(exclude_tokens=list(SPECIALS)),
            st.TokenFormat(token="<|end|>"),
            st.TokenFormat(token="<|start|>"),
            st.ConstStringFormat(value="assistant"),
        ]
    )


def _after_reasoning(st: Any, body: Any) -> Any:
    """Any number of analysis messages, then ``body``."""
    return st.SequenceFormat(elements=[st.StarFormat(content=_analysis(st)), body])


def _call(st: Any, name: str, params: dict) -> Any:
    """A call to ``name`` with its recipient in the channel header or the role header."""
    tail = [
        st.TokenFormat(token="<|constrain|>"),
        st.ConstStringFormat(value="json"),
        st.TokenFormat(token="<|message|>"),
        st.JSONSchemaFormat(json_schema=params, style="json"),
    ]
    in_channel = st.SequenceFormat(
        elements=[
            st.TokenFormat(token="<|channel|>"),
            st.ConstStringFormat(value=f"commentary to=functions.{name} "),
            *tail,
        ]
    )
    in_role = st.SequenceFormat(
        elements=[
            st.ConstStringFormat(value=f" to=functions.{name}"),
            st.TokenFormat(token="<|channel|>"),
            st.ConstStringFormat(value="commentary "),
            *tail,
        ]
    )
    return st.OrFormat(elements=[in_channel, in_role])


def _final(st: Any, element: Any) -> Any:
    """``<|channel|>final<|message|>`` then ``element``."""
    return st.SequenceFormat(
        elements=[
            st.TokenFormat(token="<|channel|>"),
            st.ConstStringFormat(value="final"),
            st.TokenFormat(token="<|message|>"),
            element,
        ]
    )


def _format_element(st: Any, rf: ResponseFormat) -> Any | None:
    """The xgrammar element a ``response_format`` asks the final message to be."""
    if rf.type == "json_object":
        return st.JSONSchemaFormat(json_schema={"type": "object"}, style="json")
    if rf.type == "json_schema":
        schema = json.loads(rf.schema) if isinstance(rf.schema, str) else rf.schema
        return st.JSONSchemaFormat(json_schema=schema, style="json")
    if rf.type == "regex":
        return st.RegexFormat(pattern=rf.regex)
    if rf.type == "grammar":
        return st.GrammarFormat(grammar=rf.grammar)
    return None


def _rf(st: Any, fmt: Any) -> ResponseFormat:
    tag = st.StructuralTag(format=fmt)
    return ResponseFormat(type="structural_tag", structural_tag=tag.model_dump_json())


def response_format_tag(rf: ResponseFormat) -> ResponseFormat:
    """Constrain only the ``final`` message to ``rf``; analysis before it stays free."""
    import xgrammar.structural_tag as st

    element = _format_element(st, rf)
    if element is None:
        return rf
    return _rf(st, _after_reasoning(st, _final(st, element)))


def tool_call_tag(tools: Any, tool_choice: Any) -> ResponseFormat | None:
    """A forced call (``required`` or named) in Harmony's call shape; ``None`` for ``auto``."""
    import xgrammar.structural_tag as st

    from arbi_serve.sampler.tool_grammar import _function_name_and_params, _resolve_choice

    mode, only = _resolve_choice(tool_choice)
    if mode == "auto":
        return None
    calls = []
    for tool in tools or ():
        name, params = _function_name_and_params(tool)
        if name and (only is None or name == only):
            calls.append(_call(st, name, params))
    if not calls:
        return None
    body = calls[0] if len(calls) == 1 else st.OrFormat(elements=calls)
    return _rf(st, _after_reasoning(st, body))


def harmony_response_format(sampling: Any) -> ResponseFormat | None:
    """gpt-oss's grammar for a request: ``response_format`` first, then a forced tool call."""
    rf = getattr(sampling, "response_format", None)
    if rf is not None and getattr(rf, "type", "text") != "text":
        return response_format_tag(rf)
    if not getattr(sampling, "tools", None) or getattr(sampling, "tool_choice", None) == "none":
        return None
    return tool_call_tag(sampling.tools, sampling.tool_choice)
# ---- kernel_warmup.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Boot-time pre-compile of the stochastic sampler's Triton kernels.

The captured decode path warms the GREEDY sampler at boot (argmax rides
the captured graphs), but the stochastic tail — the Qrita top-k/top-p
mask kernel and the counter-based Gumbel-max kernel — compiles lazily on
the FIRST ``temperature > 0`` request, which on a production chat serve
(Wise preset: temp 1.0 / top_p 0.95 / top_k 20) is the very first
request.

:func:`warm_sampler_kernels` drives the SAME wrapper entries the serving
sampler dispatches into (``apply_top_k_top_p_triton``,
``gumbel_argmax_from_seeds``, ``sample_top_k_top_p_triton``,
``apply_penalties_fused``) over the bounded specialization set the
served config can reach:

* batch rows ``B``: Triton value-specializes integer scalars into three
  classes — ``== 1``, ``% 16 == 0``, other. The Gumbel kernel's cache
  key adds its ``split`` scalar (derived from ``num_SMs / B``) and the
  split-dependent ``BLOCK_SIZE`` constexpr, so the warm set is computed
  DEVICE-ADAPTIVELY: walk every ``B`` in ``1..max_batch``, mirror the
  wrapper's ``split``/``BLOCK_SIZE`` derivation, and warm one
  representative ``B`` per distinct specialization-class tuple. Those
  rows also cover every ``class(B)`` — the only ``B`` axis the mask and
  penalty kernels key on.
* mask-kernel AXIS ENABLEMENT (:data:`_TOPK_TOPP_AXIS_CLASSES`): each of
  ``k``/``p`` present-or-``None`` is a SEPARATE compiled kernel, twice
  over — it flips the ``TOPK_ENABLED``/``TOPP_ENABLED`` constexpr AND
  changes the disabled argument's POINTER DTYPE (``_launch_topk_topp``
  passes ``logits`` itself as the dummy pointer, so a disabled ``p``
  turns the ``*fp32`` P slot into ``*bf16``). The served sampler emits
  all three enabled combinations, because
  :func:`~arbi_serve.sampler.sampling_masks._fused_topk_topp_args`
  returns ``None`` for an axis no row asks for and ``top_p >= 1.0``
  counts as "not asked for" (``sampling_metadata``: ``any_tp`` is set
  only by ``top_p < 1.0``). A ``top_p=1.00`` model card — Qwen3.5-0.8B's
  documented non-thinking preset — therefore serves the ``(k, None)``
  kernel, which a ``(k, p)``-only warm never compiles. Each combination
  is warmed for BOTH the mask-only entry and the fused mask+sample one,
  plus the sample-only (``k=None, p=None``) variant of the SPMD
  noise-supplied path.
* penalty knobs (:data:`_PENALTY_KNOB_CLASSES`): ``HAS_REP`` /
  ``HAS_FREQ`` / ``HAS_PRES`` are constexprs on the fused penalty
  kernel, so each non-empty subset of the three knobs is its own
  compiled kernel. Which subsets and which COUNT SOURCE are reachable
  depends on whether the engine installed the accumulator pool — see
  :func:`_warm_penalty_kernels`. ``B`` is a runtime scalar there too
  (three classes), and the counts buffer's dtype and ROW STRIDE are part
  of the key.

The LSE-emitting variant stays lazy: the MTP rejection sampler's LSE
fusion is warmed by the MTP verify boot path where MTP is enabled. min-p
does NOT stay lazy — it is a served request field, and on the sampled-draft
tail it is a ``tl.constexpr`` that re-keys the whole draw-offset ladder (see
:func:`warm_stochastic_drafter_kernels`).

This enumerated set is the A-PRIORI half of warmup coverage: it is what
makes the very FIRST boot at a build/arch warm, before anything has been
observed. It is not the whole of coverage, and it is not where a newly
discovered gap belongs. A specialization that escapes it is named by
:mod:`arbi_serve.jit_detector` and recorded by
:mod:`arbi_serve.jit_replay`, which pre-compiles it at the next boot from
Triton's own serialized specialization — no shapes to reverse-engineer and
no warm code to keep in sync with the kernel. Add to this module only what
a first boot must have; let the record cover the rest.

Failure here is logged loud and non-fatal: an unwarmed kernel costs the
first matching request its compile latency (which the detector reports);
it never makes a result wrong.
"""

from __future__ import annotations

import logging
import os
import sys
from pathlib import Path

import torch

import arbi_serve._custom_ops  # noqa: F401 — registers the ops the verify warm drives
from arbi_serve.sampler.watermark_warmup import (  # noqa: F401 — re-exported
    _wm_state_slates,
    warm_watermark_state_kernels,
)

logger = logging.getLogger("arbi_serve.sampler.kernel_warmup")

__all__ = [
    "warm_mtp_verify_sampler_kernels",
    "warm_sampler_kernels",
    "warm_stochastic_drafter_kernels",
    "warm_structured_output_kernel",
]

#: ``(device, vocab, max_batch)`` whose stochastic TAIL (mask, fused mask+sample, counter-Gumbel,
#: sample-only) :func:`warm_sampler_kernels` has compiled. The tail's variants depend on nothing else.
_SAMPLER_WARMED: set[tuple[str, int, int]] = set()

#: ``(device, vocab, max_batch, pooled)`` whose fused PENALTY kernels have been compiled. Separate from the
#: tail because the penalty variant set also depends on whether the accumulator pool is installed
#: (:func:`_warm_penalty_kernels`): one memo for both would mark a pooled config warm after an unpooled
#: warm, and its pooled count-source variants would compile under traffic.
_PENALTY_WARMED: set[tuple[str, int, int, bool]] = set()

#: ``(top_k_enabled, top_p_enabled)`` classes the SERVING top-k/top-p mask
#: kernel can be launched with. ``_fused_topk_topp_args`` hands the wrapper
#: ``None`` for an axis no row in the batch asks for, and each ``None``
#: is a distinct compiled kernel (constexpr gate + dummy-pointer dtype).
#: ``(False, False)`` is NOT here: the sampler never reaches the mask with
#: both axes off — that batch takes the no-filter Gumbel path, or the
#: sample-only tail, both warmed separately below.
_TOPK_TOPP_AXIS_CLASSES: tuple[tuple[bool, bool], ...] = (
    (True, True),  # top_k + top_p (Qwen thinking preset: top_p 0.95)
    (True, False),  # top_k only — top_p >= 1.0 (Qwen non-thinking: top_p 1.00)
    (False, True),  # top_p only — no top_k (a bare OpenAI client)
)

#: The served chat preset's ``top_k`` / ``top_p`` (Qwen thinking: 20 / 0.95).
#: The mask warm builds its per-row tensors from these AND hands the same
#: values to the dispatch as the host-side pair, because which of the two
#: mask kernels runs (the fanned top-C or the vendored pivot) is decided
#: from the HOST values, not from the tensors.
_WARM_TOP_K = 20
_WARM_TOP_P = 0.95

#: ``(top_k, top_p)`` VALUES the sampled-draft tail's mask is served with —
#: the same three classes as :data:`_TOPK_TOPP_AXIS_CLASSES`, spelled as
#: values because the drafter's parameter encoder never passes ``None``: an
#: unasked ``top_k`` arrives as the vocab size and an unasked ``top_p`` as
#: ``1.0``. ``top_k=-1`` is ``SamplingParams``' "no top_k" spelling; the
#: encoder maps it to ``V``.
_DRAFTER_AXIS_PRESETS: tuple[tuple[int, float], ...] = (
    (_WARM_TOP_K, _WARM_TOP_P),  # top_k + top_p (Qwen thinking preset)
    (_WARM_TOP_K, 1.0),  # top_k only — top_p >= 1.0 (Qwen non-thinking)
    (-1, 0.9),  # top_p only — no top_k (a bare OpenAI client)
)

#: A representative non-zero ``min_p`` for the sampled-draft warm. Only
#: whether it is set is keyed (``MINP_ENABLED`` is a ``tl.constexpr`` on the
#: fused filter+draw), never the value.
_WARM_MIN_P = 0.05

#: ``(has_rep, has_freq, has_pres)`` classes of the fused penalty kernel.
#: All three are ``tl.constexpr``, so every non-empty subset compiles its
#: own kernel; a request may set any of them independently. The empty
#: subset never launches (``apply_penalties`` returns early).
_PENALTY_KNOB_CLASSES: tuple[tuple[bool, bool, bool], ...] = tuple(
    (bool(m & 4), bool(m & 2), bool(m & 1)) for m in range(1, 8)
)


def _over_capacity_top_k(device: torch.device, vocab_size: int) -> int | None:
    """The narrowest served ``top_k`` the fanned top-C mask refuses (``capacity + 1``).

    Past the capacity (``topk_over_capacity``: any client's ``top_k=50``) the spec-decode
    mask dispatch falls back to the pivot ``_topk_topp_kernel``, a separate compiled
    program the ``top_k=20`` presets never reach. ``None`` when no top_k is refused
    (capacity off, or the row no wider than it): every slate then takes the pivot."""
    from arbi_serve.spec_decode.rejection_sampler_ops import topc_mask_capacity

    cap = int(topc_mask_capacity(device))
    return cap + 1 if cap > 0 and cap + 1 < int(vocab_size) else None


def _mask_slates(p: torch.Tensor, width: int, wide_k: int | None) -> list[tuple]:
    """``(k, host top_ks, p, host top_ps)`` for every served mask class of a ``width``-wide row.

    Each top_k-carrying class twice: at the served top_k (the fanned top-C mask) and,
    when one exists, past the capacity (``wide_k``, the pivot fallback). The dispatch
    picks between them from the host value, so both are served kernels. A disabled
    axis is spelled as its disabled value (``top_k = width`` / ``top_p = 1.0``), the
    way the serving encoder spells it."""
    out = []
    for topk_on, topp_on in _TOPK_TOPP_AXIS_CLASSES:
        p_arg, hp = (p, (_WARM_TOP_P,)) if topp_on else (None, (1.0,))
        for top_k in ([_WARM_TOP_K] + ([wide_k] if wide_k else [])) if topk_on else [width]:
            k_arg = torch.full(p.shape, top_k, dtype=torch.int64, device=p.device)
            out.append((k_arg if topk_on else None, (top_k,), p_arg, hp))
    return out


def _spec_class(v: int) -> str:
    """Triton's integer-scalar specialization class for value ``v``."""
    if v == 1:
        return "1"
    return "16" if v % 16 == 0 else "other"


def _representative_rows(device: torch.device, vocab_size: int, max_batch: int) -> list[int]:
    """One ``B`` per distinct Gumbel-kernel specialization tuple.

    Asks :func:`~arbi_serve.sampler.gumbel_argmax_triton.fused_draw_geometry`
    (whose ``split``/``block_size`` are also ``gumbel_argmax_from_seeds``'s)
    for every servable ``B`` and keeps the first ``B`` producing each new
    ``(class(B), class(split), block_size, draw_block, class(draw_split))``
    tuple — the axes the compiled-kernel cache is keyed on. Bounded: at most a handful of
    rows regardless of ``max_batch``.
    """
    from arbi_serve.sampler.gumbel_argmax_triton import _num_sm, fused_draw_geometry

    num_sm = _num_sm(device)
    seen: set[tuple] = set()
    rows: list[int] = []
    for b in range(1, max(1, int(max_batch)) + 1):
        split, block_size, draw_split, draw_block = fused_draw_geometry(b, vocab_size, num_sm)
        key = (_spec_class(b), _spec_class(split), block_size, draw_block, _spec_class(draw_split))
        if key not in seen:
            seen.add(key)
            rows.append(b)
    return rows


def _verify_slates(
    device: torch.device, vocab_size: int, k_plus_1: int, max_batch: int
) -> list[tuple[int, int]]:
    """One ``(K+1, B)`` slate per distinct residual/bonus specialization tuple.

    The verify slate is ``(K+1, B)`` FLAT rows, so
    :func:`~arbi_serve.sampler.gumbel_argmax_triton.
    residual_bonus_gumbel_from_seed` derives its ``split`` /
    ``BLOCK_SIZE`` from ``n_rows = (K+1)·B``, not from ``B`` — a
    different ladder from :func:`_representative_rows`.

    BOTH slate dims are walked, because both are servable and both move
    the key. ``K`` is not fixed at the drafter's ``max_k``: a slate
    accepts at the step's UNIFORM ``K_step``, which a per-row ``mtp_k``,
    a drafter fallback, dynamic-``K`` or a depth gate can shorten to any
    ``1..max_k``. ``split = num_SMs // n_rows`` then lands on a different
    value, and its divisibility-by-16 class is a cache-key axis — so
    warming only the deepest chain leaves every shallower one cold.

    Keeps the first ``(K+1, B)`` producing each new ``(class(B),
    class(n_rows), class(K·B), class(split), block_size)`` tuple, the
    axes the compiled-kernel cache is keyed on. The pointer strides are
    NOT axes here: the warm slices the same persistent
    ``(max_k+1, max_batch, V)`` / ``(max_k, max_batch, V)`` /
    ``(max_k, max_batch)`` verify buffers the serving path slices, whose
    leading strides are slate-invariant. Bounded: a handful of slates
    regardless of ``max_k`` or ``max_batch``.

    Empty below ``k_plus_1 == 2``: a ``K == 0`` step drafts nothing, so
    there is no residual to draw and no launch to warm.
    """
    from arbi_serve.sampler.gumbel_argmax_triton import _num_sm

    num_sm = _num_sm(device)
    v = int(vocab_size)
    seen: set[tuple[str, str, str, str, int]] = set()
    slates: list[tuple[int, int]] = []
    for kp1 in range(2, int(k_plus_1) + 1):
        for b in range(1, max(1, int(max_batch)) + 1):
            n_rows = kp1 * b
            split = max(1, num_sm // n_rows)
            block_size = 4096 if split == 1 else 2048
            split = min(split, max(1, (v + block_size - 1) // block_size))
            key = (
                _spec_class(b),
                _spec_class(n_rows),
                _spec_class((kp1 - 1) * b),
                _spec_class(split),
                block_size,
            )
            if key not in seen:
                seen.add(key)
                slates.append((kp1, b))
    return slates


def warm_sampler_kernels(device: torch.device, vocab_size: int, max_batch: int) -> int:
    """Pre-compile the sampler's Triton kernels for the served shapes.

    Covers the stochastic tail (top-k/top-p mask, fused mask+sample,
    counter-Gumbel) AND the fused penalty kernel — everything the
    per-step sampler chain can dispatch outside the captured graphs.

    Returns the number of warm launches issued (0 when CUDA/Triton is
    unavailable). The allocations are ``(B, V)`` fp32/bf16 transients at
    every row count :func:`_representative_rows` selects, the widest being
    ``max_batch`` itself: they scale with the vocabulary and are dead when
    this returns, but the caching allocator keeps their segments reserved.

    Each kernel family is memoised on exactly what selects its variants: the
    tail on ``(device, vocab, max_batch)`` (:data:`_SAMPLER_WARMED`), the
    penalty kernels on that plus whether the accumulator pool is installed
    (:data:`_PENALTY_WARMED`). A family already warm for its key launches and
    allocates nothing: the compiled kernels are process-wide, so a repeat only
    re-takes the transients above from a later phase's free VRAM (the
    post-freeze serve-kernel warmup repeats the pre-grow prewarm). A warm that
    finds every family warm returns 0 before allocating; one that finds the
    pool state changed warms only the penalty variants that change brings.
    """
    if not torch.cuda.is_available():
        return 0
    key = (str(device), int(vocab_size), int(max_batch))
    pooled = _penalty_pool_installed()
    penalty_key = (*key, pooled)
    tail_warm = key in _SAMPLER_WARMED
    if tail_warm and penalty_key in _PENALTY_WARMED:
        return 0
    v = int(vocab_size)
    rows = _representative_rows(device, v, max_batch)
    progress = _ShapeProgress(len(rows) * ((not tail_warm) + (penalty_key not in _PENALTY_WARMED)))
    n = 0
    try:
        if not tail_warm:
            n += _warm_tail_kernels(device, v, rows, progress)
            _SAMPLER_WARMED.add(key)
        if penalty_key not in _PENALTY_WARMED:
            n += _warm_penalty_kernels(device, v, rows, pooled, progress)
            _PENALTY_WARMED.add(penalty_key)
    finally:
        progress.close()
    if n and not tail_warm:
        _note_warm_saved(device, v, int(max_batch))
    return n


def _warm_record(device: torch.device, vocab_size: int, max_batch: int) -> Path | None:
    """The file a finished warm leaves in the pinned Triton cache, keyed on what selects its kernels."""
    root = os.environ.get("TRITON_CACHE_DIR")
    if not root:
        return None
    import hashlib

    import triton

    from arbi_serve.sampler import gumbel_argmax_triton, penalty_triton, topk_topp_triton

    key = f"{torch.cuda.get_device_name(device)}|{vocab_size}|{max_batch}|{triton.__version__}"
    h = hashlib.sha256(f"{key}|{_penalty_pool_installed()}".encode())
    for mod in (gumbel_argmax_triton, penalty_triton, topk_topp_triton, sys.modules[__name__]):
        h.update(Path(str(mod.__file__)).read_bytes())
    return Path(root) / "arbi-sampler-warm" / h.hexdigest()[:24]


def sampler_warm_saved(device: torch.device, vocab_size: int, max_batch: int) -> bool | None:
    """Whether an earlier boot's warm of these sampler kernels sits in the Triton cache; ``None`` if unknown."""
    try:
        path = _warm_record(device, int(vocab_size), int(max_batch))
    except Exception:  # noqa: BLE001 — a note must never cost the boot
        return None
    return None if path is None else path.exists()


def _note_warm_saved(device: torch.device, vocab_size: int, max_batch: int) -> None:
    try:
        path = _warm_record(device, vocab_size, max_batch)
        if path is not None:
            path.parent.mkdir(parents=True, exist_ok=True)
            path.touch()
    except Exception:  # noqa: BLE001 — the record is a log note, never a boot failure
        pass


class _ShapeProgress:
    """Publishes how many of the warm's ``(family, rows)`` shapes have compiled, for the boot heartbeat."""

    def __init__(self, total: int) -> None:
        self.done, self.total = 0, total

    def __call__(self) -> None:
        from arbi_serve import boot_progress

        self.done += 1
        boot_progress.count_progress("sampler", self.done, self.total, "sampler shapes compiled")

    def close(self) -> None:
        from arbi_serve import boot_progress

        boot_progress.clear_progress("sampler")


def _penalty_pool_installed() -> bool:
    """Whether the engine installed the penalty accumulator pool (selects the penalty variants)."""
    from arbi_serve.sampler.penalty_accumulator import _POOL_ALLOCATE

    return _POOL_ALLOCATE is not None


def _warm_tail_kernels(device: torch.device, v: int, rows: list[int], progress=lambda: None) -> int:
    """The stochastic tail of :func:`warm_sampler_kernels`: mask, fused mask+sample, Gumbel, sample-only."""
    from arbi_serve.sampler.gumbel_argmax_triton import gumbel_argmax_from_seeds
    from arbi_serve.sampler.topk_topp_triton import (
        apply_top_k_top_p_triton,
        sample_top_k_top_p_triton,
    )

    n = 0
    # Argument dtypes mirror the SERVING call sites exactly — the kernels
    # specialize on them, so a warm at the wrong dtype compiles a variant
    # the live path never asks for (the first post-fix audit measured
    # exactly that: fp32/int32-warmed kernels recompiling under traffic
    # for the bf16-logits / int64-k serving signature). The sampling
    # chain runs in the model's logits dtype (bf16 on the canonical
    # serve; fp32 on fp32-logits paths — warm both); ``sm.top_k`` is
    # int64; ``top_p`` and noise are fp32.
    for b in rows:
        k = torch.full((b,), 20, dtype=torch.int64, device=device)
        p = torch.full((b,), 0.95, dtype=torch.float32, device=device)
        seeds = torch.arange(1, b + 1, dtype=torch.int64, device=device)
        noise = torch.rand(b, v, dtype=torch.float32, device=device).clamp_min(1e-10)
        for logits_dtype in (torch.bfloat16, torch.float32):
            logits = torch.randn(b, v, dtype=logits_dtype, device=device)
            for topk_on, topp_on in _TOPK_TOPP_AXIS_CLASSES:
                k_arg = k if topk_on else None
                p_arg = p if topp_on else None
                # Re-randomize between launches: each mask writes -inf over
                # all but the surviving lanes, and a row that is entirely
                # -inf is not a shape the serving pivot search ever sees.
                # Values do not affect the specialization; a degenerate row
                # would only risk a pathological warm launch.
                logits.normal_()
                # Filtered mask-only entry (the counter-Gumbel path masks,
                # then draws with gumbel_argmax_from_seeds).
                apply_top_k_top_p_triton(logits, k_arg, p_arg)
                logits.normal_()
                # Fused mask+sample entry (SPMD noise-supplied path).
                sample_top_k_top_p_triton(logits, k_arg, p_arg, noise)
                n += 2
            logits.normal_()
            gumbel_argmax_from_seeds(logits, seeds)
            # Sample-only launch: the already-masked SPMD tail.
            sample_top_k_top_p_triton(logits, None, None, noise)
            n += 2
            del logits
        del noise
        progress()
    return n


def _warm_penalty_kernels(
    device: torch.device, vocab_size: int, rows: list[int], pooled: bool, progress=lambda: None
) -> int:
    """Pre-compile the fused repetition/frequency/presence penalty kernel.

    The per-step sampler chain dispatches it for any request that sets a
    penalty, outside every captured graph.

    Which variants are REACHABLE depends on the accumulator pool, so this
    reads the same hook :func:`~arbi_serve.sampler.penalty_accumulator.
    get_penalty_accumulator` dispatches on and warms only what the served
    config can launch. The boot order guarantees the answer is final:
    ``_install_penalty_accumulator`` runs in the model-load phase, long
    before the serve-kernel warmup.

    * POOL INSTALLED (the production boot). Presence / frequency without
      repetition never reach a kernel at all — they are one subtraction of
      the accumulator's delta — so only the four ``HAS_REP`` subsets are
      warmed. ``counts`` is the accumulator's persistent occurrence
      buffer: INT32, contiguous ``(B, V)``, row stride ``V``.
    * NO POOL. Every request builds the fallback matrix, so all seven
      subsets are reachable. ``counts`` is built there as
      ``torch.zeros(B, V + 1)[:, :V]`` — the trailing column is the
      scatter's pad sink, so its ROW STRIDE is ``V + 1``, not ``V``.

    Both details are load-bearing: Triton keys the compiled kernel on the
    pointer dtype and specializes integer arguments on divisibility-by-16,
    so warming the wrong count source leaves the served one cold.
    ``rep``/``freq``/``pres`` are cast to the LOGITS dtype at the call
    site, so the warm casts them the same way.
    """
    from arbi_serve.sampler.penalty_triton import apply_penalties_fused

    classes = tuple(c for c in _PENALTY_KNOB_CLASSES if c[0]) if pooled else _PENALTY_KNOB_CLASSES
    v = int(vocab_size)
    n = 0
    for b in rows:
        if pooled:
            counts = torch.zeros(b, v, dtype=torch.int32, device=device)
        else:
            counts = torch.zeros(b, v + 1, dtype=torch.float32, device=device)[:, :v]
        for logits_dtype in (torch.bfloat16, torch.float32):
            # (K, B, V) with K=1: K only scales the grid's row count, it is
            # not a cache-key axis (the kernel takes B, not K, as a scalar).
            logits = torch.randn(1, b, v, dtype=logits_dtype, device=device)
            rep = torch.ones(b, dtype=logits_dtype, device=device)
            freq = torch.zeros(b, dtype=logits_dtype, device=device)
            pres = torch.zeros(b, dtype=logits_dtype, device=device)
            for has_rep, has_freq, has_pres in classes:
                apply_penalties_fused(logits, counts, rep, freq, pres, has_rep, has_freq, has_pres)
                n += 1
            del logits, rep, freq, pres
        del counts
        progress()
    return n


def _row_classes(max_rows: int) -> list[int]:
    """One representative row count per Triton integer-scalar class.

    An ``n``-row launch is compiled per :func:`_spec_class` of ``n``, so
    walking ``1..max_rows`` and keeping the first of each class covers
    every reachable row count with at most three launches.
    """
    seen: set[str] = set()
    rows: list[int] = []
    for n in range(1, max(1, int(max_rows)) + 1):
        c = _spec_class(n)
        if c not in seen:
            seen.add(c)
            rows.append(n)
    return rows


def warm_structured_output_kernel(device: torch.device, vocab_size: int, max_rows: int) -> int:
    """Pre-compile xgrammar's token-bitmask kernel for the served shapes.

    Any request may carry a ``response_format``, so the structured-output
    mask is always reachable at serving; it runs OUTSIDE every captured
    graph, one fused ``apply_token_bitmask_inplace`` launch per step over
    the constrained rows of the flat ``(K*B, V)`` logits view.

    The compiled kernel is keyed on the LOGITS DTYPE (which also picks
    ``num_warps``, so each dtype is its own compile) and on the
    integer-scalar class of ``num_rows`` — the count of CONSTRAINED rows,
    which is 1 for a lone constrained request and up to the flat slate
    width when several are. ``vocab_size`` and both row strides are
    ``B``-invariant, so the warm set is ``dtypes x class(num_rows)``:
    at most twelve launches, independent of ``max_batch``. Native function
    sampling omits row indices; that None argument is a separate Triton
    specialization from the indexed structured-output path, so both are warmed.

    Returns the number of warm launches (0 when CUDA or xgrammar is
    unavailable).
    """
    if not torch.cuda.is_available():
        return 0
    try:
        import xgrammar as xg
    except ImportError:
        logger.info(
            "serve-kernel warmup: xgrammar not installed — structured-output "
            "mask kernel not warmed (structured requests are refused anyway)"
        )
        return 0

    v = int(vocab_size)
    rows = _row_classes(max_rows)
    n_max = max(rows)
    # The processor slices its persistent ``(rows, ceil(V/32))`` int32
    # bitmask and passes the logits as a contiguous ``(rows, V)`` view, so
    # both row strides here match the serving launch.
    bitmask = torch.full((n_max, (v + 31) // 32), -1, dtype=torch.int32, device=device)
    n = 0
    for logits_dtype in (torch.bfloat16, torch.float32):
        logits = torch.zeros(n_max, v, dtype=logits_dtype, device=device)
        for r in rows:
            idx = torch.arange(r, dtype=torch.int32, device=device)
            xg.apply_token_bitmask_inplace(logits, bitmask, indices=idx)
            # The native function channel masks every row without an index
            # tensor. Warm that actual launch signature, including explicit
            # vocab_size, rather than charging its first compile to speech.
            xg.apply_token_bitmask_inplace(logits[:r], bitmask[:r], vocab_size=v)
            n += 2
            del idx
        del logits
    del bitmask
    return n


def warm_stochastic_drafter_kernels(
    device: torch.device,
    vocab_size: int,
    max_batch: int,
    *,
    max_k: int,
    keyed_watermark: bool = False,
) -> int:
    """Pre-compile the SAMPLED-draft tail — the drafter half of a non-greedy step.

    Under ``ARBI_TRUE_STOCHASTIC_DRAFT`` (default ``auto``) a non-greedy
    row does not draft by argmax: the drafter filters its own logits and
    DRAWS from them, then reports the realized ``q``. That tail runs
    outside every captured graph — boot capture records the GREEDY chain,
    because capture has no request in hand and the sampled route is a
    per-row decision — so on a stock boot its kernels compile inside the
    first non-greedy request, next to the verify tail's.

    Driven through :meth:`~arbi_serve.spec_decode.rejection_sampler.
    GraphSafeRejectionSampler.sample_drafter_token`, the entry the drafter
    chain calls, so the mask dispatch (fanned top-C vs pivot), the
    parameter encoding and the draw offsets are the serving code's own.

    Two independent axes, walked separately rather than as a product
    because they key different kernels:

    * the MASK (:func:`~arbi_serve.spec_decode.rejection_sampler_ops.
      mask_spec_logits_`) keys on the ``(top_k, top_p)`` shape — the same
      three served classes :data:`_TOPK_TOPP_AXIS_CLASSES` enumerates, as
      VALUES here (the drafter's encoder never passes ``None``: an
      unasked axis arrives as ``top_k = V`` / ``top_p = 1.0``);
    * the fused filter+draw's ``DRAW_OFFSET`` is a constexpr the chain
      steps through — ``OFFSET_DRAFTER + 17 · step`` for ``step`` in
      ``0..K-1`` — so each drafted depth is its own compiled kernel.

    Both ride the ``B`` ladder of :func:`_representative_rows`: the fused
    draw derives ``split`` / ``BLOCK_SIZE`` from the row count exactly as
    ``gumbel_argmax_from_seeds`` does.

    ``keyed_watermark`` (a watermark key is configured) adds a THIRD axis:
    the coupled draw reads a per-row context seed with zero counter lanes,
    which is a ``PER_ROW_SEED`` constexpr on the same fused tail — a
    different compiled kernel from the step-seeded one, and the only one a
    watermarking boot's sampled drafts ever launch. It needs no draw-offset
    ladder: the keyed mode does not read the offset, and the wrapper pins it
    to 0 so every depth shares the one program.

    ``min_p`` is the THIRD axis, and it multiplies the second rather than
    adding to it: ``MINP_ENABLED`` is a constexpr on the fused filter+draw,
    so a min-p draw re-keys the WHOLE draw-offset ladder — plus the
    ``_minp_partials_kernel`` that only a min-p draw launches at all. It is
    warmed here rather than left lazy because it is a first-class field of
    both completion schemas (:mod:`arbi_serve.schemas.openai`), reachable by
    any client, so no model card mentioning it is not a bound on traffic.
    The plain (non-draft) sampler needs no such arm: it routes a min-p row
    through the torch ``_vectorized_min_p_mask`` and switches its fused
    mask+sample path OFF (``arbi_serve.sampler.sampler``), so min-p reaches
    no Triton constexpr there. Counted by ``jit_compile_serving``.

    Allocations are transients — one ``(B, V)`` fp32 logits block per row
    class, plus whatever the drafter tail itself builds — released when
    this returns. Returns the number of warm draws (0 without CUDA).

    Driving the real entry also fires its flag-truth counters
    (``drafter_fused_draw``, ``topc_mask`` / ``topc_mask_pivot_fallback``)
    at BOOT, so a pre-traffic scrape of them is no longer zero. Both are
    declared ``Inapplicable`` — nothing asserts a count — and a bench that
    brackets its window diffs the scrape rather than reading it absolute."""
    if not torch.cuda.is_available() or max_k <= 0:
        return 0
    from arbi_serve.engine.request import SamplingParams
    from arbi_serve.spec_decode.mtp_row_keys import MtpDraftKeys
    from arbi_serve.spec_decode.rejection_sampler import (
        DrafterSamplingTensors,
        GraphSafeRejectionSampler,
    )

    v = int(vocab_size)
    rows = _representative_rows(device, v, max_batch)
    sampler = GraphSafeRejectionSampler()
    seed_buf = torch.ones(1, dtype=torch.int64, device=device)
    wide_k = _over_capacity_top_k(device, v)
    n = 0
    for b in rows:
        logits = torch.randn(b, v, dtype=torch.float32, device=device)
        draft_keys = MtpDraftKeys(torch.ones(1, b, dtype=torch.int64, device=device))
        if wide_k is not None:  # the pivot fallback; the drafter always passes k and p
            params = [SamplingParams(temperature=1.0, top_k=wide_k, top_p=_WARM_TOP_P)] * b
            logits.normal_()
            sampler.sample_drafter_token(
                logits=logits, sampling_params=params, seed_buf=seed_buf, slot_offset=0
            )
            n += 1
        for top_k, top_p in _DRAFTER_AXIS_PRESETS:
            params = [SamplingParams(temperature=1.0, top_k=top_k, top_p=top_p)] * b
            logits.normal_()
            sampler.sample_drafter_token(
                logits=logits, sampling_params=params, seed_buf=seed_buf, slot_offset=0
            )
            n += 1
            # Per-request MTP draft keys: the same PER_ROW_SEED tail as the
            # keyed watermark, driven through the live keyed entry.
            logits.normal_()
            sampler.sample_drafter_token(
                logits=logits, sampling_params=params, seed_buf=draft_keys, slot_offset=0
            )
            n += 1
            if keyed_watermark:
                # The keyed tail rides the SAME mask, so it walks the same
                # mask axis; only the draw differs. Driven through the
                # tensor entry because that is the one the keyed walk calls.
                logits.normal_()
                sampler.sample_drafter_token_tensors(
                    logits=logits,
                    tensors=DrafterSamplingTensors.from_params(
                        params, vocab_size=v, device=device, seed_dev=seed_buf
                    ),
                    slot_offset=0,
                    wm_row_seeds=torch.ones(b, dtype=torch.int64, device=device),
                )
                n += 1
        # Draw-offset ladder: orthogonal to the mask, so one preset covers it.
        params = [SamplingParams(temperature=1.0, top_k=_WARM_TOP_K, top_p=_WARM_TOP_P)] * b
        for step in range(1, int(max_k)):
            logits.normal_()
            sampler.sample_drafter_token(
                logits=logits, sampling_params=params, seed_buf=seed_buf, slot_offset=step
            )
            n += 1
        # min-p arm: a different compiled program at EVERY offset, so this
        # walks the ladder from 0 rather than sharing the mask loop's step 0.
        mp_params = [
            SamplingParams(temperature=1.0, top_k=_WARM_TOP_K, top_p=_WARM_TOP_P, min_p=_WARM_MIN_P)
        ] * b
        for step in range(int(max_k)):
            logits.normal_()
            sampler.sample_drafter_token(
                logits=logits, sampling_params=mp_params, seed_buf=seed_buf, slot_offset=step
            )
            n += 1
        logits.normal_()  # the keyed min-p draw (no offset ladder: lanes are zero)
        sampler.sample_drafter_token(
            logits=logits, sampling_params=mp_params, seed_buf=draft_keys, slot_offset=0
        )
        n += 1
        del logits
    return n


def _check_verify_buffer(buf: torch.Tensor | None, name: str, need: tuple[int, ...]) -> None:
    """Refuse a verify buffer too small for the served slate.

    A buffer the served ``(K+1, max_batch, V)`` / ``(K, max_batch)`` slate
    does not fit inside means the warm and the serving path disagree on
    the slate bound; slicing it anyway would warm a SHORTER slate — a
    different specialization from the one traffic launches, i.e. exactly
    the silent miscoverage the warm exists to prevent.
    """
    if buf is None:
        return
    if len(buf.shape) != len(need) or any(
        int(a) < int(b) for a, b in zip(buf.shape, need, strict=True)
    ):
        raise RuntimeError(
            f"warm_mtp_verify_sampler_kernels: verify buffer {name} "
            f"{tuple(buf.shape)} cannot hold the served slate {need}."
        )


def warm_mtp_verify_sampler_kernels(
    device: torch.device,
    vocab_size: int,
    max_batch: int,
    *,
    k_plus_1: int,
    n_cand: int,
    tp_size: int,
    draw_offset: int,
    verify_p_target: torch.Tensor | None,
    verify_draft_tokens: torch.Tensor | None,
    verify_draft_probs: torch.Tensor | None,
    keyed_watermark: bool,
    verify_logits_dtype: torch.dtype = torch.bfloat16,
) -> int:
    """Pre-compile the MTP verify tail's sampler kernels.

    The verify rejection path runs OUTSIDE the captured graphs and
    dispatches Triton entries the plain-decode warm never reaches:

    * the slate mask, over ``(K+1)·B`` full-vocab rows and across the same
      :data:`_TOPK_TOPP_AXIS_CLASSES` the plain-decode warm walks (the
      verify path builds its ``(k, p)`` tensors from the SAME per-request
      metadata, so a ``top_p >= 1.0`` preset serves the ``p=None`` kernel
      here too), with and without the LSE epilogue (``lse_out`` — the
      Philox verify epilogue on the GATHERED path; ``WRITE_LSE`` is a
      constexpr, so the two are different kernels). Driven through
      :func:`~arbi_serve.spec_decode.rejection_sampler_ops.
      mask_spec_logits_`, the serving DISPATCH, not through one of the two
      kernels beneath it: that dispatch chooses the fanned top-C mask or
      the vendored pivot kernel from the HOST ``(top_k, top_p)`` values and
      the logits dtype, so a warm that calls either kernel directly leaves
      whichever the served values actually select cold;
    * the SHARDED path's candidate-width mask: ``compacted_p_target``
      masks ``(rows, C)`` logits where ``C = tp_size · n_cand`` (the
      all-gathered per-shard top-``n_cand`` candidates) — a row width
      three orders of magnitude below ``V``, i.e. a DISTINCT kernel
      specialization from any full-vocab warm;
    * :func:`~arbi_serve.sampler.gumbel_argmax_triton.
      gumbel_noise_at_indices` at the merged candidate shape
      ``(K+1, B, C)`` with the recovery draw-offset class;
    * ``mtp_sample_residual_philox`` — the DEFAULT (non-fused) Philox
      verify tail, whose single-pass counter-based recovery+bonus draw
      is :func:`~arbi_serve.sampler.gumbel_argmax_triton.
      residual_bonus_gumbel_from_seed`. Warmed through the OP, the entry
      ``GraphSafeRejectionSampler.sample_batched`` dispatches, so the
      wrapper arguments the specialization is keyed on are built by the
      serving code rather than restated here. The kernel compiles per
      ``(Q_IS_ONEHOT, IN_LOG_SPACE, DRAW_OFFSET, VOCAB_SIZE, BLOCK_SIZE)``
      constexpr class plus the integer-scalar specialization of its
      ``(K+1)·B`` rows, ``K·B``, ``B`` and ``split``, so the warm walks
      BOTH slate dims (:func:`_verify_slates`) and BOTH proposal
      encodings:

      - ``draft_probs=None`` — the point-mass proposal a greedy-argmax
        drafter reports (``POINT_MASS_Q``);
      - ``draft_probs=verify_draft_probs[:K, :B]`` — the dense ``q`` a
        boot that can realize a SAMPLED draft hands the sampler.
        ``ARBI_TRUE_STOCHASTIC_DRAFT`` defaults to ``auto``, so on the
        served config this is the encoding the FIRST non-greedy request
        reaches; ``Q_IS_ONEHOT`` being a constexpr makes it a different
        compiled kernel from the point-mass one.

      The ``in_log_space=True`` fused variant (``mtp_fused_rejection``,
      default off) stays lazy — the "only warm what this boot can reach"
      rule the top-k/top-p / min-p warm follows; the detector names it if
      a request ever gets there.

    ``keyed_watermark`` (a watermark key is configured) adds the
    EXACT-MATCH verify draw ``_sample_batched_keyed_exact`` dispatches:
    the same residual/bonus kernel under ``PER_ROW_SEED=True`` (a
    ``(K+1)·B`` seed grid instead of the scalar step seed) over a
    freshly-built all-``-1`` draft tensor — a distinct compiled kernel
    from the scalar-seed one, and the ONLY verify draw a watermarked
    slate reaches. Warmed off the key a boot RESOLVES, so the draw is
    covered before the first request reaches it.

    ``verify_p_target`` / ``verify_draft_tokens`` / ``verify_draft_probs``
    are the ENGINE's persistent verify buffers —
    ``VerifyBuffers.sc_p_target`` ``(max_k+1, max_batch, V)``,
    ``VerifyBuffers.draft_tensor`` ``(max_k, max_batch)`` and
    ``VerifyBuffers.sc_draft_probs`` ``(max_k, max_batch, V)``. The
    residual warm slices them exactly as the serving path does
    (``[:K+1, :B]`` / ``[:K, :B]``) instead of allocating fresh
    contiguous tensors, because Triton keys the compiled kernel on every
    integer argument's specialization class and the slate's LEADING
    STRIDES are arguments: a ``[:, :B]`` slice of a ``max_batch``-wide
    slab carries row stride ``max_batch`` (``max_batch · V`` for the
    vocab-scale ones), which a fresh ``(K, B)`` / ``(K+1, B, V)``
    allocation does not reproduce for ``B < max_batch``. Warming on the
    serving buffers makes every stride, dtype and alignment match by
    construction, and costs no memory — the buffers already exist and the
    KV budget already books them, so this warm adds nothing to the
    forecast the pool was sized from. All three are read-only here.

    ``verify_draft_probs`` doubles as the dense-``q`` REACHABILITY answer:
    ``VerifyBuffers`` allocates ``sc_draft_probs`` on exactly
    :func:`~arbi_serve.spec_decode._mtp_driver_ops.dense_draft_q_possible`,
    the predicate that decides whether a slate can carry a dense
    proposal, so ``None`` means the dense kernel is unreachable and
    warming it would be a boot tax for a kernel nothing launches.

    ``None`` for any of them (no verify buffers — a vocab-less pool, CPU
    tests) falls back to fresh contiguous tensors, except
    ``verify_draft_probs`` whose absence skips the dense class.

    Parameters are the RESOLVED served values (drafter ``K+1``, the
    per-shard candidate budget, the TP world size,
    ``OFFSET_RECOVERY``, the verify buffers) — passed in by the boot
    phase so this module reads no engine state. Returns the number of
    warm launches (0 without CUDA).
    """
    if not torch.cuda.is_available() or k_plus_1 <= 0:
        return 0
    from arbi_serve.sampler.gumbel_argmax_triton import (
        gumbel_noise_at_indices,
        residual_bonus_gumbel_from_seed,
    )
    from arbi_serve.sampler.spec_verify_triton import warm_fused_verify
    from arbi_serve.spec_decode.mtp_row_keys import warm_mtp_row_keys
    from arbi_serve.spec_decode.rejection_sampler_ops import mask_spec_logits_

    v = int(vocab_size)
    c_merged = int(n_cand) * max(1, int(tp_size))
    big_k = int(k_plus_1) - 1  # K = drafter block width
    n = 0
    seed_dev = torch.ones(1, dtype=torch.int64, device=device)
    _check_verify_buffer(verify_p_target, "sc_p_target", (k_plus_1, max_batch, vocab_size))
    _check_verify_buffer(verify_draft_tokens, "draft_tensor", (big_k, max_batch))
    _check_verify_buffer(verify_draft_probs, "sc_draft_probs", (big_k, max_batch, vocab_size))
    wide_k = _over_capacity_top_k(device, v)
    wide_c = _over_capacity_top_k(device, c_merged) if c_merged > 0 else None
    for b in sorted({min(x, max(1, int(max_batch))) for x in (1, 2, 16)}):
        rows = k_plus_1 * b
        p = torch.full((rows,), _WARM_TOP_P, dtype=torch.float32, device=device)
        lse = torch.empty(rows, dtype=torch.float32, device=device)
        for logits_dtype in (torch.bfloat16, torch.float32):
            flat = torch.randn(rows, v, dtype=logits_dtype, device=device)
            for k_arg, hk, p_arg, hp in _mask_slates(p, v, wide_k):
                flat.normal_()
                mask_spec_logits_(
                    flat, k_arg, p_arg, lse_out=lse, top_ks=hk, top_ps=hp, vocab_size=v
                )
                # Same full-vocab slate WITHOUT the LSE epilogue — the
                # ``_topk_topp_probs`` mask on the verify p_target chain.
                # ``WRITE_LSE`` is a constexpr, so it is a DISTINCT compiled
                # kernel, and the plain-decode warm cannot stand in for it:
                # that one only reaches ``B <= max_batch`` rows, never the
                # ``(K+1)*B`` slate widths whose divisibility-by-16 class the
                # verify path launches at.
                flat.normal_()
                mask_spec_logits_(flat, k_arg, p_arg, top_ks=hk, top_ps=hp, vocab_size=v)
                n += 2
            del flat
        if c_merged > 0:
            # Candidate-width mask (no LSE — mirrors _topk_topp_probs on
            # the sharded p_target chain), fp32 like cand_vals.
            cand_vals = torch.randn(rows, c_merged, dtype=torch.float32, device=device)
            for k_arg, hk, p_arg, hp in _mask_slates(p, c_merged, wide_c):
                cand_vals.normal_()
                mask_spec_logits_(
                    cand_vals, k_arg, p_arg, top_ks=hk, top_ps=hp, vocab_size=c_merged
                )
                n += 1
            del cand_vals
            cand = torch.randint(0, v, (k_plus_1, b, c_merged), dtype=torch.int64, device=device)
            gumbel_noise_at_indices(cand, seed_dev, draw_offset=int(draw_offset))
            grid = torch.ones(k_plus_1 * b, dtype=torch.int64, device=device)  # row keys
            gumbel_noise_at_indices(cand, grid, draw_offset=int(draw_offset))
            n += 2
            del cand, grid

    # Recovery+bonus counter-Gumbel draw — the single-pass kernel the
    # DEFAULT Philox verify tail dispatches. Driven through the SERVING
    # ENTRY (``torch.ops.arbi_serve.mtp_sample_residual_philox``, what
    # ``GraphSafeRejectionSampler.sample_batched`` calls) rather than the
    # Triton wrapper beneath it, so the strides, the draw offset and the
    # proposal encoding are the op's own and cannot drift out of step
    # with the served launch.
    #
    # Its ladder is keyed on the FLAT ``(K+1)·B`` row count, so it walks
    # its own representative slates (:func:`_verify_slates`) rather than
    # the mask kernels' rows. ``p_target`` is the fp32 ``(K+1, B, V)``
    # probs the verify chain softmaxes into the engine's persistent slate
    # buffer. Slicing the ENGINE's buffers reproduces the serving leading
    # strides exactly — a stride is a specialized kernel argument, so a
    # fresh contiguous ``(K, B)`` draft tensor compiles a variant no
    # ``B < max_batch`` slate ever launches. Values are irrelevant to the
    # specialization; every buffer is read-only here.
    #
    # BOTH proposal encodings are warmed where both are servable.
    # ``Q_IS_ONEHOT`` is a constexpr, so the point-mass draw and the
    # dense-``q`` draw are different compiled kernels, and which one a
    # slate takes is the DRAFTER's answer, not the request's: a boot that
    # can realize a sampled draft (``ARBI_TRUE_STOCHASTIC_DRAFT`` != 0 —
    # the default — or an external draft model) hands the sampler a dense
    # ``(K, B, V)`` q. ``verify_draft_probs`` is that boot's
    # ``sc_draft_probs`` slab, allocated on exactly the predicate that
    # decides the encoding, so its presence IS the reachability answer
    # and warming off it costs no memory.
    n += warm_mtp_row_keys(device, int(k_plus_1) - 1)  # the per-request key kernel
    mb = max(1, int(max_batch))
    for kp1, b in _verify_slates(device, v, k_plus_1, mb):
        k_step = kp1 - 1
        if verify_p_target is not None:
            p_target = verify_p_target[:kp1, :b]
        else:
            p_target = torch.rand(kp1, b, v, dtype=torch.float32, device=device)
        if verify_draft_tokens is not None:
            draft_tokens = verify_draft_tokens[:k_step, :b]
        else:
            draft_tokens = torch.zeros(k_step, b, dtype=torch.int64, device=device)
        u_accept = torch.full((k_step, b), 0.5, dtype=torch.float32, device=device)
        proposals: list[torch.Tensor | None] = [None]
        if verify_draft_probs is not None:
            proposals.append(verify_draft_probs[:k_step, :b])
        # Per-request row keys (``mtp_row_keys``): the MTP verify's served
        # seed is a ``(K+1)·B`` grid, a PER_ROW_SEED kernel of its own.
        row_grid = torch.ones(kp1 * b, dtype=torch.int64, device=device)
        for q in proposals:
            for seed in (seed_dev, row_grid):
                torch.ops.arbi_serve.mtp_sample_residual_philox(
                    p_target, q, draft_tokens, u_accept, seed
                )
                n += 1
        if keyed_watermark:
            # Keyed exact-match draw: a per-(depth, row) seed grid selects
            # PER_ROW_SEED, and the all-``-1`` draft tensor synthesizes the
            # zero one-hot that makes every row draw from the pure filtered
            # target. Reached BELOW the op boundary on the serving path too
            # (``_sample_batched_keyed_exact`` calls the wrapper directly),
            # and built fresh here because the serving path builds it fresh
            # — a contiguous ``(K, B)`` tensor, not a slab slice.
            neg = torch.full((k_step, b), -1, dtype=torch.int64, device=device)
            grid = torch.ones(kp1 * b, dtype=torch.int64, device=device)
            residual_bonus_gumbel_from_seed(p_target, None, grid, draft_tokens=neg)
            n += 1
            del neg, grid
        del p_target, draft_tokens, u_accept, proposals
    n += warm_fused_verify(
        device,
        k_plus_1,
        mb,
        v,
        logits_dtype=verify_logits_dtype,
        verify_draft_probs=verify_draft_probs,
        chunked=verify_p_target is not None,
        draw_offset=int(draw_offset),
    )
    return n
# ---- ngram_blocker.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Sliding-window no-repeat-n-gram logits processor.

Blocks the token that would complete an n-gram whose first ``n−1``
tokens match the sequence's current ``n−1``-token suffix, when that
n-gram already occurred inside the lookback window. OCR models
(Unlimited-OCR) rely on this to stop coordinate-token loops — greedy
decoding over dense layout/coordinate vocabularies otherwise repeats a
long span verbatim. ``window == 0`` degenerates to the
unbounded-lookback ``no_repeat_ngram_size`` behaviour.

Per-request opt-in via ``SamplingParams.no_repeat_ngram_size`` /
``no_repeat_ngram_window`` (both surfaced on the OpenAI request
bodies). Stateless — history is re-read from the request each step, so
there is no per-request state to keep in sync.

The history comes from
:func:`~arbi_serve.sampler.penalty_history.sequence_history_parts`, the
same accessor the repetition/frequency/presence penalties use, so
"the tokens this request is scored against for repetition" is ONE
definition rather than two that can drift. For every ordinary request
that is ``prompt_token_ids + output_token_ids``, exactly as before. For
the frame-lockstep duplex text channel it is the connection's real
SPOKEN tokens (design doc §7.53/§7.59) — which is what makes this
processor usable there at all: a duplex row's ``output_token_ids`` is
one entry per 80 ms tick and ~95% PAD, so n-grams over it would be
runs of PAD and the blocker would ban the very token that holds a turn
open. Filtering PAD/BOS/EOS out of the history is the whole carve-out:
every banned id is by construction a member of the history, so a token
absent from it can never be banned.
"""

from __future__ import annotations

from collections.abc import Sequence

import torch

from arbi_serve.engine.request import Request
from arbi_serve.sampler.penalty_history import sequence_history_parts
from arbi_serve.sampler.vocab_window import VocabWindow


def _refuse_speculative(row: int) -> None:
    """Refuse an n-gram-blocked row on a speculative draw.

    The blocker bans the tokens that would complete an n-gram already seen
    in the row's history, so its ban list is keyed on the row's current
    ``n-1``-token suffix. Every position of a speculative slate has a
    DIFFERENT suffix, and the drafts that produce those suffixes are exactly
    what the draw is deciding whether to keep. Masking all positions against
    the committed suffix bans tokens that are legal there and misses the
    ones that are not.

    A request that set ``no_repeat_ngram_size`` therefore takes the ``K=1``
    decode path (``mtp_k=0``, resolved at admission): the block it asked for,
    without the speculation speedup.
    """
    raise NotImplementedError(
        f"NoRepeatNgramProcessor: row {row} sets no_repeat_ngram_size under "
        "speculative decoding (K > 1), which has no per-position form — send "
        "the request with mtp_k=0."
    )


class NoRepeatNgramProcessor:
    """Mask tokens that would repeat an n-gram within the lookback window.

    Implements the :class:`arbi_serve.sampler.processors.LogitsProcessor`
    protocol. Rows whose request has ``no_repeat_ngram_size == 0`` pass
    through untouched; a step with no opted-in request returns the
    input tensor unchanged (zero-copy).
    """

    def __call__(
        self,
        logits: torch.Tensor,  # (K, num_seqs, V)
        requests: Sequence[Request],
    ) -> torch.Tensor:
        K, B, _v = logits.shape
        if len(requests) != B:
            raise RuntimeError(
                f"NoRepeatNgramProcessor: logits has B={B} but {len(requests)} requests."
            )
        banned_rows: list[tuple[int, list[int]]] = []
        for i, req in enumerate(requests):
            n = req.sampling.no_repeat_ngram_size
            if n <= 0:
                continue
            if K != 1:
                _refuse_speculative(i)
            prompt, output = sequence_history_parts(req)
            banned = self._banned_tokens(
                [*prompt, *output],
                n,
                req.sampling.no_repeat_ngram_window,
            )
            if banned:
                banned_rows.append((i, banned))
        if not banned_rows:
            return logits
        # Out-of-place: upstream logits may back a captured-graph output
        # buffer (same rationale as apply_penalties).
        out = logits.clone()
        for i, banned in banned_rows:
            ids = torch.tensor(banned, device=logits.device, dtype=torch.long)
            out[0, i, ids] = float("-inf")
        return out

    def constrains_verify_slate(self, requests: Sequence[Request]) -> bool:
        """True for a row that opted in — and this processor REFUSES those,
        so the honest answer is that it acts on the slate."""
        return any(r is not None and r.sampling.no_repeat_ngram_size > 0 for r in requests)

    def verify_slate_reads_drafts(self, requests: Sequence[Request]) -> bool:
        """The slate form does not read the draft tokens."""
        del requests
        return False

    def apply_to_verify_slate(
        self,
        logits: torch.Tensor,  # (K+1, B, W)
        requests: Sequence[Request],
        drafts_per_row: Sequence[Sequence[int]],
        *,
        window: VocabWindow | None = None,
    ) -> None:
        """Refuse the slate for every row that asked for the n-gram block.

        The ban list is a function of the row's ``n-1``-token suffix, which
        differs at every speculative position, so there is no per-position
        form of this constraint to apply — see :func:`_refuse_speculative`.
        Rows at ``no_repeat_ngram_size == 0`` are untouched, so a slate that
        contains none is a no-op.

        ``mtp_k`` is forced to 0 for an opted-in request at admission, which
        is what keeps this refusal off the served path.
        """
        # ``window`` is irrelevant here: a refusal is a refusal on every
        # rank, and refusing identically is what keeps the ranks paired.
        del logits, drafts_per_row, window  # nothing is masked; the slate is refused
        for i, req in enumerate(requests):
            if req is not None and req.sampling.no_repeat_ngram_size > 0:
                _refuse_speculative(i)

    @staticmethod
    def _banned_tokens(seq: list[int], n: int, window: int) -> list[int]:
        """Tokens that would complete an already-seen n-gram.

        The scan considers n-grams STARTING in
        ``[len(seq) − window, len(seq) − n]`` (whole sequence when
        ``window <= 0``) and bans the final token of every n-gram whose
        first ``n−1`` tokens equal the current suffix.
        """
        if len(seq) < n:
            return []
        search_start = max(0, len(seq) - window) if window > 0 else 0
        search_end = len(seq) - n + 1
        if search_end <= search_start:
            return []
        prefix = tuple(seq[-(n - 1) :]) if n > 1 else ()
        banned: set[int] = set()
        for idx in range(search_start, search_end):
            if n == 1 or tuple(seq[idx : idx + n - 1]) == prefix:
                banned.add(seq[idx + n - 1])
        return sorted(banned)

    async def accept_token(self, request: Request, token: int) -> None:
        """No-op — history is re-read from the request every step."""
# ---- omni_guard.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Omni output guard — mask speech-code logits off speech turns.

On an omni model every token id is reachable, but a request that did
NOT ask for speech output (`modalities` without ``"audio"``) should
never emit speech codes or tts control markers: the demux would swallow
them (no text corruption), but they waste KV pages / token budget and
can derail the turn. This processor applies a precomputed ``-inf`` bias
over the speech-code range and the control-id set to every row whose
request has an :class:`OmniStreamState` with speech DISABLED; rows that
seeded a speech turn are untouched (the model interleaves freely there
— its text tokens ARE the transcript, so no in-segment constraint is
imposed).

Same registration surface as the xgrammar processor
(``Sampler.set_logits_processors``); logits arrive ``(K, num_seqs, V)``
and rows map 1:1 to ``requests``.
"""

from __future__ import annotations

from collections.abc import Sequence
from typing import TYPE_CHECKING

import torch

from arbi_serve.sampler.vocab_window import VocabWindow

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request
    from arbi_serve.multimodal.output import OmniOutputSpec


class OmniOutputGuard:
    """Logits processor masking speech ids for non-speech requests."""

    def __init__(self, spec: OmniOutputSpec, *, vocab_size: int) -> None:
        self.spec = spec
        mask = torch.zeros(vocab_size, dtype=torch.bool)
        lo = spec.audio_code_base
        hi = min(lo + spec.audio_code_count, vocab_size)
        mask[lo:hi] = True
        for cid in spec.control_ids:
            if cid < vocab_size:
                mask[cid] = True
        self._mask_cpu = mask
        self._mask_dev: torch.Tensor | None = None

    def _mask_on(self, device: torch.device) -> torch.Tensor:
        if self._mask_dev is None or self._mask_dev.device != device:
            self._mask_dev = self._mask_cpu.to(device)
        return self._mask_dev

    def _guarded_rows(self, requests: Sequence[Request]) -> list[int]:
        """Columns whose request must not emit speech ids this step."""
        return [
            i
            for i, req in enumerate(requests)
            if req is not None
            and getattr(req, "omni_state", None) is not None
            and not getattr(req.sampling, "speech_output", False)
        ]

    def __call__(self, logits: torch.Tensor, requests: list[Request]) -> torch.Tensor:
        rows = self._guarded_rows(requests)
        if not rows:
            return logits
        mask = self._mask_on(logits.device)
        out = logits.clone()
        idx = torch.tensor(rows, device=logits.device)
        out[:, idx, :] = out[:, idx, :].masked_fill(mask, float("-inf"))
        return out

    def constrains_verify_slate(self, requests: Sequence[Request]) -> bool:
        return bool(self._guarded_rows(requests))

    def verify_slate_reads_drafts(self, requests: Sequence[Request]) -> bool:
        """The slate form does not read the draft tokens."""
        del requests
        return False

    def apply_to_verify_slate(
        self,
        logits: torch.Tensor,  # (K+1, B, W) — masked in place
        requests: Sequence[Request],
        drafts_per_row: Sequence[Sequence[int]],
        *,
        window: VocabWindow | None = None,
    ) -> None:
        """Mask the speech ids across EVERY position of a guarded column.

        The ban is a fixed per-request vocabulary set, not a function of the
        row's history, so the same mask is correct at every speculative
        position and the drafts are irrelevant. A guarded row therefore
        cannot emit a speech code through the verify draw either.

        A vocab-parallel ``window`` restricts the ban to the ids that rank
        holds — a slice of the same boolean mask, since the ban is a set of
        token ids and nothing else.
        """
        del drafts_per_row  # the ban does not depend on the row's history
        rows = self._guarded_rows(requests)
        if not rows:
            return
        mask = self._mask_on(logits.device)
        if window is not None:
            mask = window.slice_rows(mask)
        idx = torch.tensor(rows, device=logits.device)
        logits[:, idx, :] = logits[:, idx, :].masked_fill(mask, float("-inf"))
# ---- penalty_accumulator.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Persistent additive accumulator for the presence / frequency penalties.

Both penalties are ADDITIVE in logit space::

    penalty_add[b, t] = presence[b] * (count[b, t] > 0) + frequency[b] * count[b, t]

so one ``(rows, vocab)`` buffer can carry both, and applying them is a
single coalesced ``logits - penalty_add[:B]``.

Repetition does not share that term — it is multiplicative and
sign-dependent — but it does share the STATE. All three knobs are
functions of the same per-``(row, token)`` occurrence history: repetition
and presence need the SEEN set, frequency needs the counts themselves.
:attr:`PenaltyAccumulator._counts` already holds it, so a caller that
asks for ``need_counts`` gets the seen set out of the same persistent
buffer and applies its own arithmetic on top (see
:func:`~arbi_serve.sampler.processors.apply_penalties`).

Why a persistent buffer
-----------------------
The alternative is a ``(B, vocab+1)`` fp32 occurrence matrix rebuilt EVERY
decode step: allocate it, zero it, ``scatter_add_`` the whole
``B x history`` id matrix into it, then read it back in the penalty
kernel — per-step cost proportional to CONTEXT. The accumulator scatters
only the tokens EMITTED THIS STEP, which is O(B), and the step's device
work is the one subtraction.

Both the fold and the subtract are also free of any host-blocking device
read, which is the property that lets the engine keep running the next
step ahead of the GPU. See :meth:`PenaltyAccumulator.update`.

Bit-identity
------------
The accumulator holds the SAME value the counts chain would subtract, so
the result is bit-identical whenever the chain has exactly one additive
term:

* PRESENCE ONLY (the production knob): ``scatter_`` writes ``pres[b]``,
  an idempotent set, and the chain's ``pres_b * seen.to(dtype)`` is
  ``pres[b]`` exactly. Verified with ``torch.equal``.
* FREQUENCY ONLY: the accumulator entry is RECOMPUTED from the running
  count as ``freq[b] * count.to(dtype)`` — the chain's expression
  verbatim — not incremented by ``freq`` per occurrence. Accumulating
  per occurrence instead would drift (the chain rounds ONCE, an
  incremental sum rounds every step); recomputing costs one extra
  gather over the touched positions only, which is O(B).
* BOTH ACTIVE: the chain subtracts in TWO steps
  (``(logits - freq*counts) - pres*seen``), rounding the intermediate;
  the accumulator subtracts their sum in one, rounding once. This is the
  ONLY combination that is not bit-identical, and it is the only one
  that is not reachable from a single-knob request. The deviation is
  bounded at one ulp of the logits dtype and
  ``tests/test_sampler_penalty_accumulator.py`` asserts that bound.

Row indexing
------------
Row ``i`` holds slate position ``i``, so the apply is a plain slice with
no gather. When the slate reorders (a request finishes and the rest
compact up) the rows are PERMUTED to match, by row-copy through a single
scratch row — at most one ``vocab``-wide copy per moved row, and zero
copies in steady decode where the slate is stable. Rows whose tenant is
new are zeroed and re-seeded from whatever
:func:`~arbi_serve.sampler.penalty_history.penalty_history_parts` says
that row's knobs are scoped to — OUTPUT ONLY for presence / frequency
(the OpenAI contract, and what vLLM and sglang implement), ``prompt +
output`` only when the row asks for a repetition penalty.

This used to seed every row from the full ``prompt + output``, which made
presence and frequency cover the prompt. That is not a harmless superset:
at a 16k prompt with ``presence_penalty=1.5`` every distinct token in the
document is pushed down on every decode step, so the engine penalises the
vocabulary of the very text it was asked to summarise, and the distortion
grows with prompt length.

The seed is O(history) HOST work, ONCE per request, on the step that
admits it — the same work the history cache already does for a fresh row.
Steady decode appends only the tokens emitted since the last step.

FOLLOW-UP (not done): bound the history to a sliding window rather than
the whole output. It is arguably better behaviour — a penalty that never
forgets makes long generations progressively harder to continue — and it
also caps the fold at O(window) instead of O(output), so it saves compute
rather than costing it. Needs a decision on the window and on how it
interacts with the repetition scope before it can ship.
"""

from __future__ import annotations

import logging
from collections.abc import Callable, Sequence

import torch

from arbi_serve.sampler.penalty_history import penalty_history_parts

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

#: Grow the row count in chunks so a batch that ramps 1 -> 64 does not
#: realloc 64 times. Each row is ``vocab`` wide, so the chunk is
#: deliberately small.
_ROW_CHUNK = 8


def _knob_floats(
    requests: Sequence[object],
    pres: torch.Tensor,
    freq: torch.Tensor,
) -> tuple[list[float], list[float]]:
    """Per-row presence / frequency knobs as host floats.

    Read off the requests when they carry sampling params — which every
    engine caller does — so a device-resident knob tensor is never pulled
    back. The tensor fallback is for direct callers that pass knobs
    unattached to requests.
    """
    if requests and getattr(requests[0], "sampling", None) is not None:
        return (
            [float(r.sampling.presence_penalty) for r in requests],  # type: ignore[attr-defined]
            [float(r.sampling.frequency_penalty) for r in requests],  # type: ignore[attr-defined]
        )
    return pres.tolist(), freq.tolist()


def _host_knobs(values: Sequence[float]) -> torch.Tensor:
    """The ``(B,)`` fp32 knob vector, on the HOST.

    The scattered value must be the knob taken ``fp64 -> fp32 -> dtype``,
    which is the hop ``_build_sampling_metadata`` takes when it stores a
    Python float into an fp32 tensor and uploads it. Building the same
    fp32 vector here reproduces that bit pattern without reading the
    device-resident copy back.
    """
    return torch.as_tensor(values, dtype=torch.float32)


def _to_device_async(host: torch.Tensor, device: torch.device) -> torch.Tensor:
    """Host tensor -> device WITHOUT a pageable-H2D host stall.

    ``.to(device, non_blocking=True)`` off a PAGEABLE source is not async at
    all: the CUDA runtime serializes it as ``cudaMemcpyAsync`` +
    ``cudaStreamSynchronize``, so the host blocks until the stream drains.
    The penalty fold runs AFTER the step's forward is enqueued, which makes
    that drain cost a whole forward rather than the copy's own microseconds
    — the same mechanism, and the same fix, as the MTP draft-meta path's
    :func:`~arbi_serve.spec_decode.mtp_draft_meta.h2d_async`.

    Staging through the CUDA caching HOST allocator is safe for a temporary:
    the allocator defers reuse of the pinned block until the recorded copy
    event completes. Non-CUDA devices take the plain copy (``pin_memory``
    requires CUDA) and land identical values.

    Pinning is defined only for dense CPU memory, so a source that is ALREADY
    device-resident takes a D2D copy (a no-op when it is already on ``device``)
    instead. That source is not a production shape — ``_host_knobs`` builds the
    knob vector on the host precisely so it never is — but the repair for one
    is never ``.cpu()``: that is the D2H readback this helper exists to avoid,
    and the one
    ``tests/test_sampler_penalty_no_device_readback_gpu.py`` forbids."""
    if host.device.type != "cpu":
        return host.to(device, non_blocking=True)
    if device.type != "cuda":
        return host.to(device)
    return host.pin_memory().to(device, non_blocking=True)


class PenaltyAccumulator:
    """Slate-aligned ``(rows, vocab)`` additive penalty accumulator.

    One instance per ``(device, vocab_size, dtype)``. Not thread-safe —
    the sampler runs single-threaded inside the engine step.

    ``allocate`` is the hook that puts the buffer in a NAMED cuMem pool
    (``scratch.penalty_accum``); it takes ``(shape, dtype)`` and returns a
    zeroed tensor. The default allocates from whatever pool is current,
    which is what the CPU tests and any non-engine caller want.
    """

    def __init__(
        self,
        device: torch.device,
        vocab_size: int,
        dtype: torch.dtype,
        *,
        max_rows: int,
        allocate: Callable[[tuple[int, ...], torch.dtype], torch.Tensor] | None = None,
    ) -> None:
        self.device = device
        self.vocab_size = int(vocab_size)
        self.dtype = dtype
        self.max_rows = int(max_rows)
        self._allocate = allocate or self._default_allocate
        self._accum: torch.Tensor | None = None
        # Running per-(row, token) occurrence counts. Allocated ONLY when
        # a caller actually needs them: the frequency penalty (which
        # recomputes ``freq * count``) or the repetition penalty (which
        # needs the seen set). Presence alone needs neither.
        self._counts: torch.Tensor | None = None
        # One spare row of each buffer, used to rotate rows when the slate
        # reorders. Preallocated so a reorder never allocates OUTSIDE the
        # named pool on the serving path.
        self._scratch_row: torch.Tensor | None = None
        self._scratch_row_counts: torch.Tensor | None = None
        #: False for exactly one :meth:`update` after ``_counts`` is first
        #: materialized: the new buffer is zero while the rows may already
        #: carry history, so every live row is rebuilt once.
        self._counts_seeded = True
        self._rows = 0
        # Per-row bookkeeping, indexed by row.
        self._rid: list[int] = []  # request_id, or -1 when free
        self._plen: list[int] = []  # prompt length last applied
        self._len: list[int] = []  # total history length applied
        self._pres: list[float] = []
        self._freq: list[float] = []
        # Whether this row's ADDITIVE entry is current. False while a
        # repetition batch is live: the fused kernel derives presence and
        # frequency from the counts directly, so folding the entry as well
        # would be per-step work nothing reads. Repaired from the counts
        # (device-side, O(vocab), no history walk) the step the batch stops
        # asking for repetition.
        self._acc_ok: list[bool] = []

    def _default_allocate(self, shape: tuple[int, ...], dtype: torch.dtype) -> torch.Tensor:
        return torch.zeros(shape, dtype=dtype, device=self.device)

    # -- capacity ---------------------------------------------------------

    def _ensure_rows(self, rows: int) -> None:
        """Grow to at least ``rows``, preserving content."""
        if rows <= self._rows:
            return
        if rows > self.max_rows:
            raise RuntimeError(
                f"PenaltyAccumulator: {rows} rows requested but max_rows={self.max_rows}. "
                "The accumulator is budgeted at boot; a batch wider than the budget "
                "would allocate unbudgeted VRAM out from under the KV pool."
            )
        new_rows = min(self.max_rows, ((rows + _ROW_CHUNK - 1) // _ROW_CHUNK) * _ROW_CHUNK)
        new_accum = self._allocate((new_rows, self.vocab_size), self.dtype)
        if self._accum is not None and self._rows:
            new_accum[: self._rows].copy_(self._accum)
        self._accum = new_accum
        if self._counts is not None:
            new_counts = self._allocate((new_rows, self.vocab_size), torch.int32)
            new_counts[: self._rows].copy_(self._counts)
            self._counts = new_counts
        if self._scratch_row is None:
            self._scratch_row = self._allocate((self.vocab_size,), self.dtype)
        for _ in range(new_rows - self._rows):
            self._rid.append(-1)
            self._plen.append(0)
            self._len.append(0)
            self._pres.append(0.0)
            self._freq.append(0.0)
            self._acc_ok.append(True)
        self._rows = new_rows

    def prime(self) -> int:
        """Allocate the FULL buffer set now; return the bytes taken.

        Called once at engine boot. The bytes were already subtracted from
        the KV budget (``predict_penalty_accum_pool_bytes``), so taking
        them eagerly is what makes the reserve and the residency agree —
        growing later would spend VRAM the KV pool was handed.
        """
        self._ensure_rows(self.max_rows)
        self._ensure_counts()
        # Nothing has been folded yet, so the fresh buffer is already
        # consistent with the (empty) rows.
        self._counts_seeded = True
        return self.resident_bytes

    def _ensure_counts(self) -> torch.Tensor:
        """Materialize the occurrence-count buffer.

        Returns the buffer; :attr:`_counts_seeded` records whether it was
        already live, because a buffer created AFTER rows have folded
        history in starts empty and every live row has to be reseeded.
        """
        if self._counts is None:
            self._counts = self._allocate((self._rows, self.vocab_size), torch.int32)
            self._scratch_row_counts = self._allocate((self.vocab_size,), torch.int32)
            self._counts_seeded = False
        return self._counts

    def accum_view(self, rows: int) -> torch.Tensor | None:
        """The persistent ``(rows, vocab)`` additive penalty entry, or ``None``.

        ``None`` before :meth:`prime` (or any :meth:`update`) has
        materialized the buffer. Row ``i`` is slate position ``i``, same as
        :meth:`update`'s return value -- this IS that tensor, exposed for a
        reader that wants the entry without driving a fold.

        The drafter's penalty alignment
        (:mod:`arbi_serve.spec_decode.draft_penalties`) holds this view
        across a CUDA-graph capture, so the buffer's ADDRESS must outlive
        every replay. It does exactly as long as :meth:`prime` ran first:
        the boot reserve allocates ``max_rows`` up front and
        :meth:`_ensure_rows` is then a no-op forever after.
        """
        if self._accum is None or rows > self._rows:
            return None
        return self._accum[:rows]

    def counts_view(self, rows: int) -> torch.Tensor | None:
        """The persistent ``(rows, vocab)`` int32 occurrence counts, or ``None``.

        ``None`` until some call has asked for them (``need_counts`` or a
        frequency penalty). Row ``i`` is slate position ``i``, same as
        :meth:`update`'s return, so the view needs no gather.
        """
        if self._counts is None:
            return None
        return self._counts[:rows]

    # -- row permutation --------------------------------------------------

    def _swap_rows(self, i: int, j: int) -> None:
        """Exchange rows ``i`` and ``j`` (device rows + host bookkeeping)."""
        assert self._accum is not None and self._scratch_row is not None
        tmp = self._scratch_row
        tmp.copy_(self._accum[i])
        self._accum[i].copy_(self._accum[j])
        self._accum[j].copy_(tmp)
        if self._counts is not None:
            assert self._scratch_row_counts is not None
            ctmp = self._scratch_row_counts
            ctmp.copy_(self._counts[i])
            self._counts[i].copy_(self._counts[j])
            self._counts[j].copy_(ctmp)
        for lst in (self._rid, self._plen, self._len, self._pres, self._freq, self._acc_ok):
            lst[i], lst[j] = lst[j], lst[i]

    def _move_row(self, dst: int, src: int) -> None:
        """One-way copy ``src`` -> ``dst``; ``src``'s tenant is not preserved.

        Used when the row being overwritten holds a request that has LEFT
        the slate — there is nothing to save, so the move is one copy
        instead of a swap's three.
        """
        assert self._accum is not None
        self._accum[dst].copy_(self._accum[src])
        if self._counts is not None:
            self._counts[dst].copy_(self._counts[src])
        self._rid[dst] = self._rid[src]
        self._plen[dst] = self._plen[src]
        self._len[dst] = self._len[src]
        self._pres[dst] = self._pres[src]
        self._freq[dst] = self._freq[src]
        self._acc_ok[dst] = self._acc_ok[src]
        # The source row now holds a DUPLICATE. Free it, or the next step's
        # rid -> row map would carry two entries for one request and resolve
        # to the stale one.
        self._rid[src] = -1
        self._plen[src] = 0
        self._len[src] = 0
        self._pres[src] = 0.0
        self._freq[src] = 0.0
        self._acc_ok[src] = True

    def _align(self, desired: Sequence[int]) -> None:
        """Permute rows so row ``i`` holds ``desired[i]``.

        Selection sort over at most ``B`` positions. A stable slate does
        ZERO device work — the common case, and the whole reason rows are
        slate-aligned rather than gathered at apply time.

        The bound on the rare case is worth stating. A row whose current
        occupant has left the slate is overwritten one-way (ONE row copy);
        only a genuine reorder, where both rows' tenants are still live,
        needs a three-copy swap. The dominant churn shape — one request
        finishes and the rest compact up — is entirely one-way, so it
        costs ``B - 1`` row copies, not ``3(B - 1)``. A pathological full
        reorder is still bounded at ``3(B - 1)`` copies on the ONE step it
        happens; a per-step counts matrix pays its full cost on EVERY step.
        """
        needed = set(desired)
        where = {rid: i for i, rid in enumerate(self._rid) if rid >= 0}
        for i, rid in enumerate(desired):
            j = where.get(rid, -1)
            if j < 0 or j == i:
                continue
            other = self._rid[i]
            if other < 0 or other not in needed:
                self._move_row(i, j)
            else:
                self._swap_rows(i, j)
                where[other] = j
            where[rid] = i

    # -- public API -------------------------------------------------------

    def update(
        self,
        requests: Sequence[object],
        pres: torch.Tensor,
        freq: torch.Tensor,
        *,
        need_counts: bool = False,
        want_accum: bool = True,
    ) -> torch.Tensor | None:
        """Fold this step's new tokens in; return the ``(B, vocab)`` delta.

        ``None`` when every row's history is empty — there is nothing to
        subtract, and the caller returns its input untouched rather than
        materialise a zero delta over the whole vocab.

        ``need_counts`` keeps the occurrence buffer live even when no row
        asks for a frequency penalty, so a caller reading the seen set
        (repetition) gets it from :meth:`counts_view` instead of
        rebuilding one.

        ``want_accum=False`` says the caller will NOT read the returned
        delta — the fused kernel derives presence and frequency from the
        counts directly on a repetition batch — so the additive entry is
        left unfolded and the rows are flagged for repair. The return value
        is then only meaningful as ``None`` / not-``None``.

        ``pres`` / ``freq`` are the ``(B,)`` fp32 knob tensors. They are a
        FALLBACK source of the per-row knob floats, for direct callers
        whose requests carry no sampling params; every engine caller's
        knobs are read off the requests instead. Nothing on this path
        touches the tensors' storage, because ``_build_sampling_metadata``
        builds them on the LOGITS device and any read of a device tensor —
        ``.tolist()``, or indexing it with a host index vector — is a D2H
        copy that BLOCKS the host until the stream drains. Once per decode
        step that costs the whole pipelining win, not the copy.

        The value actually scattered is taken ``fp64 -> fp32 -> dtype``,
        the same hop the counts chain's ``pres.to(device, dtype)`` takes,
        so its bit pattern is unchanged; ``_host_knobs`` does the fp32 leg
        on the host, and fp32 -> bf16/fp16 is round-to-nearest-even on
        host and device alike. Casting from the raw Python float instead
        would be a DIFFERENT rounding (fp64 -> dtype) and could differ in
        the last bit.
        """
        pres_l, freq_l = _knob_floats(requests, pres, freq)
        B = len(requests)
        self._ensure_rows(B)
        assert self._accum is not None

        desired = [int(r.request_id) for r in requests]  # type: ignore[attr-defined]
        if self._rid[:B] != desired:
            self._align(desired)

        any_freq = any(f != 0.0 for f in freq_l)
        counts = self._ensure_counts() if (any_freq or need_counts) else self._counts
        # A counts buffer materialized under live rows is zero while their
        # accumulator entries are not: rebuild every row once, or the seen
        # set would miss all history folded before this call.
        counts_cold = counts is not None and not self._counts_seeded
        self._counts_seeded = True

        # The additive entry is folded only when some row asks for it AND
        # the caller will read it.
        additive = want_accum and (any_freq or any(p != 0.0 for p in pres_l))

        resets: list[int] = []
        # Rows whose additive entry was skipped by an earlier repetition
        # batch and is needed again now.
        repairs: list[int] = []
        # (row, ids) appends to fold in this step.
        appends: list[tuple[int, list[int]]] = []
        max_total = 0
        for i, req in enumerate(requests):
            rid = desired[i]
            prompt, output = penalty_history_parts(req)
            plen = len(prompt)
            total = plen + len(output)
            if total > max_total:
                max_total = total
            stale_entry = additive and not self._acc_ok[i]
            fresh = (
                counts_cold
                or self._rid[i] != rid
                or self._plen[i] != plen
                or self._len[i] > total
                or self._pres[i] != pres_l[i]
                or self._freq[i] != freq_l[i]
            )
            if fresh:
                # New tenant, prompt rewritten by recompute, history reset
                # by preemption, or the knobs changed under a live request:
                # the append-only assumption is broken, so the row is
                # rebuilt from the full history. Same trigger set as
                # PenaltyHistoryCache, for the same reasons.
                resets.append(i)
                if total:
                    appends.append((i, list(prompt) + list(output)))
            else:
                have = self._len[i]
                if total > have:
                    if have >= plen:
                        tail = list(output[have - plen : total - plen])
                    else:
                        tail = list(prompt[have:]) + list(output)
                    appends.append((i, tail))
            if stale_entry and not fresh:
                repairs.append(i)
            self._rid[i] = rid
            self._plen[i] = plen
            self._len[i] = total
            self._pres[i] = pres_l[i]
            self._freq[i] = freq_l[i]
            # The entry is current when it was folded this step, and also
            # when the row asks for neither additive knob — its entry is
            # zero either way.
            self._acc_ok[i] = additive or (pres_l[i] == 0.0 and freq_l[i] == 0.0)

        if resets:
            idx = _to_device_async(torch.as_tensor(resets, dtype=torch.int64), self.device)
            self._accum.index_fill_(0, idx, 0)
            if counts is not None:
                counts.index_fill_(0, idx, 0)

        if appends:
            self._fold(appends, pres_l, freq_l, counts, additive=additive)
        if repairs:
            self._repair(repairs, pres_l, freq_l, counts)

        if max_total == 0:
            return None
        return self._accum[:B]

    def _fold(
        self,
        appends: list[tuple[int, list[int]]],
        pres: Sequence[float],
        freq: Sequence[float],
        counts: torch.Tensor | None,
        *,
        additive: bool,
    ) -> None:
        """Scatter this step's new tokens into the accumulator.

        Indices are FLATTENED to ``row * vocab + token`` so rows with
        different tail lengths need no padding column — the steady-state
        tail is one token per row, so this is a ``B``-element H2D copy.

        The knobs arrive as HOST floats and the per-element value vector is
        built host-side, so the whole fold is host reads plus one H2D. The
        obvious alternative — indexing the sampler's device-resident knob
        tensor with the host row vector — is a CUDA gather with a CPU
        index, which pulls the index across and BLOCKS the host until the
        stream drains. See :meth:`update` for why that matters.

        ``additive`` is False when no row asks for presence or frequency —
        a repetition-only batch. The accumulator entry is then zero
        everywhere and stays that way, so only the occurrence counts are
        folded and the value chain (gather + the entry scatter) is skipped
        entirely.
        """
        assert self._accum is not None
        V = self.vocab_size
        flat_pos: list[int] = []
        row_of: list[int] = []
        for row, ids in appends:
            base = row * V
            flat_pos.extend(base + t for t in ids)
            row_of.extend([row] * len(ids))
        pos = _to_device_async(torch.as_tensor(flat_pos, dtype=torch.int64), self.device)
        rows = torch.as_tensor(row_of, dtype=torch.int64)

        flat_accum = self._accum.view(-1)
        if counts is None:
            if not additive:
                return
            # Presence only: an idempotent SET of the per-row penalty.
            vals = _to_device_async(_host_knobs(pres)[rows].to(self.dtype), self.device)
            flat_accum.scatter_(0, pos, vals)
            return

        # Frequency (with or without presence): bump the running counts,
        # then RECOMPUTE the entry from the new count so the stored value
        # is the chain's ``freq * count.to(dtype)`` exactly rather than a
        # per-occurrence sum. Gathering after the scatter_add_ gives every
        # duplicate in the tail the same FINAL count, so duplicates write
        # the same value and the scatter stays order-independent.
        flat_counts = counts.view(-1)
        ones = torch.ones_like(pos, dtype=torch.int32)
        flat_counts.scatter_add_(0, pos, ones)
        if not additive:
            return
        c = flat_counts.gather(0, pos).to(self.dtype)
        pres_t = _to_device_async(_host_knobs(pres)[rows].to(self.dtype), self.device)
        freq_t = _to_device_async(_host_knobs(freq)[rows].to(self.dtype), self.device)
        flat_accum.scatter_(0, pos, pres_t + freq_t * c)

    def _repair(
        self,
        rows: list[int],
        pres: Sequence[float],
        freq: Sequence[float],
        counts: torch.Tensor | None,
    ) -> None:
        """Rebuild the additive entry of ``rows`` from the occurrence counts.

        The entry is a pure function of the counts
        (``pres * (count > 0) + freq * count``), so a row whose entry was
        skipped while a repetition batch held the slate is recovered with
        one device pass per row — no history walk, no host work
        proportional to context. Bit-identical to what :meth:`_fold` would
        have written: ``pres * 1`` is ``pres`` exactly, and the remaining
        multiply-then-add rounds in the same order.
        """
        assert self._accum is not None and counts is not None
        idx = _to_device_async(torch.as_tensor(rows, dtype=torch.int64), self.device)
        c = counts.index_select(0, idx).to(self.dtype)
        sel = torch.as_tensor(rows, dtype=torch.int64)
        p = _to_device_async(_host_knobs(pres)[sel].to(self.dtype), self.device).view(-1, 1)
        f = _to_device_async(_host_knobs(freq)[sel].to(self.dtype), self.device).view(-1, 1)
        self._accum.index_copy_(0, idx, p * (c > 0).to(self.dtype) + f * c)

    def drop(self, request_id: int) -> None:
        """Release the row held by ``request_id`` (no-op when absent)."""
        rid = int(request_id)
        for i, held in enumerate(self._rid):
            if held == rid:
                self._rid[i] = -1
                self._plen[i] = 0
                self._len[i] = 0
                self._pres[i] = 0.0
                self._freq[i] = 0.0
                self._acc_ok[i] = True
                return

    def reset(self) -> None:
        """Drop every row and free the buffers."""
        self._accum = None
        self._counts = None
        self._scratch_row = None
        self._scratch_row_counts = None
        self._counts_seeded = True
        self._rows = 0
        self._rid.clear()
        self._plen.clear()
        self._len.clear()
        self._pres.clear()
        self._freq.clear()
        self._acc_ok.clear()

    @property
    def resident_bytes(self) -> int:
        """Bytes currently held by this accumulator (for the VRAM ledger)."""
        total = 0
        for t in (
            self._accum,
            self._counts,
            self._scratch_row,
            self._scratch_row_counts,
        ):
            if t is not None:
                total += t.numel() * t.element_size()
        return total


# ---------------------------------------------------------------------------
# Process-wide registry + the engine's pool hook
# ---------------------------------------------------------------------------

#: One accumulator per (device, vocab, dtype). Mirrors the history cache's
#: registry so a model swap that changes vocab or dtype gets a fresh one.
_ACCUMULATORS: dict[tuple[str, int, str], PenaltyAccumulator] = {}

#: Installed by the engine at boot: allocates into the NAMED cuMem pool
#: ``scratch.penalty_accum`` so the bytes are budgeted before KV is sized
#: and show as their own VRAM-ledger row. ``None`` means no engine has
#: installed one.
_POOL_ALLOCATE: Callable[[tuple[int, ...], torch.dtype], torch.Tensor] | None = None
_POOL_MAX_ROWS = 0
#: The ``(vocab, dtype)`` the boot reserve was computed for. A request for
#: any other shape is REFUSED rather than served from a fresh allocation:
#: the reserve is a specific number of bytes, and a different vocab or a
#: different logits dtype is a different number.
_POOL_SHAPE: tuple[int, str] | None = None
#: One WARNING per reserved shape, not one per decode step.
_SHAPE_MISMATCH_LOGGED: dict[tuple[int, str] | None, bool] = {}


def install_penalty_accumulator_pool(
    allocate: Callable[[tuple[int, ...], torch.dtype], torch.Tensor],
    max_rows: int,
    vocab_size: int,
    dtype: torch.dtype,
) -> None:
    """Engine boot hook: route accumulator allocations into a named pool.

    Until this is called the accumulator is DISENGAGED on CUDA (see
    :func:`get_penalty_accumulator`): a multi-tens-of-MB device buffer
    allocated outside every named pool lands in
    ``unpooled.torch_default_pool``, which the VRAM ledger reports as
    unbudgeted and which KV sizing has already spent.
    """
    global _POOL_ALLOCATE, _POOL_MAX_ROWS, _POOL_SHAPE
    reset_penalty_accumulators()
    _POOL_ALLOCATE = allocate
    _POOL_MAX_ROWS = int(max_rows)
    _POOL_SHAPE = (int(vocab_size), str(dtype))


def get_penalty_accumulator(
    device: torch.device,
    vocab_size: int,
    dtype: torch.dtype,
    *,
    max_rows: int,
) -> PenaltyAccumulator | None:
    """Return the accumulator for this ``(device, vocab, dtype)``, or ``None``.

    ``None`` means the caller must take the counts path: on CUDA that is
    the case whenever no engine has installed a pool hook, which keeps the
    buffer from ever being allocated unbudgeted.

    ``device`` IS PART OF THE KEY, BY ITS STRING FORM. ``torch.device("cuda")``
    and ``torch.device("cuda:0")`` are different keys and therefore different
    accumulators, even though they name one GPU. The engine always builds the
    indexed form (:mod:`arbi_serve.engine.engine_init`), so serving is
    consistent; a harness or test that primes with the bare ``"cuda"`` and
    then drives a path reading ``tensor.device`` gets a SECOND, unprimed
    instance whose counts buffer was never materialized — which silently
    routes :func:`~arbi_serve.spec_decode.verify_penalties._committed_counts`
    down its padded-history fallback and measures the wrong path. Pass the
    indexed device.
    """
    if device.type == "cuda":
        if _POOL_ALLOCATE is None:
            return None
        if (int(vocab_size), str(dtype)) != _POOL_SHAPE:
            # The boot reserve was computed for a specific vocab x dtype.
            # Serving a different one would allocate bytes nobody budgeted,
            # out of a KV pool that was already handed them. Take the
            # counts path instead — correct, just slower — and say so once.
            if _SHAPE_MISMATCH_LOGGED.get(_POOL_SHAPE) is None:
                _SHAPE_MISMATCH_LOGGED[_POOL_SHAPE] = True
                logger.warning(
                    "penalty accumulator DISENGAGED: boot reserved %s but the "
                    "sampler asked for (vocab=%d, dtype=%s). The penalty path "
                    "falls back to the per-step counts matrix. Fix the boot "
                    "reserve (predict_penalty_accum_pool_bytes) rather than "
                    "letting it allocate unbudgeted.",
                    _POOL_SHAPE,
                    int(vocab_size),
                    dtype,
                )
            return None
    key = (str(device), int(vocab_size), str(dtype))
    acc = _ACCUMULATORS.get(key)
    if acc is None:
        # A vocab / dtype change on the same device means a different model
        # is resident — free the stale buffer rather than keep it mapped.
        for stale in [k for k in _ACCUMULATORS if k[0] == key[0]]:
            _ACCUMULATORS.pop(stale).reset()
        rows = _POOL_MAX_ROWS if _POOL_ALLOCATE is not None else int(max_rows)
        acc = PenaltyAccumulator(
            device,
            vocab_size,
            dtype,
            max_rows=max(rows, int(max_rows)),
            allocate=_POOL_ALLOCATE,
        )
        _ACCUMULATORS[key] = acc
    elif _POOL_ALLOCATE is None and int(max_rows) > acc.max_rows:
        # UNPOOLED caller (CPU tests, any non-engine consumer): there is no
        # boot reserve to overrun, so the cap must follow the widest batch
        # actually seen. Pinning it to the FIRST batch's width made a
        # growing batch raise on its second call — caught by #1160's
        # test_every_served_sampler_kernel_is_warmed, which walks B upward
        # through apply_penalties.
        #
        # The cap stays HARD on the pooled path, which is the one where
        # growing past it would spend VRAM the KV pool was handed.
        acc.max_rows = int(max_rows)
    return acc


def drop_penalty_accumulator_request(request_id: int) -> None:
    """Invalidate one request before rewriting its scoring history."""
    for acc in _ACCUMULATORS.values():
        acc.drop(request_id)


def reset_penalty_accumulators() -> None:
    """Drop every accumulator (model swap / engine rebuild / test isolation)."""
    for acc in _ACCUMULATORS.values():
        acc.reset()
    _ACCUMULATORS.clear()


def uninstall_penalty_accumulator_pool() -> None:
    """Forget the installed pool hook and every accumulator built through it.

    The counterpart to :func:`install_penalty_accumulator_pool`, for the
    stable-VA member-build seam
    (:func:`arbi_serve.engine.member_scratch_retire.retire_member_scoped_device_caches`).
    The installed closure captures the OUTGOING member's
    ``scratch.penalty_accum`` pool (and a carve of its persistent slab); once
    that member is parked and its pool physical evicted, an allocation through
    the stale closure lands in unmapped VA. Leaving it disengaged until the
    incoming member's build re-installs its own is exactly the pre-install
    behaviour (:func:`get_penalty_accumulator` returns ``None`` on CUDA), so
    nothing is served from a dead pool in the window.
    """
    global _POOL_ALLOCATE, _POOL_MAX_ROWS, _POOL_SHAPE
    reset_penalty_accumulators()
    _POOL_ALLOCATE = None
    _POOL_MAX_ROWS = 0
    _POOL_SHAPE = None
# ---- penalty_history.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Device-resident, incrementally-appended token histories for the penalty path.

Why this exists
---------------
:func:`arbi_serve.sampler.processors.apply_penalties` needs, per decode
step, a padded ``(B, max_hist)`` tensor of every row's ``prompt +
output`` token ids so one ``scatter_add_`` can build the occurrence
counts. Rebuilding that from the Python lists on every step is O(total
context) HOST work per step, and it dominated the whole penalty path:

    B=64, V=248320, hist=16896, measured on a 4090 (sm_89)
        apply_penalties TOTAL         56.6 ms
        rebuild from Python lists     53.6 ms   (94.8%)
        everything on the device       0.9 ms   ( 1.7%)

The prompt never changes and the output grows by a handful of tokens per
step, so the history is APPEND-ONLY in the common case. This cache keeps
each row's ids in a pooled device buffer and appends only the new tail,
turning the per-step host cost from O(context) into O(tokens appended).
``apply_penalties`` at that shape goes from 56.6 ms to 0.435 ms.

End-to-end, Qwen3.5-0.8B TP1 bf16, 16k prompts, ``--ignore-eos`` pinning
both arms to exactly 512 output tokens, one server boot per row, ONLY
``presence_penalty`` varying (TPOT ms, two reps each)::

                    c16 pp=0      c16 pp=2    tax      c64 pp=0      c64 pp=2     tax
    before   13.92 / 13.77   20.13 / 20.22   +46%   21.41 / 21.51  40.62 / 41.92  +93%
    after    13.76 / 13.91   14.53 / 14.71   + 5%   21.41 / 21.49  23.22 / 22.79  + 7%

The ``pp=0`` control is unchanged to within noise, which is what makes
the ``pp=2`` column attributable. Note what it also says: arbi's
penalty-FREE decode (13.8 ms at c16) is already slower than vLLM's and
SGLang's penalty-INCLUSIVE decode (10.1 / 9.8 ms), so the residual
cross-engine gap at c16/c64 is baseline decode, not this path — do not
expect more of it from here.

Correctness
-----------
The returned tensor is bit-identical to the freshly rebuilt one: same
ids, same ``vocab_size`` pad sink, same dtype. A row is REBUILT from
scratch whenever the append-only assumption cannot be proven:

* the row is new;
* ``len(prompt_token_ids)`` changed — a re-prefill rewrite (preemption,
  lost-snapshot recovery, and their SPMD mirror replay) folds the emitted
  output back into the prompt;
* the total history got SHORTER than what is cached.

Within a fixed prompt length a longer-or-equal total can only come from
appends, so the cached prefix is provably still valid.

That covers the fold exactly, and not by luck, on BOTH of the scopes
:func:`penalty_history_parts` can hand back. The ``prompt + output`` scope
sees the prompt length change, which routes the row to a rebuild. The
output-only scope is scored against
:func:`~arbi_serve.engine.request.generated_token_ids`, whose
length and order the fold does not change at all — the tokens move, the
sequence does not — so the cached prefix survives and the row appends as
it would have without the rewrite.

Keyed by ``request_id`` (an ``int`` on both :class:`Request` and the SPMD
``_MirroredRequest`` view) rather than object identity, because the SPMD
path builds a FRESH per-row view object every step. Ids are unique only
WITHIN one engine instance — ``engine_init`` seeds a fresh
``itertools.count(1)`` — so a rebuilt engine would reuse them. The
process-wide caches are therefore dropped in ``Sampler.__init__``, which
runs once per engine build.
"""

from __future__ import annotations

from collections.abc import Sequence

import torch

from arbi_serve.engine.request import generated_token_ids

# Rows are held in an int32 pool (a token id always fits, and the pad
# sink is ``vocab_size``, itself well under 2**31). The scatter index
# must be int64, so the per-step gather casts — copying B*max_hist, not
# the whole pool.
_POOL_DTYPE = torch.int32

# Grow the per-row capacity in chunks so a slowly growing context does
# not realloc every step.
_CAP_CHUNK = 2048


def penalty_history_parts(req: object) -> tuple[Sequence[int], Sequence[int]]:
    """The ``(prompt, output)`` id sequences a penalty must count over.

    SCOPE IS PER-KNOB, and this is the function that decides it:

    * ``presence_penalty`` / ``frequency_penalty`` count the OUTPUT ONLY.
      That is the OpenAI contract and what vLLM and sglang implement.
    * ``repetition_penalty`` is the one knob scoped to ``prompt + output``.

    So the prompt is included here only when the row actually asks for a
    repetition penalty. Counting the prompt for presence/frequency is not
    a harmless superset: at a 16k prompt with the Qwen non-thinking
    recipe's ``presence_penalty=1.5``, EVERY distinct token in the
    document takes a -1.5 logit hit on every decode step, so the engine
    penalises the exact vocabulary of the text it was asked to summarise.
    The damage grows with prompt length, which is why it showed up as a
    long-context regression before it showed up as a quality complaint.

    KNOWN RESIDUAL: a row that sets repetition != 1.0 AND presence or
    frequency != 0 gets the prompt counted for all three, because the
    accumulator keeps ONE occurrence buffer per row and repetition needs
    the prompt in it. Splitting that needs a second buffer (or a separate
    prompt-seen mask threaded through the fused kernel) and is not worth
    the VRAM for a combination no shipped profile uses — Qwen ships
    ``repetition_penalty=1.0`` in every profile.

    A request may override the history entirely by setting
    ``penalty_token_ids``, in which case THAT list is the whole history
    and the prompt contributes nothing.

    The override exists for the frame-lockstep duplex text channel (design
    doc §7.53), whose ``output_token_ids`` is one entry per 80 ms tick and
    therefore ~95% PAD: scored raw, a repetition penalty would drive PAD —
    the token that holds a turn open and closes it — down on every step,
    and the turn machinery is built on PAD being freely re-emittable. The
    duplex layer instead maintains a list of the connection's REAL spoken
    text tokens, so PAD/BOS/EOS are absent from the history and thus can
    never be penalized. Filtering the history IS the special-token
    carve-out; no sampler branch is needed for one.

    Both penalty caches (:class:`PenaltyHistoryCache` and
    ``PenaltyAccumulator``) assume an append-only history and detect a
    rewrite by comparing lengths, so an override must only ever grow —
    which the duplex list does, one entry per real text token.
    """
    prompt, output = sequence_history_parts(req)
    sp = getattr(req, "sampling", None)
    rep = getattr(sp, "repetition_penalty", 1.0) if sp is not None else 1.0
    if rep != 1.0:
        return prompt, output
    # Presence / frequency only: output-only scope — and OUTPUT here means
    # every token the request GENERATED, not the live ``output_token_ids``
    # list. A re-prefill rewrite (preemption, lost-snapshot recovery) folds
    # the generated tokens into the prompt and empties that list, and a
    # request scored against the emptied one stops penalising everything it
    # had already said: it starts repeating itself after a preemption with
    # nothing in any log to say why. ``repetition_penalty`` above is
    # untouched precisely because its ``prompt + output`` scope is already
    # fold-invariant, and that asymmetry is the whole shape of the bug.
    #
    # An override is the whole history by construction and owns its own
    # scope, so it is never augmented here.
    if req.penalty_token_ids is None:  # type: ignore[attr-defined]
        output = generated_token_ids(req)
    return (), output


def sequence_history_parts(req: object) -> tuple[Sequence[int], Sequence[int]]:
    """The FULL ``(prompt, output)`` the request has seen and said.

    Scope-free: this is "what tokens exist", with only the
    ``penalty_token_ids`` override applied. Consumers that must see the
    prompt regardless of any penalty knob read this — notably
    ``no_repeat_ngram_size``, which has to block an n-gram that occurred
    in the PROMPT and would silently stop doing so if it inherited
    presence/frequency's output-only scope.

    ``penalty_token_ids`` is read as a plain attribute, so every
    Request-shaped view the scoring path is handed must declare it. A view
    that merely LACKED it would read as "no override" and be scored against
    ``prompt + output`` — which for the one request type that sets the
    override is the PAD stream the override exists to keep out, and a wrong
    history is not a thing that can be noticed downstream.
    """
    override = req.penalty_token_ids  # type: ignore[attr-defined]
    if override is not None:
        return (), override
    return req.prompt_token_ids, req.output_token_ids  # type: ignore[attr-defined]


class PenaltyHistoryCache:
    """Pooled ``(rows, cap)`` int32 device buffer of per-request histories.

    One instance per ``(device, vocab_size)`` pair; see
    :func:`get_penalty_history_cache`. Not thread-safe — the sampler runs
    single-threaded inside the engine step.
    """

    def __init__(self, device: torch.device, vocab_size: int) -> None:
        self.device = device
        self.vocab_size = vocab_size
        self._pool: torch.Tensor | None = None
        self._cap = 0
        self._rows = 0
        # Per-row bookkeeping, indexed by row.
        self._owner: list[int] = []  # request_id, or -1 when free
        self._prompt_len: list[int] = []
        self._len: list[int] = []
        self._touch: list[int] = []  # tick of last use, for LRU eviction
        self._by_request: dict[int, int] = {}
        self._tick = 0

    # -- pool growth ------------------------------------------------------

    def _ensure(self, rows: int, cap: int) -> None:
        """Grow the pool to at least ``rows`` x ``cap``, preserving content."""
        if rows <= self._rows and cap <= self._cap:
            return
        new_rows = max(rows, self._rows)
        new_cap = max(cap, self._cap)
        if new_cap > self._cap:
            new_cap = ((new_cap + _CAP_CHUNK - 1) // _CAP_CHUNK) * _CAP_CHUNK
        new_pool = torch.full(
            (new_rows, new_cap),
            self.vocab_size,
            dtype=_POOL_DTYPE,
            device=self.device,
        )
        if self._pool is not None and self._rows and self._cap:
            new_pool[: self._rows, : self._cap] = self._pool
        self._pool = new_pool
        for _ in range(new_rows - self._rows):
            self._owner.append(-1)
            self._prompt_len.append(0)
            self._len.append(0)
            self._touch.append(-1)
        self._rows = new_rows
        self._cap = new_cap

    def _claim_row(self, request_id: int) -> int:
        """Return a row for ``request_id``, evicting an idle row if needed."""
        for row in range(self._rows):
            if self._owner[row] == -1:
                break
        else:
            # No free row: evict the least-recently-used row that is NOT
            # part of the batch currently being built (touch < tick).
            row = -1
            oldest = self._tick
            for r in range(self._rows):
                if self._touch[r] < oldest:
                    oldest = self._touch[r]
                    row = r
            if row < 0:
                # Every row belongs to the current batch — grow.
                self._ensure(self._rows + 1, self._cap or _CAP_CHUNK)
                row = self._rows - 1
        prev = self._owner[row]
        if prev != -1:
            self._by_request.pop(prev, None)
        self._owner[row] = request_id
        self._by_request[request_id] = row
        self._prompt_len[row] = 0
        self._len[row] = 0
        return row

    # -- public API -------------------------------------------------------

    def padded(self, requests: Sequence[object]) -> torch.Tensor | None:
        """Return the ``(B, max_hist)`` int64 padded history, or ``None``.

        ``None`` means every row's history is empty (nothing to count).
        The pad value is ``vocab_size``, matching the ``(B, V+1)`` counts
        buffer's discarded sink column.
        """
        self._tick += 1
        tick = self._tick
        B = len(requests)
        # Pre-size to the batch so a cold pool grows once, not B times.
        if self._rows < B:
            self._ensure(B, max(self._cap, _CAP_CHUNK))

        rows: list[int] = []
        totals: list[int] = []
        max_total = 0
        # (row, start, ids) writes to push to the device this step.
        rebuilds: list[int] = []
        writes: list[tuple[int, int, list[int]]] = []

        for req in requests:
            rid = int(req.request_id)  # type: ignore[attr-defined]
            prompt, output = penalty_history_parts(req)
            plen = len(prompt)
            total = plen + len(output)
            if total > max_total:
                max_total = total

            row = self._by_request.get(rid, -1)
            fresh = row < 0
            if fresh:
                self._ensure(max(self._rows, 1), max(self._cap, total, _CAP_CHUNK))
                row = self._claim_row(rid)
            elif self._prompt_len[row] != plen or self._len[row] > total:
                # Prompt rewritten (recompute) or history reset (preemption):
                # the append-only assumption is broken — rebuild this row.
                fresh = True
                self._prompt_len[row] = 0
                self._len[row] = 0

            if total > self._cap:
                self._ensure(self._rows, total)

            if fresh:
                rebuilds.append(row)
                if total:
                    writes.append((row, 0, list(prompt) + list(output)))
            else:
                have = self._len[row]
                if total > have:
                    # Append only the new tail. It straddles the
                    # prompt/output boundary only on the first post-prefill
                    # step, which the prompt-length check already routes to
                    # a rebuild, so the tail is pure output in practice.
                    if have >= plen:
                        tail = list(output[have - plen : total - plen])
                    else:
                        tail = list(prompt[have:]) + list(output)
                    writes.append((row, have, tail))
            self._prompt_len[row] = plen
            self._len[row] = total
            self._touch[row] = tick
            rows.append(row)
            totals.append(total)

        if max_total == 0:
            return None

        assert self._pool is not None
        cap = self._cap
        # Rebuilt rows must be reset to the pad sink first: their previous
        # tenant's ids would otherwise leak past the new history's end.
        if rebuilds:
            idx = torch.as_tensor(rebuilds, dtype=torch.int64, device=self.device)
            self._pool.index_fill_(0, idx, self.vocab_size)

        if writes:
            flat_pos: list[int] = []
            flat_val: list[int] = []
            for row, start, ids in writes:
                base = row * cap + start
                flat_pos.extend(range(base, base + len(ids)))
                flat_val.extend(ids)
            pos = torch.as_tensor(flat_pos, dtype=torch.int64).to(self.device, non_blocking=True)
            val = torch.as_tensor(flat_val, dtype=_POOL_DTYPE).to(self.device, non_blocking=True)
            self._pool.view(-1).scatter_(0, pos, val)

        # Gather the batch's rows. Slicing to ``max_total`` first keeps the
        # copy at B*max_total instead of B*cap.
        view = self._pool[:, :max_total]
        if rows == list(range(B)):
            gathered = view[:B]
        else:
            idx = torch.as_tensor(rows, dtype=torch.int64, device=self.device)
            gathered = view.index_select(0, idx)
        return gathered.to(torch.int64)

    def drop(self, request_id: int) -> None:
        """Release the row held by ``request_id`` (no-op when absent)."""
        row = self._by_request.pop(int(request_id), -1)
        if row >= 0:
            self._owner[row] = -1
            self._prompt_len[row] = 0
            self._len[row] = 0
            self._touch[row] = -1

    def reset(self) -> None:
        """Drop every cached row and free the pool."""
        self._pool = None
        self._cap = 0
        self._rows = 0
        self._owner.clear()
        self._prompt_len.clear()
        self._len.clear()
        self._touch.clear()
        self._by_request.clear()


# One cache per (device, vocab_size). A model swap that changes the vocab
# gets its own cache; the stale one is dropped so its pool is freed.
_CACHES: dict[tuple[str, int], PenaltyHistoryCache] = {}


def get_penalty_history_cache(device: torch.device, vocab_size: int) -> PenaltyHistoryCache:
    """Return the process-wide cache for ``(device, vocab_size)``."""
    key = (str(device), int(vocab_size))
    cache = _CACHES.get(key)
    if cache is None:
        # A vocab change on the same device means a different model is
        # resident — free the old pool rather than keep it around.
        for stale_key in [k for k in _CACHES if k[0] == key[0]]:
            _CACHES.pop(stale_key).reset()
        cache = PenaltyHistoryCache(device, vocab_size)
        _CACHES[key] = cache
    return cache


def drop_penalty_history_request(request_id: int) -> None:
    """Invalidate one request before rewriting its scoring history."""
    for cache in _CACHES.values():
        cache.drop(request_id)


def reset_penalty_history_caches() -> None:
    """Drop every cache (model swap / test isolation)."""
    for cache in _CACHES.values():
        cache.reset()
    _CACHES.clear()
# ---- penalty_triton.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Single-pass fused repetition / frequency / presence penalty kernel.

The PyTorch chain in :func:`arbi_serve.sampler.processors.apply_penalties`
is vectorized but not fused: it materialises six-to-eight full
``(K, B, V)`` intermediates, each one a separate launch reading and
writing the whole vocab. This kernel does the whole chain in ONE pass:
read ``logits`` + ``counts``, write ``out``.

There is deliberately NO runtime flag gating this. The kernel is
bit-identical to the chain it replaces — ``tests/test_sampler_penalty_fusion.py``
is what asserts that — and no batch has measured it a loss, so there is
nothing for an operator to A/B; the unfused PyTorch chain remains as the
non-CUDA path, which keeps it exercised.

WHERE FUSION PAYS, AND WHERE WE SERVE. Two mechanisms decide it, and the
served ``--max-batch`` decides which one applies:

* While the ``counts`` matrix still fits L2, the unfused chain's extra
  passes are nearly free and presence-only fusion is a TIE, not a win —
  a pure memory-traffic argument overestimates it there. The served
  recipe sits deep inside that regime (``compose.dflash.yaml`` ships
  ``--max-batch=8``), which is why an end-to-end A/B on a served
  configuration cannot separate fused from unfused.
* Fusion pays once ``counts`` spills L2, and whenever repetition or
  frequency are also active, because the unfused path then materialises
  the repetition branch as well. So what fusion buys AT THE SERVED BATCH
  is a penalty cost that is flat in WHICH knobs a tenant sets, not a
  throughput win — a per-batch magnitude quoted for this kernel has to
  name the batch, the vocab and the card it was swept on, and none is
  recorded in-tree.
* None of it is the headline win either way: the penalty path's cost is
  dominated by HOST-side history rebuilding, which is what
  :mod:`penalty_history` exists to remove.

Bit-identity
------------
The result is BIT-IDENTICAL to the PyTorch chain, not merely close.
PyTorch's CUDA elementwise kernels evaluate bf16 operands in fp32
(``opmath_t = float``) and round to bf16 on store, so every intermediate
in the reference chain is a bf16 value. The kernel reproduces that by
keeping every intermediate in the LOGITS dtype and issuing one Triton op
per PyTorch op, which lowers to the same cvt-f32 / op / cvt.rn-bf16
sequence.

Two things had to be got right, both caught by
``tests/test_sampler_penalty_fusion.py`` and neither visible under a
tolerance-based comparison:

* Do NOT hand-roll the rounding as ``.to(dtype).to(tl.float32)`` around
  each step. The compiler folds the truncate/extend PAIR away, the
  intermediates silently keep fp32 precision, and the result then
  diverges from the reference at exact round-to-even ties.
* Triton's default fp32 divide is APPROXIMATE. ``tl.fdiv(...,
  ieee_rounding=True)`` is required for the repetition branch.

The reference chain being replicated, in order::

    counts3 = counts.to(dtype)  # (1, B, V)
    seen3 = counts3 > 0
    rep_adj = where(logits > 0, logits / rep, logits * rep)
    out = where(seen3 & (rep != 1.0), rep_adj, logits)
    out = out - freq * counts3
    out = out - pres * seen3.to(dtype)

Each of ``HAS_REP`` / ``HAS_FREQ`` / ``HAS_PRES`` is a ``constexpr``, so
a batch that asks for presence only compiles a kernel with the
repetition and frequency arithmetic removed entirely.

Two count sources
-----------------
``counts`` is either the per-step ``(B, V+1)[:, :V]`` fp32 matrix the
fallback path builds, or the persistent int32 occurrence buffer the
accumulator maintains. Same kernel, same arithmetic — they differ only in
the pointer dtype and the row stride, both of which Triton specializes on,
so both are in the boot warm set."""

from __future__ import annotations

import torch
import triton
import triton.language as tl


@triton.jit
def _penalty_kernel(
    LOGITS,  # (K*B, V) input logits
    COUNTS,  # (B, V) occurrence counts, fp32 (counts path) or int32 (accumulator)
    REP,  # (B,) repetition penalties, logits dtype
    FREQ,  # (B,) frequency penalties, logits dtype
    PRES,  # (B,) presence penalties, logits dtype
    OUT,  # (K*B, V) output
    B,  # runtime, NOT constexpr: batch size varies step to step and a
    V,  # constexpr B would recompile the kernel for every batch shape.
    stride_lr,
    stride_cr,
    HAS_REP: tl.constexpr,
    HAS_FREQ: tl.constexpr,
    HAS_PRES: tl.constexpr,
    BLOCK: tl.constexpr,
):
    row = tl.program_id(0)  # index into K*B
    blk = tl.program_id(1)
    b = row % B  # the (B,) penalty vectors are shared across K

    offs = blk * BLOCK + tl.arange(0, BLOCK)
    mask = offs < V

    lptr = LOGITS + row * stride_lr + offs
    logits = tl.load(lptr, mask=mask, other=0)
    dtype = logits.dtype

    # `other=0`, not `0.0`: COUNTS is fp32 on the fallback counts path and
    # int32 when it is the accumulator's persistent occurrence buffer.
    counts = tl.load(COUNTS + b * stride_cr + offs, mask=mask, other=0)
    # counts3 = counts.to(logits.dtype) — the reference DOWNCASTS before
    # comparing and before the frequency multiply, so both must see the
    # rounded value, not the raw one. A positive integer count never rounds
    # to zero, so `seen` is the same set either way.
    counts_d = counts.to(dtype)
    seen = counts_d > 0

    # Everything below stays in the LOGITS dtype, one Triton op per
    # PyTorch op. That is deliberate: an earlier version computed in fp32
    # and wrote `.to(dtype).to(tl.float32)` around each step to force the
    # reference's rounding, and the compiler folded those trunc/extend
    # PAIRS away — the products then kept full fp32 precision and the
    # result diverged from the reference at exact round-to-even ties (3
    # elements in 16396 at bf16). Native-dtype arithmetic lowers to
    # cvt-to-f32 / op / cvt.rn-to-bf16, which is precisely PyTorch's
    # `opmath_t = float` elementwise semantics, and there is no
    # foldable pair for the compiler to remove.
    out = logits
    if HAS_REP:
        rep = tl.load(REP + b)
        # DIVISION is the one op Triton does not lower like PyTorch: the
        # default fp32 divide is approximate (measured 1.9e-6 absolute
        # drift, enough to flip an fp32 result and a bf16 tie). MEASURED
        # over 2**20 fp32 pairs against torch: `a / b` and
        # `tl.fdiv(..., ieee_rounding=True)` BOTH mismatch on 316k of
        # them — ieee_rounding does not do what its name suggests here —
        # while `tl.math.div_rn` (libdevice __nv_div_rn) matches exactly.
        quot = tl.math.div_rn(logits.to(tl.float32), rep.to(tl.float32))
        adj = tl.where(logits > 0, quot.to(dtype), logits * rep)
        out = tl.where(seen & (rep != 1.0), adj, logits)

    if HAS_FREQ:
        freq = tl.load(FREQ + b)
        out = out - freq * counts_d

    if HAS_PRES:
        pres = tl.load(PRES + b)
        out = out - pres * tl.where(seen, 1.0, 0.0).to(dtype)

    tl.store(OUT + row * stride_lr + offs, out, mask=mask)


def fused_penalties_supported(logits: torch.Tensor) -> bool:
    """Whether the fused kernel can serve this tensor.

    CUDA only, contiguous, and a dtype whose PyTorch elementwise
    semantics the kernel reproduces exactly (fp32 compute, round on
    store).
    """
    return (
        logits.is_cuda
        and logits.is_contiguous()
        and logits.dtype in (torch.bfloat16, torch.float16, torch.float32)
    )


def apply_penalties_fused(
    logits: torch.Tensor,  # (K, B, V)
    counts: torch.Tensor,  # (B, V) fp32 or int32
    rep: torch.Tensor,  # (B,) logits dtype
    freq: torch.Tensor,  # (B,) logits dtype
    pres: torch.Tensor,  # (B,) logits dtype
    has_rep: bool,
    has_freq: bool,
    has_pres: bool,
) -> torch.Tensor:
    """Fused penalty application. Returns a new ``(K, B, V)`` tensor."""
    K, B, V = logits.shape
    out = torch.empty_like(logits)
    flat = logits.view(K * B, V)
    # 1024 lanes/block keeps the vocab sweep bandwidth-bound without
    # over-subscribing registers; V/1024 blocks x K*B rows saturates the
    # grid at every batch size we serve.
    block = 1024
    grid = (K * B, triton.cdiv(V, block))
    _penalty_kernel[grid](
        flat,
        counts,
        rep,
        freq,
        pres,
        out.view(K * B, V),
        B=B,
        V=V,
        stride_lr=flat.stride(0),
        stride_cr=counts.stride(0),
        HAS_REP=has_rep,
        HAS_FREQ=has_freq,
        HAS_PRES=has_pres,
        BLOCK=block,
        num_warps=4,
        # Bit-identity REQUIRES this. Triton contracts `out - freq *
        # counts` into a single FMA by default, which skips the rounding
        # of the intermediate product that the reference — two separate
        # PyTorch kernels — necessarily materialises. Without it the
        # results differ at exact round-to-even ties.
        enable_fp_fusion=False,
    )
    return out
# ---- processors.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Logits processors operating on ``(K, num_seqs, vocab_size)`` tensors.

Every processor takes a 3-D logits tensor and returns one of the same
shape; ``K=1`` in the non-MTP path. Constant-K shape costs zero at
runtime and keeps the surface MTP-ready.

The :class:`LogitsProcessor` protocol is the seam structured-decoding
processors plug into. The free-function processors below
(``apply_penalties``, ``apply_logit_bias``, ``apply_temperature``)
are the built-in chain.

Vectorization. Each free-function processor short-circuits when no
request needs it (greedy / default knobs across the batch). When the
batch is mixed the per-request work is done with one batched tensor op
instead of a Python loop over rows: penalty counts via a single padded
``scatter_add_`` on ``(B, max_recent)`` history, temperature via an
in-place ``logits.div_(temp.unsqueeze(1))``, and logit-bias via a
single padded ``scatter_add_`` on ``(B, max_bias_keys)`` ids/vals.
"""

from __future__ import annotations

from collections.abc import Sequence
from typing import Protocol

import torch

from arbi_serve.engine.request import Request
from arbi_serve.sampler.penalty_accumulator import get_penalty_accumulator
from arbi_serve.sampler.penalty_history import get_penalty_history_cache
from arbi_serve.sampler.sampling_metadata import _SamplingMetadata, _staging_empty
from arbi_serve.sampler.vocab_window import VocabWindow, window_bounds


class LogitsProcessor(Protocol):
    """Per-step logits transformer.

    A processor reads ``(K, num_seqs, V)`` logits and the per-request
    list and returns a same-shape tensor. It MAY mutate per-request
    internal state (e.g. an xgrammar matcher) when invoked, but MUST
    NOT mutate other requests' state — the multi-tenant invariant
    requires processors to be reentrant across the request set.

    Stateful processors keep their per-request state on
    ``Request.grammar_state`` (or another request-scoped slot), never
    on the processor instance itself.
    """

    def __call__(
        self,
        logits: torch.Tensor,  # (K, num_seqs, V)
        requests: Sequence[Request],
    ) -> torch.Tensor: ...

    async def accept_token(
        self,
        request: Request,
        token: int,
    ) -> None:
        """Inform the processor that ``token`` was committed for ``request``.

        Called by the engine after sampling, before the next forward.
        Stateless processors implement this as a no-op; stateful ones
        (xgrammar) advance their per-request automaton here.
        Implementations doing CPU-bound work should remain sync-fast
        (one matcher step per token); otherwise dispatch via
        ``asyncio.to_thread``.
        """
        ...

    def verify_slate_reads_drafts(self, requests: Sequence[Request]) -> bool:
        """Whether :meth:`apply_to_verify_slate` reads ``drafts_per_row``
        for any of ``requests``.

        The verify path keeps the draft tokens on the device and pulls them
        to the host only for a processor that answers True here. The default
        is True: a processor that has not said otherwise is handed the
        tokens, never a slate it cannot constrain.
        """
        del requests
        return True

    def apply_to_verify_slate(
        self,
        logits: torch.Tensor,  # (K+1, num_seqs, W) — masked IN PLACE
        requests: Sequence[Request],  # one per COLUMN
        drafts_per_row: Sequence[Sequence[int]],  # per-column draft token ids
        *,
        window: VocabWindow | None = None,
    ) -> None:
        """Apply this processor's constraint to the MTP verify slate.

        The speculative draw does not run ``__call__``: it samples a
        ``(K+1, B, V)`` slate whose column ``col``, position ``p`` draws the
        continuation of ``drafts_per_row[col][:p]``, so a constraint derived
        from a row's token history must be rebuilt PER POSITION from those
        drafts rather than applied once against the committed history. This
        method is that per-position form, and it is the reason the chain
        cannot simply be replayed on the slate.

        Every member of the chain implements it: the verify path reads it
        directly off each processor, so a processor that does not have one
        is an error and never a row served unconstrained. A processor whose
        constraint has NO per-position form REFUSES the rows that asked for
        it — a request must not receive a constraint on the ``K=1`` draw and
        silently lose it the moment speculation turns on.

        Position-independent constraints (a fixed per-request vocabulary
        mask) apply unchanged across all ``K+1`` positions.

        ``window`` restricts the write to one vocab-parallel rank's slice of
        the vocabulary, for the shard-resident verify draw. Every constraint
        here is per-token, so the restriction is exact: keep the entries the
        window carries and index them by ``global_id - start``. A processor
        that cannot restrict its own form must RAISE on a window rather than
        apply a full-vocab mask to a shard's columns, which would ban the
        wrong tokens outright. ``None`` is the whole vocabulary.
        """
        ...

    def constrains_verify_slate(self, requests: Sequence[Request]) -> bool:
        """Whether :meth:`apply_to_verify_slate` would write for ``requests``.

        The shard-resident verify draw has to know BEFORE it lays out the
        slate whether anything will be applied to it, because reaching the
        appliers at all costs it a reorder of the vocab-wide local logits.
        Asking each processor is the only form of that question that cannot
        go stale: a caller-side list of "which flags mean constrained" would
        answer for the processors that existed when it was written, and a
        new one would be silently skipped on that path alone.

        Must agree with :meth:`apply_to_verify_slate` — a ``True`` that
        writes nothing is only wasted work, but a ``False`` that would have
        written is a request served unconstrained.
        """
        ...


# ---------------------------------------------------------------------------
# Vectorized helpers (private). The public free-function entry points
# below use these for the "any request needs work" path.
# ---------------------------------------------------------------------------


_ONES_BY_DEVICE: dict[torch.device, torch.Tensor] = {}


def _scatter_one(device: torch.device) -> torch.Tensor:
    """A cached 0-d ``1.0`` on ``device``, for use as a stride-0 scatter src."""
    one = _ONES_BY_DEVICE.get(device)
    if one is None:
        one = torch.ones((), dtype=torch.float32, device=device)
        _ONES_BY_DEVICE[device] = one
    return one


def _build_padded_history(
    requests: Sequence[Request],
    vocab_size: int,
    device: torch.device,
) -> torch.Tensor | None:
    """Return the padded ``(B, max_recent)`` int64 history, or ``None``.

    ``None`` when every request's history is empty.

    The pad value is ``vocab_size`` so a downstream ``scatter_add_`` into
    a ``(B, V+1)`` counts buffer hits a sink column we discard. This
    avoids materialising a separate row-mask scatter.

    Delegates to :class:`~arbi_serve.sampler.penalty_history.PenaltyHistoryCache`,
    which keeps the ids resident on the device and appends only each
    step's new tail. Rebuilding this from the Python lists every step was
    94.8% of the whole penalty path at ``B=64, hist=16k`` (53.6 ms of
    56.6 ms) — the histories are append-only, so re-reading O(context)
    ints per step was pure waste.
    """
    return get_penalty_history_cache(device, vocab_size).padded(requests)


def _fused_penalties_engaged(logits: torch.Tensor) -> bool:
    """Whether this step takes the single-pass Triton penalty kernel.

    Not behind a runtime flag: the kernel is bit-identical to the chain
    below (``tests/test_sampler_penalty_fusion.py`` asserts
    ``torch.equal`` across bf16/fp16/fp32, four shapes and four knob
    combinations) and measured a tie-or-win, never a loss — so there is
    no quality or perf question for an operator to A/B. The unfused chain
    stays as the non-CUDA path, which is what keeps it exercised.

    Triton is imported lazily so the CPU path never needs it.
    """
    if not logits.is_cuda:
        return False
    try:
        from arbi_serve.sampler.penalty_triton import fused_penalties_supported
    except ImportError:  # pragma: no cover — triton absent
        return False
    return fused_penalties_supported(logits)


def apply_penalties(
    logits: torch.Tensor,  # (K, num_seqs, W) fp32 — W = window width, else V
    requests: Sequence[Request],
    meta: _SamplingMetadata | None = None,
    *,
    inplace: bool = False,
    window: VocabWindow | None = None,
) -> torch.Tensor:
    """Apply repetition / frequency / presence penalties per request.

    ``window`` restricts the write to one vocab-parallel rank's slice: the
    per-``(row, token)`` occurrence state is a global-vocab quantity, so it
    is read at full width and the WINDOW is what narrows — a view of the
    resident accumulator, never a shard-side reimplementation of the
    arithmetic. ``None`` is the full vocabulary and is byte-identical to
    having no window parameter at all.

    Scope is PER-KNOB and lives in
    :func:`~arbi_serve.sampler.penalty_history.penalty_history_parts`:
    presence / frequency count the OUTPUT ONLY, repetition counts
    ``prompt + output``. Returns
    a new tensor of the same shape by default; in-place is not the default
    because penalties may need to write to logits that are still backed by
    a CUDAGraph output buffer.

    ``inplace`` writes the result INTO ``logits`` and returns it, for a
    caller that was going to ``copy_`` the result back anyway and owns the
    buffer. On the production path — presence and/or frequency with no
    repetition — that turns three full-vocab passes (read, write a fresh
    tensor, read it back, write the original) into ONE fused subtract.
    Only worth asking for on a caller whose tensor is big enough for that
    to matter: the MTP verify slate is ``(K+1, B, V)``, i.e. K+1 times the
    K=1 sampler's own draw.

    All three knobs are functions of ONE per-``(row, token)`` occurrence
    history, which the persistent accumulator
    (:mod:`arbi_serve.sampler.penalty_accumulator`) maintains
    incrementally. Whenever it is available this function reads that state
    and never builds a per-step counts matrix:

    * with no repetition anywhere in the batch, presence + frequency are
      ADDITIVE, so they arrive pre-summed as the accumulator's ``(B, V)``
      delta and the step is one subtraction — no penalty kernel at all;
    * a batch that DOES ask for repetition takes the fused kernel, reading
      the accumulator's int32 occurrence buffer where the fallback reads a
      freshly scattered fp32 matrix. Everything else about that tail is
      identical, which is what makes the two bit-identical.

    The counts path is the fallback for callers with no accumulator (on
    CUDA: no engine pool hook, or a vocab/dtype the boot reserve was not
    computed for). It allocates and scatters a ``(B, V+1)`` matrix per
    call.

    ``tests/test_sampler_penalty_accumulator.py`` drives both arms through
    this entry point and compares with ``torch.equal``.
    """
    K, B, W = logits.shape
    if len(requests) != B:
        raise RuntimeError(f"apply_penalties: logits has B={B} but {len(requests)} requests.")
    if window is not None and window.width != W:
        raise RuntimeError(
            f"apply_penalties: window width {window.width} != logits last dim {W}; "
            f"the caller must trim the local slice to the window's REAL columns."
        )
    # The occurrence state is indexed by GLOBAL token id, so every lookup
    # below is sized by the global vocabulary even when the write is not.
    V = window.vocab_size if window is not None else W

    # PREFER THE CACHED KNOBS. ``_slate_sampling_key`` already keys on all
    # three penalties, so the slate cache guarantees byte-identical
    # tensors for an unchanged slate. Rebuilding them here cost a Python
    # loop over requests plus three PAGEABLE (therefore synchronous) H2D
    # copies on EVERY decode step — for values the cache had already paid
    # to key on. The fallback below is for direct callers and tests.
    _cached = (
        meta is not None
        and getattr(meta, "repetition_penalty", None) is not None
        and meta.repetition_penalty.shape[0] == B
    )
    if _cached:
        rep = meta.repetition_penalty
        freq = meta.frequency_penalty
        pres = meta.presence_penalty
        any_rep = meta.any_repetition
        any_freq = meta.any_frequency
        any_pres = meta.any_presence
    else:
        rep = torch.empty(B, dtype=torch.float32)
        freq = torch.empty(B, dtype=torch.float32)
        pres = torch.empty(B, dtype=torch.float32)
        any_rep = False
        any_freq = False
        any_pres = False
        for i, req in enumerate(requests):
            sp = req.sampling
            rep[i] = sp.repetition_penalty
            freq[i] = sp.frequency_penalty
            pres[i] = sp.presence_penalty
            if sp.repetition_penalty != 1.0:
                any_rep = True
            if sp.frequency_penalty != 0.0:
                any_freq = True
            if sp.presence_penalty != 0.0:
                any_pres = True
    if not (any_rep or any_freq or any_pres):
        return logits
    # From here ``inplace`` is honoured at every return: each one either
    # writes through ``logits`` itself or copies the fresh tensor back into
    # it, so the contract "the answer is in ``logits``" holds on every path.

    # ----- Persistent accumulator -----
    # One (rows, V) buffer pair carries the whole penalty state: the
    # additive presence+frequency term and the int32 occurrence counts.
    # The step's device work is a subtraction, plus one more pass when
    # repetition is asked for. No per-step counts matrix, no history
    # gather.
    counts: torch.Tensor | None = None
    acc = get_penalty_accumulator(logits.device, V, logits.dtype, max_rows=B)
    if acc is not None:
        # `want_accum` is False on a repetition batch: the tail below reads
        # the counts and derives presence / frequency from them, so folding
        # the pre-summed entry as well would be per-step work nothing
        # reads. The accumulator flags those rows and repairs them from the
        # counts if a later batch does need the entry.
        delta = acc.update(requests, pres, freq, need_counts=any_rep, want_accum=not any_rep)
        if delta is None:
            return logits
        if window is not None:
            delta = window.slice_rows(delta)
        if not any_rep:
            # THE production path: presence and/or frequency, no repetition.
            if inplace:
                return logits.sub_(delta.unsqueeze(0))
            return logits - delta.unsqueeze(0)
        counts = acc.counts_view(B)  # (B, V) int32, row stride V
        if counts is not None and window is not None:
            counts = window.slice_rows(counts)

    if counts is None:
        pad_ids = _build_padded_history(requests, V, logits.device)
        if pad_ids is None:
            return logits
        if window is not None:
            # Localize, and send every id the window does not carry to the
            # SAME pad sink the history's own pad value already uses. The
            # scatter target is then window-wide, not vocab-wide: a shard
            # must never allocate a full-vocab counts matrix, which is the
            # cost the windowed path exists to avoid.
            local = window.localize(pad_ids)
            pad_ids = torch.where((local >= 0) & (local < W), local, torch.full_like(local, W))

        # counts: (B, W+1); the W'th column is the pad sink.
        #
        # Allocated + zeroed per call rather than kept resident: a persistent
        # (B, V+1) buffer is ~61 MiB at B=64 that would have to be reserved
        # at boot, against KV, for a capability most deployments never use.
        # Making that trade needs a boot-time budget flag, not a silent
        # allocation here.
        counts = torch.zeros(B, W + 1, dtype=torch.float32, device=logits.device)
        # The scatter increments by one per occurrence, so `src` is constant.
        # A stride-0 expand carries no storage at all; `ones_like(pad_ids)`
        # would allocate and fill a (B, history) fp32 tensor every step to
        # hold nothing but 1.0.
        counts.scatter_add_(1, pad_ids, _scatter_one(logits.device).expand_as(pad_ids))
        counts = counts[:, :W]  # (B, W) — drop the pad sink.

    # Cast helpers to the logits dtype so the chain preserves bf16/fp32.
    # PyTorch type promotion would otherwise upcast (bf16, fp32) -> fp32
    # in `logits / rep_b`, costing a ~vocab*bf16 D2D copy per call.
    #
    # PER-KNOB early-out. Each of the three penalties is skipped whole
    # when NO row asks for it, instead of running the full-vocab op and
    # discarding it. This is not a corner case: Qwen ships
    # repetition_penalty=1.0 in every profile (0.8B and 27B, thinking and
    # non-thinking), so under a stock serving config the repetition branch
    # below — which evaluates BOTH `logits / rep` and `logits * rep` over
    # the entire (K, B, V) tensor before throwing the result away — is
    # pure waste on every decode step.
    rep_d = rep.to(logits.device, dtype=logits.dtype, non_blocking=True)
    freq_d = freq.to(logits.device, dtype=logits.dtype, non_blocking=True)
    pres_d = pres.to(logits.device, dtype=logits.dtype, non_blocking=True)

    if _fused_penalties_engaged(logits):
        from arbi_serve.sampler.penalty_triton import apply_penalties_fused

        fused = apply_penalties_fused(
            logits, counts, rep_d, freq_d, pres_d, any_rep, any_freq, any_pres
        )
        return logits.copy_(fused) if inplace and fused is not logits else fused

    # Broadcast (B, V) across the K dim.
    counts3 = counts.to(logits.dtype).unsqueeze(0)  # (1, B, V)
    seen3 = counts3 > 0
    rep_b = rep_d.view(1, B, 1)
    freq_b = freq_d.view(1, B, 1)
    pres_b = pres_d.view(1, B, 1)

    out = logits
    if any_rep:
        # Repetition: positive logits divide, negative multiply, only on
        # tokens whose count > 0. Match the legacy per-row formula.
        pos = logits > 0
        rep_adj = torch.where(pos, logits / rep_b, logits * rep_b)
        out = torch.where(seen3 & (rep_b != 1.0), rep_adj, logits)

    # Frequency: subtract freq_penalty * counts (zero rows are no-ops).
    if any_freq:
        out = out - freq_b * counts3
    # Presence: subtract presence_penalty on any seen token.
    if any_pres:
        out = out - pres_b * seen3.to(logits.dtype)
    return logits.copy_(out) if inplace and out is not logits else out


def apply_logit_bias(
    logits: torch.Tensor,  # (K, num_seqs, W) fp32 — W = window width, else V
    requests: Sequence[Request],
    *,
    window: VocabWindow | None = None,
) -> torch.Tensor:
    """Add per-request logit bias to specific token IDs.

    Vectorized: builds a padded ``(B, max_keys)`` ids tensor + matching
    values tensor, then one ``scatter_add_`` into a ``(B, W+1)`` buffer
    delivers every per-request bias in a single launch. The pad column
    is dropped before broadcasting back over K.

    ``window`` restricts the write to one vocab-parallel rank's slice. A
    bias is a per-``(row, token)`` constant, so the restriction is exact by
    inspection: keep the keys the window carries, index them by
    ``id - start``, and no other rank's keys can reach these columns.
    """
    K, B, W = logits.shape
    if len(requests) != B:
        raise RuntimeError(f"apply_logit_bias: logits has B={B} but {len(requests)} requests.")
    if window is not None and window.width != W:
        raise RuntimeError(
            f"apply_logit_bias: window width {window.width} != logits last dim {W}; "
            f"the caller must trim the local slice to the window's REAL columns."
        )
    lo, hi = window_bounds(window, W)

    # Gather per-request bias maps. Filter to the ids this window carries
    # (the whole vocabulary when there is none) so the padded scatter is
    # well-defined.
    rows: list[list[tuple[int, float]]] = []
    max_keys = 0
    any_active = False
    for req in requests:
        kvs: list[tuple[int, float]] = []
        for tid, bias in (req.sampling.logit_bias or {}).items():
            if lo <= tid < hi:
                kvs.append((tid - lo, float(bias)))
        rows.append(kvs)
        if kvs:
            any_active = True
            if len(kvs) > max_keys:
                max_keys = len(kvs)
    if not any_active:
        return logits

    pad = W
    ids = torch.full((B, max_keys), pad, dtype=torch.int64)
    vals = torch.zeros((B, max_keys), dtype=torch.float32)
    for i, kvs in enumerate(rows):
        if not kvs:
            continue
        for j, (tid, bias) in enumerate(kvs):
            ids[i, j] = tid
            vals[i, j] = bias
    ids = ids.to(logits.device, non_blocking=True)
    vals = vals.to(logits.device, non_blocking=True)

    # Sum biases into (B, W+1); drop the pad sink.
    delta = torch.zeros(B, W + 1, dtype=logits.dtype, device=logits.device)
    delta.scatter_add_(1, ids, vals.to(logits.dtype))
    delta = delta[:, :W]  # (B, W)

    return logits + delta.unsqueeze(0)  # broadcast across K


def apply_temperature(
    logits: torch.Tensor,  # (K, num_seqs, V) fp32
    requests: Sequence[Request],
) -> torch.Tensor:
    """Scale logits by 1/temperature per request (skip greedy rows).

    Vectorized: one in-place ``logits.div_(temp.unsqueeze(1))`` after
    replacing greedy temperatures with 1.0 to keep their rows
    untouched. Works in-place on a freshly cloned tensor so an
    upstream CUDAGraph output buffer is not modified.
    """
    K, B, _ = logits.shape

    # Gather temperatures and decide if anything needs to change.
    temps = _staging_empty(B, dtype=torch.float32, device=logits.device)
    any_active = False
    for i, req in enumerate(requests):
        sp = req.sampling
        if sp.is_greedy or sp.temperature == 1.0:
            temps[i] = 1.0
        else:
            temps[i] = sp.temperature
            any_active = True
    if not any_active:
        return logits

    out = logits.clone()
    # (K, B, V) / (1, B, 1) — broadcast across K and V, in-place.
    t = temps.to(logits.device, non_blocking=True).view(1, B, 1)
    out.div_(t)
    return out


def top_k_mask(probs: torch.Tensor, k: int) -> torch.Tensor:
    """Keep only the top-k probabilities, set the rest to 0 + renormalize.

    Kept for external consumers (spec_decode rejection sampler etc.).
    """
    if k <= 0 or k >= probs.shape[-1]:
        return probs
    vals, _ = torch.topk(probs, k, dim=-1)
    thresh = vals[..., -1:]
    out = torch.where(probs >= thresh, probs, torch.zeros_like(probs))
    return out / out.sum(dim=-1, keepdim=True).clamp_min(1e-12)


def top_p_mask(probs: torch.Tensor, top_p: float) -> torch.Tensor:
    """Nucleus sampling — keep the smallest set whose cumulative prob >= top_p.

    Kept for external consumers (spec_decode rejection sampler etc.).
    """
    if top_p >= 1.0:
        return probs
    sorted_probs, sorted_idx = torch.sort(probs, descending=True, dim=-1)
    cumprobs = sorted_probs.cumsum(dim=-1)
    keep_sorted = cumprobs - sorted_probs < top_p
    keep = torch.empty_like(keep_sorted)
    keep.scatter_(-1, sorted_idx, keep_sorted)
    out = torch.where(keep, probs, torch.zeros_like(probs))
    return out / out.sum(dim=-1, keepdim=True).clamp_min(1e-12)


def min_p_mask(probs: torch.Tensor, min_p: float, *, inplace: bool = False) -> torch.Tensor:
    """min-p — keep tokens with prob >= min_p * max(prob).

    External callers preserve their input. The verify sampler may reuse its
    privately owned probability buffer with ``inplace=True``.
    """
    if min_p <= 0.0:
        return probs
    pmax = probs.max(dim=-1, keepdim=True).values
    threshold = min_p * pmax
    if inplace:
        probs.masked_fill_(~(probs >= threshold), 0.0)
        return probs.div_(probs.sum(dim=-1, keepdim=True).clamp_min(1e-12))
    out = torch.where(probs >= threshold, probs, torch.zeros_like(probs))
    return out / out.sum(dim=-1, keepdim=True).clamp_min(1e-12)
# ---- rank_symmetric.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Rank-symmetric Gumbel-max noise for SPMD stochastic sampling.

Under the SPMD TP loop every rank holds the SAME post-all-reduce logits
and the SAME replicated request state, so the ONLY thing that can break
cross-rank determinism is the random draw. A stateful per-rank
``torch.Generator`` diverges (each rank advances its own offset). This
module replaces it with a counter-based draw keyed on
``(base_seed, position)`` — a value every rank agrees on without a
broadcast — so every rank produces byte-identical noise and therefore
byte-identical samples.

The draw goes through a CPU ``torch.Generator`` (same device-independent
contract as ``spec_decode.rejection_sampler._seeded_uniforms``): the
uniforms are bit-identical on CPU and CUDA, which is what makes the CPU
gloo parity test a faithful proxy for the GPU TP path.
"""

from __future__ import annotations

from collections.abc import Sequence

import torch

# SplitMix64 finalizer constants — a counter-based mix so consecutive
# positions / seeds decorrelate. Reused from the loader signature mixer
# (``loader.flat_loader``) so the project has ONE such constant.
_GOLDEN_GAMMA = 0x9E3779B97F4A7C15
_MIX_A = 0xBF58476D1CE4E5B9
_MIX_B = 0x94D049BB133111EB
_U64 = 0xFFFFFFFFFFFFFFFF
_S63 = 0x7FFFFFFFFFFFFFFF


def _splitmix64(x: int) -> int:
    """One SplitMix64 step — a counter-based scramble of a 64-bit input."""
    x = (x + _GOLDEN_GAMMA) & _U64
    x = ((x ^ (x >> 30)) * _MIX_A) & _U64
    x = ((x ^ (x >> 27)) * _MIX_B) & _U64
    return (x ^ (x >> 31)) & _U64


def request_base_seed(req: object) -> int:
    """The base seed one request's stochastic draws are keyed on.

    The request's explicit ``sampling.seed`` when set, else its
    ``request_id``: stable for the request's whole life, distinct across
    requests, and identical on every rank (the id is replicated).
    """
    seed = getattr(req.sampling, "seed", None)  # type: ignore[attr-defined]
    if seed is not None:
        return int(seed)
    rid = getattr(req, "request_id", None)
    return int(rid) if rid is not None else id(req)


def request_position(req: object) -> int:
    """The committed token count a request's next draw is keyed on."""
    total = getattr(req, "total_length", None)
    if total is not None:
        return int(total)
    return len(getattr(req, "prompt_token_ids", ())) + len(getattr(req, "output_token_ids", ()))


def request_row_seeds(requests: Sequence[object], k: int = 1) -> list[int]:
    """Per-row Philox seeds for a ``(k, B)`` slate, flat row ``j * B + b``.

    Row ``b`` at slot ``j`` draws with
    ``derive_row_seed(request_base_seed(req_b), request_position(req_b) + j)``
    — the same function of the same ``(seed, position)`` the SPMD driver
    derives for its workers, so a single-process server and a
    tensor-parallel one sample the same request identically.
    """
    bases = [request_base_seed(r) for r in requests]
    positions = [request_position(r) for r in requests]
    return [
        derive_row_seed(bs, pos + j)
        for j in range(k)
        for bs, pos in zip(bases, positions, strict=True)
    ]


def derive_row_seed(base_seed: int, position: int) -> int:
    """Derive a positive 63-bit seed from ``(base_seed, position)``.

    Counter-based: distinct ``(base_seed, position)`` pairs scramble to
    decorrelated seeds. Rank-independent — every rank passes the same
    ``base_seed`` (the request seed) and ``position`` (the request's
    committed token count), so every rank derives the same seed.
    """
    mixed = _splitmix64((int(base_seed) & _U64) ^ _splitmix64(int(position) & _U64))
    return mixed & _S63


def gumbel_exp_noise(
    base_seeds: list[int],
    positions: list[int],
    vocab_size: int,
    *,
    device: torch.device | str = "cpu",
    dtype: torch.dtype = torch.float32,
) -> torch.Tensor:
    """Build the ``(B, V)`` Exp(1) Gumbel-max noise, one row per request.

    Each row ``i`` is drawn from a CPU generator seeded with
    ``derive_row_seed(base_seeds[i], positions[i])`` — so the noise is a
    pure function of the rank-agreed ``(seed, position)`` and is identical
    on every rank. ``device`` only governs where the returned tensor
    lands; the draw itself is always on a CPU generator (device-
    independent values), matching ``_seeded_uniforms``.

    The noise is ``Exp(1)`` (the ``probs / Exp(1)`` Gumbel-max trick the
    sampler uses), clamped strictly positive so the downstream divide is
    finite.
    """
    if len(base_seeds) != len(positions):
        raise ValueError(f"gumbel_exp_noise: {len(base_seeds)} seeds != {len(positions)} positions")
    rows = []
    for base, pos in zip(base_seeds, positions, strict=True):
        g = torch.Generator(device="cpu")
        g.manual_seed(derive_row_seed(base, pos))
        row = torch.empty(vocab_size, dtype=dtype).exponential_(1, generator=g)
        rows.append(row.clamp_min_(1e-10))
    noise = torch.stack(rows, dim=0)  # (B, V)
    dev = torch.device(device) if not isinstance(device, torch.device) else device
    if noise.device != dev:
        if dev.type == "cuda":
            # Pinned staging + non_blocking, not a pageable ``.to(cuda)`` —
            # the pageable form is a synchronous H2D that blocks the host
            # behind the already-enqueued forward (#618 bug class; this is
            # the SPMD full-noise rollback path). Byte-identical values; the
            # caching host allocator defers the pinned block's reuse until
            # the copy event completes.
            noise = noise.pin_memory().to(dev, non_blocking=True)
        else:
            noise = noise.to(dev)
    return noise
# ---- sampler.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Per-request sampling on ``(K, num_seqs, vocab_size)`` logits.

The pipeline operates on a 3-D logits tensor; ``K=1`` in the non-MTP
path. The leading dim costs zero at runtime and keeps the surface
MTP-ready (no ``if K > 1:`` branch anywhere).

Per-request sampling chain:
  1. Repetition / frequency / presence penalties (over the output-id
     history).
  2. ``logit_bias`` — raw additive shifts on specific token IDs.
  3. Structured-decoding processors (xgrammar) — mask disallowed
     tokens to ``-inf``.
  4. Greedy short-circuit (T=0).
  5. Temperature scale.
  6. top_k → top_p → min_p mask.
  7. Gumbel-max sample (categorical via the ``-log(-log(u))`` trick).

Vectorization. The chain runs as a small set of batched tensor ops over
the full ``(K, B, V)`` (or flattened ``(K*B, V)``) tensor — no Python
loop over requests in the steady state. The greedy fast path skips
penalty / bias / temperature / sampling entirely when every row in the
batch is greedy and has identity-valued knobs (``temperature <= 0``,
no penalties, no bias) — in that case sampling is one ``argmax`` over
the whole tensor and a single ``.cpu().tolist()`` host sync.

Module layout. The per-step metadata (:class:`_SamplingMetadata` and its
build/key helpers) lives in :mod:`arbi_serve.sampler.sampling_metadata`;
the batched logit masks and the sampler-private noise generator live in
:mod:`arbi_serve.sampler.sampling_masks`. Both are re-imported below so
every name remains importable as ``arbi_serve.sampler.sampler.<name>``.
``_fused_sample`` and ``_USE_COUNTER_GUMBEL_FILTERED`` deliberately stay
in THIS module: tests replace/mutate them as module attributes and
:class:`Sampler` must observe those mutations at call time.
"""

from __future__ import annotations

from collections.abc import Sequence

import torch

from arbi_serve.engine.request import Request
from arbi_serve.flag_truth import FiringWindow as _FW
from arbi_serve.flag_truth import path_counter as _pc
from arbi_serve.runtime.pinned_h2d import to_device_async
from arbi_serve.sampler.penalty_accumulator import reset_penalty_accumulators
from arbi_serve.sampler.penalty_history import reset_penalty_history_caches
from arbi_serve.sampler.processors import (
    LogitsProcessor,
    apply_logit_bias,
    apply_penalties,
    apply_temperature,
)
from arbi_serve.sampler.rank_symmetric import request_row_seeds
from arbi_serve.sampler.sampling_masks import (
    _counter_gumbel_seeds,
    _fused_topk_topp_args,
    _fused_topk_topp_triton,
    _get_noise_generator,
    _vectorized_min_p_mask,
    _vectorized_top_k_mask,
    _vectorized_top_p_mask,
)
from arbi_serve.sampler.sampling_metadata import (
    _build_sampling_metadata,
    _SamplingMetadata,
    _slate_sampling_key,
)
from arbi_serve.sampler.watermark import WatermarkStore

# Same epsilon vLLM uses for "treat as greedy" tie-break in the
# where-merge of greedy / stochastic samples.
_SAMPLING_EPS = 1e-5


def _env_flag(name: str, default: bool = True) -> bool:
    """Read a boolean env flag (``0``/``false``/``no``/``off`` disable it)."""
    import os

    val = os.environ.get(name)
    if val is None:
        return default
    return val.strip().lower() not in ("0", "false", "no", "off")


# Route the FILTERED stochastic path (top_k / top_p / min_p) through the
# same single-pass counter-based Gumbel-max kernel the no-filter default
# uses: mask in logit space (identical mask kernels as today), then draw
# with on-the-fly Philox noise — no materialized ``(K*B, V)`` Exp(1)
# tensor. On by default; ``ARBI_SAMPLER_FILTERED_GUMBEL=0`` falls back to
# the legacy noise-materialize chain (A/B + rollback). The flag governs
# only the self-seeded path selection — when a caller supplies explicit
# ``row_seeds`` (SPMD), the counter kernel is always honored so the
# cross-rank determinism contract can never be toggled off mid-fleet by a
# stray env var on one rank. Rank-consistent rollback is the driver's
# job: ``DistributedEngineDriver`` consults this flag to decide whether
# to send ``row_seeds`` or legacy full ``noise`` in the first place.
_USE_COUNTER_GUMBEL_FILTERED = _env_flag("ARBI_SAMPLER_FILTERED_GUMBEL", default=True)


def _fused_sample(
    logits: torch.Tensor,  # (K, B, V) fp32
    sm: _SamplingMetadata,
    noise: torch.Tensor | None = None,  # (K*B, V) Exp(1), optional
    row_seeds: torch.Tensor | None = None,  # (K*B,) int64 Philox seeds, optional
) -> torch.Tensor:
    """Single batched stochastic sample over (K*B, V) logits.

    Steps:

        1. Top-k + Top-p in **one fused Triton kernel launch** (vLLM's
           Qrita pivot algorithm) — replaces the two-launch
           ``_vectorized_top_k_mask`` + ``_vectorized_top_p_mask``
           chain when fp32 + CUDA.
        2. Apply per-row min-p mask on softmax-probs (logit-space
           threshold; one batched ``masked_fill_``).
        3. Softmax → Gumbel-max via the ``probs / Exp(1)`` trick → argmax.

    Returns sampled token ids of shape ``(K, B)`` int64. Greedy rows
    are NOT excluded here; the caller merges them in via
    ``torch.where`` against a parallel argmax pass (vLLM pattern).

    Numerical contract. Greedy rows are short-circuited above the
    fused path entirely — temperature=0 routes through the
    ``argmax``-only path that never enters this function. The
    resulting token-id distribution is parity-tested via KL-divergence
    in ``tests/test_sampler_triton_parity_gpu``.

    Cudagraph-safety. The Gumbel-max noise draw uses a sampler-private
    ``torch.Generator`` (see :func:`_get_noise_generator`) instead of
    the default CUDA generator. Default-generator ``exponential_``
    raises ``RuntimeError: Offset increment outside graph capture
    encountered unexpectedly`` on every stochastic completion when
    cudagraphs are ON, because the engine's captured forwards register
    the default generator with their CUDAGraphs and the post-capture
    main-stream RNG call trips a state-mismatch check in
    ``CUDAGeneratorState::increase``.
    """
    K, B, V = logits.shape
    flat = logits.reshape(K * B, V)

    # ----- No-filter single-pass counter-based Gumbel-max fast path -----
    # The server-default decode shape (temperature>0, top_p=1, top_k unset,
    # min_p=0) is a plain categorical draw from ``softmax(logits)``. The
    # single-pass Gumbel-max kernel draws it as ``argmax_v(logit_v + g_v)``
    # with the per-element Gumbel noise ``g_v = -log(-log(u_v))`` generated
    # ON THE FLY from a counter-based Philox RNG keyed on
    # ``(row_seed, vocab_index)`` — ONE pass over V, NO materialized noise
    # tensor, NO separate softmax, NO 3-pass argmax kernel. Measured ~28 µs
    # at V=248320 B=1 on a 4090 vs ~105 µs for ``torch.multinomial(softmax)``
    # and ~154 µs for the vendored full-Gumbel kernel.
    #
    # Cross-rank (SPMD/TP) determinism: when ``row_seeds`` is supplied the
    # noise is a pure function of the rank-agreed ``(seed, position)``-
    # derived seed, so every rank draws the byte-identical token with NO
    # noise tensor exchanged — see
    # :mod:`arbi_serve.sampler.gumbel_argmax_triton`. When ``row_seeds`` is
    # None and no SPMD ``noise`` pins the draw (the c=1 single-process
    # path) we self-generate a per-step seed from the sampler-private
    # generator. If a caller still supplies the legacy full ``noise`` for a
    # no-filter SPMD draw (``row_seeds`` None, ``noise`` given), we fall
    # through to the exact noise-consuming Gumbel tail below so that
    # contract is never silently broken.
    nofilter = flat.is_cuda and not (sm.any_top_k or sm.any_top_p or sm.any_min_p)
    if nofilter and (row_seeds is not None or noise is None):
        from arbi_serve.sampler.gumbel_argmax_triton import gumbel_argmax_from_seeds

        seeds = _counter_gumbel_seeds(K * B, flat.device, row_seeds)
        return gumbel_argmax_from_seeds(flat, seeds).view(K, B)

    # ----- FILTERED single-pass counter-based Gumbel-max fast path -----
    # top_k / top_p / min_p rows: apply the EXISTING sort-free masks in
    # logit space (the same Qrita top-k/top-p Triton kernel + logit-space
    # min-p threshold the legacy chain uses — masked-out entries become
    # ``-inf``), then sample the masked logits with the counter-based
    # Gumbel-max kernel. ``argmax_v(logit_v + g_v)`` over masked logits is
    # an EXACT categorical draw over the renormalized softmax of the
    # SURVIVING set — a masked row scores ``-inf + g_v = -inf`` and can
    # never win — so the filtered distribution and support are unchanged
    # from today's chain. What changes is the tail: no materialized
    # ``(K*B, V)`` Exp(1) noise tensor and no full-vocab Gumbel/argmax
    # passes over it (measured 487 → 356 µs/step at B=1 and 517 → 407 µs
    # at B=8, V=248320, top_p=0.9/top_k=50 on a 4090 —
    # ``scripts/bench_sampler_filtered_microbench.py``; the residual is
    # dominated by the Qrita mask itself, matching the FlashInfer-port
    # bake-off's ~351 µs floor).
    #
    # Cross-rank (SPMD/TP) determinism: the masks are deterministic
    # functions of the post-all-reduce (rank-identical) logits and the
    # per-request knobs, and ``row_seeds`` is rank-agreed — so every rank
    # masks identically and draws the byte-identical token, with NO noise
    # tensor exchanged. Explicit ``row_seeds`` always takes this path
    # (the env flag cannot break the determinism contract); the
    # self-seeded c=1 selection honors the rollback flag. A legacy caller
    # supplying full ``noise`` (``row_seeds`` None) still falls through
    # to the exact noise-consuming chain below, unchanged.
    filtered = flat.is_cuda and (sm.any_top_k or sm.any_top_p or sm.any_min_p)
    if filtered and (row_seeds is not None or (noise is None and _USE_COUNTER_GUMBEL_FILTERED)):
        from arbi_serve.sampler.gumbel_argmax_triton import gumbel_argmax_from_seeds

        seeds = _counter_gumbel_seeds(K * B, flat.device, row_seeds)
        # The mask kernels mutate ``flat`` in-place — same aliasing rules
        # as the legacy chain below: ``contiguous()`` on a strided view
        # already copies; a mixed greedy/stochastic batch re-reads ``x``
        # post-mask (greedy argmax merge) so clone; otherwise
        # ``_sample_to_device`` already cloned ``x`` when it aliased the
        # caller's logits, so the in-place mask is safe.
        if not flat.is_contiguous():
            flat = flat.contiguous()
        elif sm.any_greedy:
            flat = flat.clone()
        if sm.any_top_k or sm.any_top_p:
            flat = _fused_topk_topp_triton(flat, sm, K, B)
        if sm.any_min_p:
            flat = _vectorized_min_p_mask(flat, sm.min_p, K, B, any_min_p=sm.any_min_p)
        return gumbel_argmax_from_seeds(flat, seeds).view(K, B)

    # The fused Triton kernel reads the logits (fp32 OR bf16/fp16) and
    # mutates them in-place (the top-k/top-p mask write-back). It upcasts
    # bf16/fp16 to fp32 IN-REGISTER per tile — keeping the softmax max/sum
    # accumulators fp32 — so we DON'T materialize a full fp32 (K*B, V)
    # tensor on the host anymore. Reading bf16 directly halves the HBM
    # read on every one of the kernel's passes over V (the one figure on
    # record for it is ~26% faster at B=32 over a V=151936 vocabulary —
    # neither the served batch nor the served vocabulary, so it needs
    # re-taking before it is quoted for this deployment; bit-exact vs the
    # fp32-input path because
    # a bf16 value widens to fp32 exactly and the masked write-back
    # round-trips bf16 losslessly).
    use_triton = flat.is_cuda and (sm.any_top_k or sm.any_top_p)

    # The single-launch fused kernel (top-k/top-p mask + Gumbel-max tail in
    # ONE launch) fires only when there is a real top-k/top-p mask AND no
    # min-p (min-p needs an intermediate mask on the kernel's output).
    fused_mask_sample = use_triton and not sm.any_min_p

    # ----- Masked multinomial fast path predicate -----
    # The pure no-filter default (no top-k/top-p/min-p) is already handled
    # by the single-pass counter-based Gumbel-max kernel above and returned.
    # This predicate now covers only the MASKED-but-not-single-launch-fused
    # cases with no SPMD noise: a min-p mask, or a non-fused top-k/top-p
    # mask. There we sample the (masked) softmax with ``torch.multinomial``
    # — ONE uniform per row — instead of drawing a full ``(K*B, V)`` Exp(1)
    # Gumbel tensor and running the 3-pass argmax kernel over the whole
    # vocab. ``multinomial`` samples the masked distribution correctly
    # (softmax maps the ``-inf`` mask to zero probability). The Gumbel-max
    # tail is preserved verbatim whenever ``noise`` is supplied (SPMD rank
    # symmetry) — the fast path never triggers there.
    fast_multinomial = flat.is_cuda and noise is None and not fused_mask_sample

    if use_triton:
        # The kernel mutates ``flat`` in-place. ``flat`` is a reshape view
        # of ``x``; the mixed-batch merge below reads ``x``'s argmax AFTER
        # the mask, and ``_sample_to_device`` only clones ``x`` when it
        # aliases the caller's ``logits`` — so we must clone here to keep
        # ``x`` intact for the greedy argmax. A bf16 clone is HALF the
        # bytes the old ``.to(fp32)`` copy cost.
        if not flat.is_contiguous():
            flat = flat.contiguous()
        elif sm.any_greedy:
            # Mixed greedy/stochastic batch: ``x`` is read again post-mask.
            flat = flat.clone()
        else:
            # All-stochastic: ``x`` already cloned upstream when it aliased
            # ``logits`` (see ``_sample_to_device``); in-place mask is safe.
            pass

    # Exp(1) Gumbel-max noise ``q``. Materialized BEFORE the mask so the
    # fused kernel can consume it; the draw is independent of the masked
    # logits, so the order is irrelevant to the result. Shape (K*B, V),
    # fp32 (the softmax/Gumbel accumulator dtype). The fused Triton tail
    # divides ``probs / q`` exactly as the Python chain below does. The
    # multinomial fast path consumes no full-V noise, so skip the draw
    # entirely there (this full-V Exp(1) draw is itself a chunk of the
    # per-step sampling cost the fast path removes).
    q = None
    if not fast_multinomial:
        if noise is not None:
            # Rank-symmetric SPMD path: the caller supplies the Exp(1) noise
            # derived from each row's (seed, position) so every rank draws the
            # IDENTICAL Gumbel — see :mod:`arbi_serve.sampler.rank_symmetric`.
            if tuple(noise.shape) != (K * B, V):
                raise RuntimeError(
                    f"_fused_sample: noise shape {tuple(noise.shape)} != logits shape {(K * B, V)}"
                )
            q = noise.to(device=flat.device, dtype=torch.float32)
        elif flat.is_cuda:
            # ``generator=`` arg routes through a sampler-private generator
            # whose ``capturing_`` state is never set by the engine's
            # CUDAGraphs — see :func:`_get_noise_generator` for the full
            # rationale and the ``Offset increment outside graph capture``
            # bug it fixes.
            gen = _get_noise_generator(flat.device)
            q = (
                torch.empty((K * B, V), device=flat.device, dtype=torch.float32)
                .exponential_(1, generator=gen)
                .clamp_min_(1e-10)
            )
        else:
            # CPU path — no cudagraphs in scope, no need for the private
            # generator; preserves the legacy default-generator behaviour
            # for the (vanishingly small) CPU sampler test paths.
            q = (
                torch.empty((K * B, V), device=flat.device, dtype=torch.float32)
                .exponential_(1)
                .clamp_min_(1e-10)
            )

    # FUSED FAST PATH: one Triton launch folds top-k/top-p mask +
    # softmax + Gumbel-max + argmax. Only the no-min-p case (min-p needs
    # an intermediate mask on the kernel's output, see below). The result
    # is op-for-op identical to the Python chain (verified exact in
    # ``tests/test_sampler_fused_tail``).
    if fused_mask_sample:
        from arbi_serve.sampler.topk_topp_triton import sample_top_k_top_p_triton

        k_full, p_full = _fused_topk_topp_args(flat, sm, K, B)
        if not q.is_contiguous():
            q = q.contiguous()
        sampled = sample_top_k_top_p_triton(flat, k_full, p_full, q)
        return sampled.view(K, B)

    # NON-FUSED PATH: top-k/top-p mask (triton or PyTorch), then min-p,
    # then softmax → Gumbel-max → argmax in PyTorch.
    if use_triton:
        flat = _fused_topk_topp_triton(flat, sm, K, B)
    else:
        if sm.any_top_k:
            flat = _vectorized_top_k_mask(flat, sm.top_k, K, B)
        if sm.any_top_p:
            flat = _vectorized_top_p_mask(flat, sm.top_p, K, B)

    if sm.any_min_p:
        flat = _vectorized_min_p_mask(flat, sm.min_p, K, B, any_min_p=sm.any_min_p)

    if fast_multinomial:
        # MULTINOMIAL FAST PATH (no SPMD noise, no single-launch fused path).
        # Sample the (masked) softmax directly with one uniform per row. Same
        # distribution as the Gumbel-max tail — Gumbel-max on ``softmax(x)``
        # draws exactly ``categorical(softmax(x))`` — but skips the full-V
        # Exp(1) draw and the 3-pass argmax kernel over the whole vocab. The
        # softmax accumulates in fp32 (``dtype=float32``) so a bf16-input row
        # is sampled at the SAME precision the Gumbel kernel used (it upcasts
        # bf16→fp32 in-register). The draw routes through the sampler-private
        # generator for cudagraph safety + determinism (see
        # :func:`_get_noise_generator`).
        probs = flat.softmax(dim=-1, dtype=torch.float32)
        gen = _get_noise_generator(flat.device)
        return torch.multinomial(probs, 1, generator=gen).view(K, B)

    if flat.is_cuda:
        # Fold the softmax/Gumbel/argmax tail into one Triton launch over
        # the already-masked logits (k=None, p=None → sample-only). Reached
        # only on the SPMD noise-supplied path now (the fast path above owns
        # the noise=None case). Exact, same caller-supplied noise.
        from arbi_serve.sampler.topk_topp_triton import sample_top_k_top_p_triton

        if not q.is_contiguous():
            q = q.contiguous()
        sampled = sample_top_k_top_p_triton(flat, None, None, q)
        return sampled.view(K, B)

    # CPU fallback (sampler unit tests): Gumbel-max categorical sample —
    # softmax → probs / Exp(1) → argmax.
    probs = flat.softmax(dim=-1)
    sampled = (probs / q).argmax(dim=-1)  # (K*B,) int64
    return sampled.view(K, B)


#: Keyed watermark draws actually served, per SAMPLING PATH. Two counters and
#: not one, because "watermarking is on" is a per-path property: a recipe that
#: routes its tokens through a path nobody keyed marks nothing while every
#: status surface reports the feature on. Fired where the keyed seeds are
#: BUILT, so a zero means that path served no keyed draw, not that it was
#: configured off.
_WM_KEYED_DRAW_K1 = _pc("watermark_keyed_draw_k1", _FW.SERVE)


class Sampler:
    """Stateless sampling coordinator.

    Operates on ``(K, num_seqs, vocab_size)`` logits. Non-MTP callers
    pass ``K=1``; :class:`MtpDriver` passes ``K = draft_len + 1``
    without changing any signature.

    External logits processors (e.g. :class:`XGrammarLogitsProcessor`)
    plug in via :meth:`set_logits_processors`. They run after penalty
    / bias / temperature and before greedy / top-k masking, so the
    mask they apply (``-inf`` on disallowed tokens) survives every
    downstream masking step.
    """

    def __init__(self) -> None:
        self._processors: list[LogitsProcessor] = []
        # The penalty path caches each request's token history on the
        # device, keyed by ``request_id``. Ids are unique only WITHIN an
        # engine instance (``engine_init`` seeds ``itertools.count(1)``),
        # and one Sampler is built per engine (``build_phases_load``), so
        # dropping the caches here is what makes id reuse across a model
        # swap / engine rebuild unobservable. The additive accumulator is
        # keyed by request_id the same way and is dropped for the same
        # reason — its rows would otherwise carry the previous engine's
        # penalties into a reused id.
        reset_penalty_history_caches()
        reset_penalty_accumulators()
        # This member's keyed-watermark caches and their pool hook. Owned
        # here, not process-wide: ``eng.sampler`` is model-tied state, so a
        # swap repoints readers to the woken member's own rings, and building
        # another member never drops this one's.
        self.watermark_store = WatermarkStore()
        # Per-step sampling-metadata cache. In steady decode the active
        # slate's per-request sampling params are constant across steps,
        # so the (B,) knob tensors + CPU predicates can be reused instead
        # of rebuilt + re-uploaded every step. The cache is a PURE host
        # optimization: a HIT returns the exact same ``_SamplingMetadata``
        # a fresh build would produce (see ``_slate_sampling_key`` for the
        # invalidation contract), so it can never change which token is
        # sampled. Invalidates on any slate-membership change, reorder,
        # or param change. Engine run loop is single-threaded per device,
        # so no lock is needed.
        self._sm_cache_key: tuple | None = None
        self._sm_cache: _SamplingMetadata | None = None

    def _sampling_metadata(
        self,
        requests: Sequence[Request],
        device: torch.device,
        vocab_size: int,
    ) -> _SamplingMetadata:
        """Return ``_SamplingMetadata`` for the slate, reusing the cached
        tensors when the slate's sampling key is unchanged.

        Cache HIT requires the slate membership (request ids, in slate
        order), the params of every row, the device, AND the vocab size
        to all match the previous build. On any mismatch we rebuild and
        refresh the cache. Bit-exact with calling
        :func:`_build_sampling_metadata` directly: the returned tensors
        are identical-valued (a HIT returns the *same* tensor objects the
        prior build produced; downstream consumers never mutate the
        metadata tensors in-place — they only read them and broadcast /
        compare, mutating their own logits copies).
        """
        key = _slate_sampling_key(requests, device, vocab_size)
        cached = self._sm_cache
        if cached is not None and self._sm_cache_key == key:
            return cached
        sm = _build_sampling_metadata(requests, device, vocab_size)
        self._sm_cache_key = key
        self._sm_cache = sm
        return sm

    def clear_slate_metadata_cache(self) -> int:
        """Drop the cached slate metadata. Returns 1 when there was one.

        The tensors above are built with the forward arena routing, so the
        cache holds a block in a pool whose physical can only be returned by
        destroying it (:func:`~arbi_serve.engine.inprocess_capture.
        release_idle_forward_arena`). This is the seam that gives that block
        up, and it is sound there for a reason the cache key states: the key
        carries the slate's request ids, and the release runs only with no
        running and no waiting row, so no later slate can hit this entry.
        """
        had = self._sm_cache is not None
        self._sm_cache = None
        self._sm_cache_key = None
        return int(had)

    def set_logits_processors(self, procs: Sequence[LogitsProcessor]) -> None:
        """Replace the active processor chain. Engine-owned, hot-swap safe."""
        self._processors = list(procs)

    @property
    def logits_processors(self) -> tuple[LogitsProcessor, ...]:
        """The active chain, in the order :meth:`sample` runs it.

        The speculative verify draw does not go through :meth:`sample`, so it
        reads the chain here and runs each member's
        :meth:`~arbi_serve.sampler.processors.LogitsProcessor.apply_to_verify_slate`
        — the same members, in the same order. Every constraint a request is
        granted on the ``K=1`` draw therefore reaches its speculative draw
        too, or is refused there.
        """
        return tuple(self._processors)

    @staticmethod
    def _is_trivial_greedy(req: Request) -> bool:
        """True ⇒ request needs nothing but ``argmax``.

        Cheap CPU-side predicate: temperature == 0 (greedy), no
        ``top_k`` / ``top_p`` / ``min_p`` constraint, no penalty, no
        ``logit_bias``, no structured-output (``response_format`` /
        grammar). When this returns True for the only row in a batch
        and the sampler has no external processors attached, the
        whole sampling chain collapses to ``logits.argmax(-1)`` —
        which lets the B=1 greedy path skip the ``_SamplingMetadata``
        build entirely.
        """
        sp = req.sampling
        if not sp.is_greedy:
            return False
        # top_k = -1 (or 0) ⇒ disabled. Anything else means a mask op.
        if sp.top_k is not None and sp.top_k > 0:
            return False
        if sp.top_p < 1.0:
            return False
        if sp.min_p > 0.0:
            return False
        if (
            sp.repetition_penalty != 1.0
            or sp.frequency_penalty != 0.0
            or sp.presence_penalty != 0.0
        ):
            return False
        if sp.logit_bias:
            return False
        return sp.response_format is None or sp.response_format.type == "text"

    def _sample_to_device(
        self,
        logits: torch.Tensor,  # (K, num_seqs, V) bf16/fp32
        requests: Sequence[Request],
        noise: torch.Tensor | None = None,  # (K*B, V) Exp(1), SPMD only
        row_seeds: torch.Tensor | None = None,  # (K*B,) int64 Philox seeds, SPMD only
    ) -> torch.Tensor:
        """Run the full sampling chain and return ``(K, B)`` int64 on device.

        ``noise`` (SPMD rank-symmetric path): when given, the stochastic
        Gumbel draw uses this caller-supplied Exp(1) tensor instead of the
        sampler's own generator, so every rank draws identical Gumbels.
        Greedy rows ignore it. Passing ``noise`` keeps the SAME chain — it
        is not a separate code path.

        The pure-GPU kernel chain — no host sync. Keeping the host sync
        out of this method lets :meth:`sample_step_keep_gpu` reuse the
        chain without any host work, so the engine task can hand the
        GPU tensor straight to the next step's persistent ``input_ids``
        buffer via D2D.

        Bit-identical contract with :meth:`sample`: every fast-path /
        branch returns the exact same ``(K, B)`` int64 GPU tensor that
        :meth:`sample` produces before its host sync.
        """
        if logits.dim() != 3:
            raise RuntimeError(
                f"Sampler.sample: expected 3-D (K, num_seqs, V) "
                f"logits, got shape {tuple(logits.shape)}."
            )
        K, B, V = logits.shape
        if len(requests) != B:
            raise RuntimeError(f"Sampler.sample: logits has B={B} but {len(requests)} requests.")

        # ----- Trivial single-request greedy fast-path -----
        # The dominant decode-step shape in low-QPS production: B=1,
        # greedy, no penalties / bias / advanced sampling / structured
        # output. Skipping ``_build_sampling_metadata`` here saves the
        # five (B,) host tensor allocations + H2D copies + the gather
        # loop over requests — ~12 µs at B=1 on RTX 4090.
        # Bit-identical to the legacy greedy path: argmax only.
        if (
            B == 1
            and len(requests) == 1
            and not self._processors
            and self._is_trivial_greedy(requests[0])
        ):
            return logits.argmax(dim=-1)  # (K, 1)

        sm = self._sampling_metadata(requests, logits.device, V)

        # ----- Greedy super-fast path -----
        # Skip fp32 cast, penalties, bias, external procs, temperature,
        # masks. Only requirement: every row is greedy AND no processor
        # in the chain might rewrite logits (penalty / bias / xgrammar
        # are all argmax-affecting). External processors (xgrammar) can
        # mask tokens to -inf and that DOES affect argmax, so we still
        # run them when present.
        if (
            sm.all_greedy
            and not sm.has_penalties
            and not sm.has_logit_bias
            and not self._processors
        ):
            # argmax is stable in bf16 — no fp32 cast needed.
            return logits.argmax(dim=-1)  # (K, B)

        # ----- Full chain -----
        # Run the chain in the input dtype (typically bf16). Softmax in
        # PyTorch already auto-promotes its accumulator internally, and
        # explicit fp32 promotion here was a vocab*bf16 = ~600 KB D2D
        # copy at vocab=152k that didn't add precision (apply_temperature
        # downcasts its fp32 temp tensor in-place, apply_logit_bias casts
        # delta to logits.dtype, apply_penalties is dtype-preserving).
        # The argmax fast-path below is bit-identical to the legacy bf16
        # greedy super-fast path (already running in bf16 above).
        # In the stochastic path, bf16 sampling may shift the lowest few
        # bits of the Gumbel sample (probs / Exp(1)), but does NOT change
        # argmax — softmax+sort are auto-promoted in PyTorch.
        x = logits

        if sm.has_penalties:
            x = apply_penalties(x, requests, sm)
        if sm.has_logit_bias:
            x = apply_logit_bias(x, requests)
        # External processors (xgrammar, etc.) apply BEFORE temperature
        # so their -inf mask cannot be diluted by a low temperature.
        for proc in self._processors:
            x = proc(x, requests)
        x = apply_temperature(x, requests)

        # If after the chain everything is greedy, just argmax — no
        # need to draw Gumbels or do top-k/p/min-p work.
        if sm.all_greedy:
            return x.argmax(dim=-1)  # (K, B)

        # ----- Fused stochastic kernel -----
        # Single batched pass over (K*B, V): top-k + top-p + min-p +
        # softmax + Gumbel-max sample. Mixed-batch greedy rows get
        # merged in below.
        #
        # IMPORTANT: x may alias `logits` (penalty/bias may have
        # short-circuited and returned the same tensor); the fused
        # path masks logits in-place via masked_fill_, so clone first
        # to keep the caller's tensor intact.
        if x.data_ptr() == logits.data_ptr():
            x = x.clone()

        # ----- Request-keyed row seeds -----
        # A row's stochastic draw is keyed on its request's ``(seed or
        # request_id, committed position)``, the same derivation the SPMD
        # driver ships as ``row_seeds``. A single-process server derives
        # them here, so an explicit ``sampling.seed`` reproduces the same
        # sample at the same position on any topology, and two requests
        # without one stay decorrelated through their ids. The legacy
        # full-noise payload (``noise`` given) carries its own draw.
        if row_seeds is None and noise is None:
            row_seeds = self._request_row_seeds(requests, K, x.device)

        # ----- Keyed-noise watermark (ARBI_WATERMARK_KEY) -----
        # Replace the stochastic draw's seed source with
        # ``PRF(key, last-H sampled tokens)`` — same counter-Gumbel
        # kernels, same per-token distribution, keyed randomness (see
        # :mod:`arbi_serve.sampler.watermark`). The context ring lives on
        # device and is advanced from the merged sample tensor below, so
        # the path stays host-sync-free under async output. Rank-symmetric
        # under SPMD: every rank hashes the same rank-agreed context and
        # the masked-row fallback consumes the rank-agreed ``row_seeds``.
        wm_cache = None
        if x.is_cuda:
            from arbi_serve.sampler.watermark_request import step_watermark_cache

            wm_cache = step_watermark_cache(x.device, requests, self.watermark_store)
        if wm_cache is not None:
            _WM_KEYED_DRAW_K1.fired = 1
            if K != 1:
                raise RuntimeError(
                    "ARBI_WATERMARK_KEY: a K>1 slate reached the K=1 decode "
                    "sampler — MTP draws must route through the keyed "
                    "exact-match verify (rejection_sampler), never here."
                )
            if noise is not None and row_seeds is None:
                raise RuntimeError(
                    "ARBI_WATERMARK_KEY requires the counter-seed sampling "
                    "path; the legacy SPMD full-noise payload has no "
                    "rank-agreed seed for the masked-row fallback."
                )
            base_seeds = _counter_gumbel_seeds(K * B, x.device, row_seeds)
            keyed_seeds = wm_cache.row_seeds(requests, base_seeds)
            # Per-row opt-OUT: a request whose ``sampling.watermark is False``
            # is sampled UNKEYED (the standard rank-agreed counter seed) while
            # its batch-mates stay keyed. The forward pass is shared — only the
            # per-row seed source differs. K==1 here (enforced above), so the
            # (K*B,) seed rows map 1:1 to ``requests``. The keep-mask is
            # ``(cache is not None) and (watermark is not False)``; the cache
            # is non-None on this branch, so only the per-request bit remains.
            from arbi_serve.sampler.watermark import watermark_keep_mask

            keep_list = watermark_keep_mask(requests)
            if not all(keep_list):
                keep = torch.tensor(keep_list, dtype=torch.bool, device=x.device)
                row_seeds = torch.where(keep, keyed_seeds, base_seeds)
            else:
                row_seeds = keyed_seeds

        stoch = _fused_sample(x, sm, noise, row_seeds)  # (K, B) int64

        # In a mixed batch, greedy rows take the ORIGINAL logits'
        # argmax (penalties / bias / xgrammar mask still apply, so
        # use `x` post-chain; temperature is identity for greedy
        # rows by construction in _build_sampling_metadata).
        #
        # Branch on the HOST-side ``any_greedy`` bool, not
        # ``sm.is_greedy.any()`` — the latter is a device tensor reduction
        # that forces a per-step blocking D2H sync, stalling the host from
        # launching the next step. ``any_greedy`` is derived from the same
        # host-side SamplingParams that built ``is_greedy`` so it is exactly
        # ``bool(sm.is_greedy.any())`` with no GPU round-trip.
        if not sm.any_greedy:
            out = stoch
        else:
            greedy_samples = x.argmax(dim=-1)  # (K, B)
            # Broadcast (B,) is_greedy across K.
            is_g_kb = sm.is_greedy.unsqueeze(0).expand(K, B)
            out = torch.where(is_g_kb, greedy_samples, stoch)
        if wm_cache is not None:
            # D2D ring update from the merged tokens — every row's context
            # window stays current without waiting for the host commit.
            wm_cache.advance(requests, out[0])
        return out

    @staticmethod
    def _request_row_seeds(
        requests: Sequence[Request], k: int, device: torch.device
    ) -> torch.Tensor:
        """``(k * B,)`` int64 row seeds derived from the requests, staged through the pinned ring."""
        return to_device_async(
            torch.tensor(request_row_seeds(requests, k), dtype=torch.int64), device
        )

    def sample(
        self,
        logits: torch.Tensor,  # (K, num_seqs, V) bf16/fp32
        requests: Sequence[Request],
        noise: torch.Tensor | None = None,  # (K*B, V) Exp(1), SPMD only
        row_seeds: torch.Tensor | None = None,  # (K*B,) int64 Philox seeds, SPMD only
    ) -> list[list[int]]:
        """Sample tokens per (k, request) row.

        Returns a list of length ``num_seqs``; each entry is a list of
        length ``K`` of sampled token IDs. In the non-MTP path
        (``K=1``), the returned inner lists are length-1.

        Hot-path strategy.

        Trivial single-request greedy fast-path: when ``B == 1`` and
        the only request is greedy with no penalties / bias / advanced
        sampling / structured output, sampling collapses to a single
        ``argmax`` and one host sync — and the ``_SamplingMetadata``
        build (five (B,) host-tensor allocations + H2D copies + a
        Python loop over requests) is skipped entirely. This is the
        dominant decode-step shape in low-QPS production.

        Greedy fast path: when every row has ``temperature <= 0`` and
        no penalties / bias / external processors, sampling collapses
        to a single ``argmax(dim=-1)`` over the whole ``(K, B, V)``
        tensor and one ``.cpu().tolist()``. No fp32 cast, no penalty
        scatter, no mask passes — the dominant decode-step shape in
        production.

        Stochastic / mixed path: penalty / bias / temperature / mask
        passes are each ONE batched tensor op over the full
        ``(K, B, V)`` (or flattened ``(K*B, V)``) tensor — no Python
        loop over requests. Greedy rows in a mixed batch are merged in
        via a ``torch.where`` against a parallel argmax pass (vLLM
        pattern); this keeps the stochastic kernels launched once.
        """
        samples = self._sample_to_device(logits, requests, noise, row_seeds)
        K, B = samples.shape
        # ONE host sync. ``samples_cpu[k][i]`` is the sampled token id;
        # transpose into the (B, K) outer-list layout the caller
        # expects.
        samples_cpu = samples.cpu().tolist()
        return [[samples_cpu[k][i] for k in range(K)] for i in range(B)]

    # Convenience wrapper for the engine's non-MTP step (K=1):
    # accepts a 2-D ``(num_seqs, V)`` view and returns one token per
    # request.
    def sample_step(
        self,
        logits: torch.Tensor,  # (num_seqs, V) fp32
        requests: Sequence[Request],
        noise: torch.Tensor | None = None,  # (B, V) Exp(1), SPMD only
        row_seeds: torch.Tensor | None = None,  # (B,) int64 Philox seeds, SPMD only
    ) -> list[int]:
        """Sample one token per request from a 2-D ``(num_seqs, V)`` view.

        The engine's non-MTP step calls this — it adds a leading K=1
        dim, dispatches through :meth:`sample`, and unwraps. ``noise`` is
        the rank-symmetric SPMD Gumbel noise (``(B, V)``, K=1);
        ``row_seeds`` is the cheaper rank-agreed per-row Philox seed for
        the no-filter counter-based Gumbel-max fast path (``(B,)``, K=1).
        """
        if logits.dim() != 2:
            raise RuntimeError(
                f"Sampler.sample_step: expected 2-D (num_seqs, V) "
                f"logits, got shape {tuple(logits.shape)}."
            )
        out = self.sample(logits.unsqueeze(0), requests, noise, row_seeds)
        return [seq[0] for seq in out]

    def sample_step_keep_gpu(
        self,
        logits: torch.Tensor,  # (num_seqs, V) fp32
        requests: Sequence[Request],
    ) -> tuple[torch.Tensor, list[int]]:
        """Sample one token per request and return BOTH GPU + CPU views.

        Returns ``(samples_gpu, sampled_ints)`` where ``samples_gpu`` is a
        ``(B,)`` int64 device tensor (a ``[0]`` slice of the internal
        ``(K=1, B)`` result) and ``sampled_ints`` is the per-request
        Python int list (length B). The GPU tensor lets
        ``ModelRunner._build_batch`` write the next step's
        ``input_ids`` slot via D2D, skipping the int-list →
        ``torch.as_tensor`` → H2D path. The host int list is still
        produced because ``Scheduler.commit`` / ``post_token`` /
        detokenization need real Python ints.

        The single ``.cpu().tolist()`` host sync is the only sync
        point — and it is unavoidable as long as the run loop drives
        detokenization synchronously after each step. The win here is
        the elimination of the H2D round-trip ON THE NEXT STEP's
        batch build.

        No silent fallback: every sampling mode (trivial greedy,
        all-greedy fast path, full stochastic chain) keeps the merged
        result on GPU through :meth:`_sample_to_device` and produces
        a normal ``(K, B)`` int64 tensor here. Logprobs aren't
        produced by this path — callers requesting logprobs go
        through :meth:`sample` which has its own host-copy budget.
        """
        if logits.dim() != 2:
            raise RuntimeError(
                f"Sampler.sample_step_keep_gpu: expected 2-D "
                f"(num_seqs, V) logits, got shape {tuple(logits.shape)}."
            )
        samples = self._sample_to_device(logits.unsqueeze(0), requests)  # (1, B) int64
        # samples_gpu is a (B,) view — same storage as `samples`, no copy.
        samples_gpu = samples[0]
        # Single host sync, returns Python ints for the run loop.
        sampled_ints = samples_gpu.cpu().tolist()
        return samples_gpu, sampled_ints

    def sample_step_keep_gpu_async(
        self,
        logits: torch.Tensor,  # (num_seqs, V) fp32
        requests: Sequence[Request],
    ) -> torch.Tensor:
        """Sample one token per request and return ONLY the GPU tensor.

        Async-output path. Identical sampling to
        :meth:`sample_step_keep_gpu` but issues NO ``.cpu().tolist()`` —
        the host materialization is deferred one engine tick on the
        run-loop side via the dedicated copy stream + event (see
        :mod:`arbi_serve.runtime.async_output`). Returns the ``(B,)``
        int64 device tensor; the caller stamps ``last_sampled_gpu`` from
        it (so the next forward's input is a D2D copy) and issues the
        non-blocking D2H itself.
        """
        if logits.dim() != 2:
            raise RuntimeError(
                f"Sampler.sample_step_keep_gpu_async: expected 2-D "
                f"(num_seqs, V) logits, got shape {tuple(logits.shape)}."
            )
        samples = self._sample_to_device(logits.unsqueeze(0), requests)  # (1, B) int64
        return samples[0]
# ---- sampling_masks.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Batched logit masks + the sampler-private noise generator.

Holds the vectorized top-k / top-p / min-p masks, the fused-Triton mask
helpers, and the per-device cudagraph-safe noise generator +
counter-Gumbel seed resolver. All names are re-exported from
:mod:`arbi_serve.sampler.sampler` so the public import surface (and the
``smod._vectorized_*`` / ``smod._get_noise_generator`` test hooks) are
unchanged.
"""

from __future__ import annotations

import torch

from arbi_serve.sampler.sampling_metadata import _SamplingMetadata


def _vectorized_top_k_mask(
    logits: torch.Tensor,  # (N, V) fp32
    k: torch.Tensor,  # (B,) int64; 0 = disabled. N == K*B
    K: int,
    B: int,
) -> torch.Tensor:
    """Mask all but the top-k entries per row to ``-inf``.

    Single batched ``topk`` over the whole (N, V) tensor at the max
    K active in the batch; rows whose k=0 (or k>=V) are unmasked. The
    mask is applied in-place.
    """
    # Broadcast k from (B,) to (N=K*B,) — one row per (k, b) pair.
    k_full = k.unsqueeze(0).expand(K, B).reshape(-1)  # (N,)
    no_top_k = k_full == 0
    if no_top_k.all():
        return logits

    # Replace 0 with 1 so we can gather without an OOB; we'll mask
    # those rows back to -inf-free below.
    k_eff = torch.where(no_top_k, torch.ones_like(k_full), k_full)
    max_k = int(k_eff.max().item())  # ONE small CPU sync; unavoidable for topk-K.
    # (N, max_k) topk; per-row threshold is the (k_eff[r]-1)'th column.
    topk_vals = torch.topk(logits, max_k, dim=-1).values  # (N, max_k) sorted desc
    idx = (k_eff - 1).unsqueeze(1)  # (N, 1)
    thresh = topk_vals.gather(1, idx)  # (N, 1) — k-th largest
    # Rows with k=0 (disabled): set threshold to -inf so nothing is masked.
    thresh = torch.where(
        no_top_k.unsqueeze(1),
        torch.full_like(thresh, float("-inf")),
        thresh,
    )
    return logits.masked_fill_(logits < thresh, float("-inf"))


def _vectorized_top_p_mask(
    logits: torch.Tensor,  # (N, V) fp32, in-place
    p: torch.Tensor,  # (B,) fp32; 1.0 = disabled
    K: int,
    B: int,
) -> torch.Tensor:
    """Apply per-row top-p (nucleus) mask via batched sort + cumsum.

    Single sort, single softmax, single cumsum, single scatter — all
    batched across N rows.
    """
    p_full = p.unsqueeze(0).expand(K, B).reshape(-1)  # (N,)
    if (p_full >= 1.0).all():
        return logits

    sorted_logits, sorted_idx = logits.sort(dim=-1, descending=True)
    sorted_probs = sorted_logits.softmax(dim=-1)
    cum = sorted_probs.cumsum(dim=-1)
    # Standard nucleus rule: keep tokens whose cumulative prob (BEFORE
    # this token's contribution) is < top_p. Equivalent to cumprobs -
    # sorted_probs < p, matches the legacy single-row helper.
    keep_sorted = (cum - sorted_probs) < p_full.unsqueeze(1)
    # At least one token: ensure the very top entry is always kept.
    keep_sorted[:, 0] = True
    # For disabled rows (p>=1.0), keep everything.
    keep_sorted = keep_sorted | (p_full.unsqueeze(1) >= 1.0)
    # Scatter the kept mask back into the original index ordering.
    keep = torch.empty_like(keep_sorted)
    keep.scatter_(-1, sorted_idx, keep_sorted)
    return logits.masked_fill_(~keep, float("-inf"))


def _vectorized_min_p_mask(
    logits: torch.Tensor,  # (N, V) fp32, in-place
    mp: torch.Tensor,  # (B,) fp32; 0.0 = disabled
    K: int,
    B: int,
    *,
    any_min_p: bool | None = None,
) -> torch.Tensor:
    """Apply per-row min-p mask: keep tokens whose softmax-prob >= mp * max.

    Single softmax + max + threshold compare, all batched.

    ``any_min_p`` is the host-side predicate request metadata already holds
    (:attr:`_SamplingMetadata.any_min_p`). Given, it replaces the early-out's
    device reduction, whose truth value would block the host on the GPU
    queue. ``None`` keeps that reduction for callers without metadata.
    """
    mp_full = mp.unsqueeze(0).expand(K, B).reshape(-1)  # (N,)
    if any_min_p is False or (any_min_p is None and (mp_full <= 0.0).all()):
        return logits
    # Logit-space comparison avoids a full softmax pass. ``prob_i >=
    # mp * max_prob`` iff ``exp(logit_i - max_logit) >= mp`` iff
    # ``logit_i >= log(mp) + max_logit``. The downstream sampler in
    # :func:`_fused_sample` runs its own softmax for Gumbel-max — the
    # prior version computed softmax HERE just to find thresholds and
    # then a SECOND softmax for the sample. Logit-space removes the
    # redundant N×V softmax (~50-150 µs/step at production batches).
    max_logit = logits.max(dim=-1, keepdim=True).values  # (N, 1)
    # ``mp == 0`` rows: the log below would explode to -inf which would
    # mask nothing (correct); but the explicit disabled mask is clearer
    # and avoids the log entirely.
    log_mp = mp_full.clamp_min(1e-30).log().unsqueeze(1)  # (N, 1)
    thresh = log_mp + max_logit  # (N, 1)
    thresh = torch.where(
        (mp_full <= 0.0).unsqueeze(1),
        torch.full_like(thresh, float("-inf")),
        thresh,
    )
    return logits.masked_fill_(logits < thresh, float("-inf"))


def _fused_topk_topp_triton(
    flat: torch.Tensor,  # (N, V) fp32 — modified in-place
    sm: _SamplingMetadata,
    K: int,
    B: int,
) -> torch.Tensor:
    """Fused top-k + top-p mask via the vendored vLLM Triton kernel.

    Replaces the two Python-batched ops
    (``_vectorized_top_k_mask`` + ``_vectorized_top_p_mask``) with
    ONE kernel launch, avoiding the global ``sort`` + ``softmax`` +
    ``cumsum`` + ``scatter`` kernel sequence the Python top-p path
    triggers.

    Tensors must be CUDA fp32. The caller (``_fused_sample``) is
    responsible for that contract — see the cast at the call site.

    Args:
        flat: ``(N=K*B, V)`` fp32 logits tensor; modified in-place.
        sm: per-step sampling metadata.
        K, B: original logits dimensions.
    """
    # Lazy import — keeps ``import triton`` off the CPU-only path so
    # tests on CPU-only hosts don't pay for it.
    from arbi_serve.sampler.topk_topp_triton import apply_top_k_top_p_triton

    k_full, p_full = _fused_topk_topp_args(flat, sm, K, B)
    if k_full is None and p_full is None:
        return flat

    return apply_top_k_top_p_triton(flat, k_full, p_full)


def _fused_topk_topp_args(
    flat: torch.Tensor,
    sm: _SamplingMetadata,
    K: int,
    B: int,
) -> tuple[torch.Tensor | None, torch.Tensor | None]:
    """Build the per-row (k, p) tensors for the fused Triton kernel.

    Broadcasts the (B,) metadata to (N=K*B,) and maps our "disabled"
    sentinels to the kernel's convention (top_k==0 → vocab_size so the
    kernel's ``k >= VOCAB_SIZE`` early-exit fires; top_p>=1 is already
    disabled per row). Returns ``(None, None)`` for disabled axes.
    """
    if sm.any_top_k:
        k_full = sm.top_k.unsqueeze(0).expand(K, B).reshape(-1)
        V = flat.shape[1]
        k_full = torch.where(k_full == 0, torch.full_like(k_full, V), k_full)
    else:
        k_full = None

    if sm.any_top_p:
        p_full = sm.top_p.unsqueeze(0).expand(K, B).reshape(-1).contiguous()
    else:
        p_full = None

    return k_full, p_full


# Per-device sampler-private RNG generator cache.
#
# Why we don't use the default CUDA generator for ``exponential_`` here.
# When cudagraphs are ON, the engine's captured forward pass records
# RNG-consuming ops (e.g. flash-attn varlen prefill always allocates a
# Philox ``rng_state``; future captured ops may dropout). The default
# generator's ``CUDAGeneratorState`` gets ``register_graph``'d to those
# captured CUDAGraphs, which flips ``capturing_=true`` during
# ``replay_prologue``. If ANY ``increase()`` call on the default
# generator fires while ``capturing_=true`` but the current stream's
# capture status is ``None`` (the steady-state on the main stream
# between captured replays), torch raises:
#
#     RuntimeError: Offset increment outside graph capture encountered
#     unexpectedly.
#
# at ``CUDAGeneratorState::increase`` in
# ``aten/src/ATen/cuda/CUDAGeneratorImpl.cpp``. The sampler's
# ``torch.empty_like(probs).exponential_(1)`` was the only RNG call on
# the engine's main stream — every stochastic completion (T>0) tripped
# this on every step the engine had captured graphs in its pool.
#
# Fix: route the ``exponential_`` through a sampler-private
# ``torch.Generator`` instance, one per device. Custom generators have
# their own independent ``CUDAGeneratorState`` that is NOT auto-
# registered with the engine's CUDAGraphs (only the default per-device
# generator is). The ``capturing_`` flag on this state never flips, so
# ``increase()`` always takes the non-capture branch and advances
# ``philox_offset_per_thread_`` cleanly. Distributionally identical to
# the default-generator path (Philox(seed, offset) is the same RNG
# regardless of which generator instance owns the state).
_NOISE_GENERATORS: dict[int, torch.Generator] = {}


def _get_noise_generator(device: torch.device) -> torch.Generator:
    """Return the sampler-private noise generator for ``device``.

    Lazily allocated on first request per device; seeded from the
    default generator's current seed so determinism contracts the
    engine sets via ``torch.manual_seed`` are preserved (the user-
    visible "set seed → reproduce sample" guarantee). All subsequent
    calls reuse the same generator instance — its Philox offset
    advances normally on each ``exponential_(generator=g)`` call.

    Threading. The engine's run loop is single-threaded per device,
    so no lock is needed. The dict-set on first miss is safe under
    the GIL.
    """
    idx = device.index if device.index is not None else 0
    g = _NOISE_GENERATORS.get(idx)
    if g is None:
        g = torch.Generator(device=device)
        # Seed from the current default generator's seed so the
        # sampler's noise stream is deterministic with the rest of the
        # engine's RNG state. Calling ``initial_seed()`` does not
        # advance offset on the default generator and is safe to
        # invoke here even when the default generator is registered
        # to a CUDAGraph (it does not touch ``offset_intragraph_``).
        try:
            g.manual_seed(int(torch.cuda.initial_seed()))
        except RuntimeError:
            # ``initial_seed`` can raise on a generator that has been
            # registered to a captured graph in some torch builds; in
            # that case fall back to a fresh wallclock seed (still
            # deterministic per-process via ``torch.manual_seed``
            # before sampler construction in tests).
            import time

            g.manual_seed(int(time.time_ns()) & 0x7FFFFFFFFFFFFFFF)
        _NOISE_GENERATORS[idx] = g
    return g


def _counter_gumbel_seeds(
    n: int,
    device: torch.device,
    row_seeds: torch.Tensor | None,
) -> torch.Tensor:
    """Resolve the ``(n,)`` int64 per-row Philox seeds for the counter kernel.

    ``row_seeds`` given: validate the shape and use it verbatim — the
    caller derived the seeds from each row's ``(seed, position)``
    (:func:`~arbi_serve.sampler.rank_symmetric.request_row_seeds`), the
    same keys on every rank and topology. ``row_seeds`` None (a caller
    with no requests to key on): draw a fresh per-step seed per row from
    the sampler-private (cudagraph-safe) generator.
    """
    if row_seeds is not None:
        if tuple(row_seeds.shape) != (n,):
            raise RuntimeError(f"_fused_sample: row_seeds shape {tuple(row_seeds.shape)} != ({n},)")
        return row_seeds
    gen = _get_noise_generator(device)
    return torch.randint(0, 2**62, (n,), device=device, dtype=torch.int64, generator=gen)
# ---- sampling_metadata.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Per-step sampling metadata: the ``(B,)`` knob tensors + fast-path predicates.

The :class:`_SamplingMetadata` dataclass and its build/key helpers marshal
each request's :class:`SamplingParams` into the device-side scalar tensors
the sampling chain consumes. Re-exported from
:mod:`arbi_serve.sampler.sampler` so the public import surface is unchanged.
"""

from __future__ import annotations

from collections.abc import Sequence
from dataclasses import dataclass

import torch

from arbi_serve.engine.request import Request


@dataclass
class _SamplingMetadata:
    """Per-step pre-built sampling knobs (one allocation per ``sample()``).

    Lives only for the duration of one ``Sampler.sample`` call. Holds
    GPU-side per-request scalar tensors (temperature, top_k, top_p,
    min_p) plus boolean fast-path predicates. The fields here are the
    minimum needed to drive the stochastic path with zero Python loops
    over requests.
    """

    # Per-row knobs, shape (B,), on the logits device.
    temperature: torch.Tensor  # fp32; 1.0 for greedy rows
    top_k: torch.Tensor  # int64; 0 = disabled
    top_p: torch.Tensor  # fp32; 1.0 = disabled
    min_p: torch.Tensor  # fp32; 0.0 = disabled
    # Per-row "is greedy" mask, shape (B,), bool. True ⇒ keep the
    # argmax sample and ignore the stochastic one.
    is_greedy: torch.Tensor
    # Per-row penalty knobs, shape (B,), fp32, on the logits device.
    # Built HERE rather than in ``apply_penalties`` because the slate
    # cache key already covers all three (see ``_slate_sampling_key``),
    # so a cache hit makes them free. Rebuilding them per step cost a
    # Python loop over requests plus three PAGEABLE (synchronous) H2D
    # copies on every decode step.
    repetition_penalty: torch.Tensor
    frequency_penalty: torch.Tensor
    presence_penalty: torch.Tensor
    # Per-knob predicates. ``has_penalties`` is their OR; these three let
    # ``apply_penalties`` skip an individual full-vocab op when no row
    # asks for it (Qwen ships repetition_penalty=1.0 in every profile).
    any_repetition: bool
    any_frequency: bool
    any_presence: bool

    # Fast-path predicates (CPU bools; cheap to test).
    all_greedy: bool
    # ``True`` iff AT LEAST ONE row is greedy. The host-side complement of
    # ``all_greedy``: it lets the mixed-batch merge decide whether a
    # ``torch.where`` against the greedy argmax is needed WITHOUT a per-step
    # ``is_greedy.any()`` device->host sync (which would block the host from
    # running the next step ahead). Derived purely from the slate's host-side
    # SamplingParams — bit-identical to ``bool(is_greedy.any())``.
    any_greedy: bool
    has_penalties: bool
    has_logit_bias: bool
    any_top_k: bool
    any_top_p: bool
    any_min_p: bool


def _staging_empty(n: int, *, dtype: torch.dtype, device: torch.device | str) -> torch.Tensor:
    """An uninitialised host buffer whose H2D copy to ``device`` is truly async.

    ``torch.empty(n, dtype=...)`` returns PAGEABLE host memory, and the CUDA
    runtime serializes a pageable H2D as ``cudaMemcpyAsync`` +
    ``cudaStreamSynchronize``. The ``non_blocking=True`` on the matching
    ``.to(device)`` is therefore silently ignored and the host blocks until
    the copy stream drains. Allocating the staging buffer in PINNED host
    memory makes that flag effective: byte-identical device values, no host
    stall. The pinned block is owned by the CUDA caching host allocator,
    which defers its reuse until the recorded copy event completes, so it is
    safe even though the host tensor is a temporary.

    Falls back to a pageable buffer for a non-CUDA device, where
    ``pin_memory`` is unavailable and the copy is a plain host memcpy.
    """
    if torch.device(device).type != "cuda":
        return torch.empty(n, dtype=dtype)
    return torch.empty(n, dtype=dtype, pin_memory=True)


def _slate_sampling_key(
    requests: Sequence[Request],
    device: torch.device,
    vocab_size: int,
) -> tuple:
    """Build an invalidation key for the per-step sampling metadata.

    The key is a pure function of *exactly* the inputs
    :func:`_build_sampling_metadata` reads — and nothing else — so two
    slates with the same key are guaranteed to produce byte-identical
    ``_SamplingMetadata`` tensors. It captures, in slate order:

      * ``device`` and ``vocab_size`` — both feed the build (the
        ``top_k >= vocab_size`` clamp, the H2D target device);
      * per row: ``request_id`` AND every :class:`SamplingParams` field
        the build touches (temperature, top_k, top_p, min_p, the three
        penalties, and ``bool(logit_bias)``).

    Why ``request_id`` *in slate order* matters. ``_SamplingMetadata``
    tensors are indexed by **slate position**, not request id. An
    admission, an eviction, or any reorder changes the position→request
    mapping even if the multiset of params is unchanged. Folding
    ``request_id`` into the key at its slate index makes any such churn
    flip the key, so the cache can never serve a stale row-to-position
    mapping. This is deliberately conservative: identical params on a
    *different* request still invalidate.

    Note we intentionally do NOT consult ``logit_bias`` contents,
    penalty histories, or grammar state here — those do not affect the
    five scalar knob tensors or the six CPU bool predicates this
    metadata holds (penalty/bias VALUES are read later, per step, by
    the processor chain, not by the metadata build). Only the
    ``bool(logit_bias)`` / penalty-active flags live in the metadata,
    and those are captured.
    """
    dev_key = (device.type, device.index)
    rows = []
    for req in requests:
        sp = req.sampling
        rows.append(
            (
                req.request_id,
                sp.temperature,
                sp.top_k,
                sp.top_p,
                sp.min_p,
                sp.repetition_penalty,
                sp.frequency_penalty,
                sp.presence_penalty,
                bool(sp.logit_bias),
            )
        )
    return (dev_key, vocab_size, tuple(rows))


def _build_sampling_metadata(
    requests: Sequence[Request],
    device: torch.device,
    vocab_size: int,
) -> _SamplingMetadata:
    """Marshal per-request sampling knobs into device-side tensors.

    One CPU loop, one H2D copy per scalar tensor. The downstream chain
    is a function of these tensors only.
    """
    B = len(requests)
    temps = _staging_empty(B, dtype=torch.float32, device=device)
    tks = _staging_empty(B, dtype=torch.int64, device=device)
    tps = _staging_empty(B, dtype=torch.float32, device=device)
    mps = _staging_empty(B, dtype=torch.float32, device=device)
    greedy = _staging_empty(B, dtype=torch.bool, device=device)
    rep = _staging_empty(B, dtype=torch.float32, device=device)
    freq = _staging_empty(B, dtype=torch.float32, device=device)
    pres = _staging_empty(B, dtype=torch.float32, device=device)

    has_penalties = False
    any_rep = False
    any_freq = False
    any_pres = False
    has_bias = False
    any_tk = False
    any_tp = False
    any_mp = False
    all_greedy = True
    any_greedy = False

    # Per-row values gather in Python lists and land in each staging tensor with ONE copy:
    # a per-element ``tensor[i] = x`` is a dispatcher call, eight per row per step.
    l_g, l_t, l_tk, l_tp, l_mp, l_rep, l_freq, l_pres = [], [], [], [], [], [], [], []
    for req in requests:
        sp = req.sampling
        is_g = sp.is_greedy
        l_g.append(is_g)
        if is_g:
            any_greedy = True
        # For greedy rows we collapse temperature to 1.0 — the row is
        # selected via the where-merge with greedy_argmax further down,
        # so the temperature value only matters for stochastic rows.
        l_t.append(1.0 if (is_g or sp.temperature == 1.0) else sp.temperature)
        # top_k=-1 ⇒ "disabled". Also clamp >= V to "disabled".
        tk = sp.top_k
        if tk is None or tk <= 0 or tk >= vocab_size:
            l_tk.append(0)
        else:
            l_tk.append(tk)
            if not is_g:
                any_tk = True
        l_tp.append(sp.top_p)
        if not is_g and sp.top_p < 1.0:
            any_tp = True
        l_mp.append(sp.min_p)
        if not is_g and sp.min_p > 0.0:
            any_mp = True
        if not is_g:
            all_greedy = False
        l_rep.append(sp.repetition_penalty)
        l_freq.append(sp.frequency_penalty)
        l_pres.append(sp.presence_penalty)
        if sp.repetition_penalty != 1.0:
            any_rep = True
        if sp.frequency_penalty != 0.0:
            any_freq = True
        if sp.presence_penalty != 0.0:
            any_pres = True
        if (
            sp.repetition_penalty != 1.0
            or sp.frequency_penalty != 0.0
            or sp.presence_penalty != 0.0
        ):
            has_penalties = True
        if sp.logit_bias:
            has_bias = True
    if B:
        for dst, vals in (
            (greedy, l_g),
            (temps, l_t),
            (tks, l_tk),
            (tps, l_tp),
            (mps, l_mp),
            (rep, l_rep),
            (freq, l_freq),
            (pres, l_pres),
        ):
            dst.copy_(torch.tensor(vals, dtype=dst.dtype))

    return _SamplingMetadata(
        temperature=temps.to(device, non_blocking=True),
        top_k=tks.to(device, non_blocking=True),
        top_p=tps.to(device, non_blocking=True),
        min_p=mps.to(device, non_blocking=True),
        is_greedy=greedy.to(device, non_blocking=True),
        repetition_penalty=rep.to(device, non_blocking=True),
        frequency_penalty=freq.to(device, non_blocking=True),
        presence_penalty=pres.to(device, non_blocking=True),
        any_repetition=any_rep,
        any_frequency=any_freq,
        any_presence=any_pres,
        all_greedy=all_greedy,
        any_greedy=any_greedy,
        has_penalties=has_penalties,
        has_logit_bias=has_bias,
        any_top_k=any_tk,
        any_top_p=any_tp,
        any_min_p=any_mp,
    )


def _all_greedy_default(requests: Sequence[Request]) -> bool:
    """``True`` iff every request is greedy with default penalties /
    bias / xgrammar.

    The full sampling chain (``apply_penalties`` ->
    ``apply_logit_bias`` -> external processors -> ``apply_temperature``)
    short-circuits row-by-row when each row's :class:`SamplingParams`
    has the default values. But each processor still iterates the
    ``requests`` sequence, reads attributes, and walks ``logit_bias``
    keys. At B=1 single-stream decode (the production hot path) every
    one of those calls is a no-op that still costs Python overhead.

    This predicate folds the four short-circuits into one flat loop so
    :meth:`Sampler.sample` can skip the chain entirely. Mirrors
    :attr:`SamplingParams.is_greedy` but additionally checks penalties,
    bias, and grammar state (the only fields the processors touch).
    """
    for req in requests:
        sp = req.sampling
        if not sp.is_greedy:
            return False
        if sp.repetition_penalty != 1.0:
            return False
        if sp.frequency_penalty != 0.0:
            return False
        if sp.presence_penalty != 0.0:
            return False
        if sp.logit_bias:
            return False
        # Grammar state is per-request; xgrammar processor is a member
        # of ``self._processors`` (caller checks ``no_external_procs``)
        # so we don't need to probe ``req.grammar_state`` here.
    return True
# ---- serve_warmup.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The serve-kernel warmup's sampler half: the kernels a sampled token runs."""

from __future__ import annotations

import fcntl
import logging
import os
from contextlib import ExitStack, contextmanager
from pathlib import Path
from typing import Any

import torch

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


@contextmanager
def coordinate_verify_warmup(eng: Any):
    """Let CPU-constrained local TP peers reuse the first rank's Triton compilations.

    Only the rank-local verify sampler belongs in this scope. Each rank must
    still load and launch every variant before serving. Collectives run outside.
    """
    from arbi_serve.cache_paths import _is_local
    from arbi_serve.ocr.cpu_budget import container_cpus
    from arbi_serve.runtime.host_oom_margin import local_rank_count

    ranks = min(int(eng.parallel_cfg.tp_size), local_rank_count())
    root = os.environ.get("TRITON_CACHE_DIR")
    if ranks < 2 or not root or container_cpus() > ranks or not _is_local(Path(root)):
        yield
        return

    sm, minor = torch.cuda.get_device_capability(eng.device)
    shape = (eng.model.dims.vocab_size, eng.cfg.batch.max_batch, eng.drafter.max_k, ranks)
    key = "-".join(map(str, shape))
    path = Path(root) / f".arbi-verify-warm-sm{sm}{minor}-{key}.lock"
    with ExitStack() as stack:
        try:
            lock = stack.enter_context(path.open("a"))
            fcntl.flock(lock, fcntl.LOCK_EX)
        except OSError as exc:
            logger.debug("verify sampler warmup continuing without cache lock %s: %s", path, exc)
        yield


def warm_serving_sampler_kernels(eng: Any) -> None:
    """Warm the sampler and structured-output kernels, post-grow, before ready.

    Nothing on a task that never samples
    (:func:`~arbi_serve.engine.serving_tasks.samples_tokens`): an embed / rerank /
    decide / forward instance runs neither, and warming them cost a pooling boot
    its sampler scratch and up to 88 s.
    """
    from arbi_serve.engine.serving_tasks import samples_tokens

    if not samples_tokens(eng):
        return
    try:
        from arbi_serve.sampler.kernel_warmup import warm_sampler_kernels

        _n = warm_sampler_kernels(
            eng.device,
            int(eng.model.dims.vocab_size),
            int(eng.cfg.batch.max_batch),
        )
        logger.info("serve-kernel warmup: sampler kernels — %d warm launches", _n)
        from arbi_serve.sampler.vocab_shard_draw import warm_shard_draw_kernels

        _n = warm_shard_draw_kernels(eng)
        logger.info("serve-kernel warmup: vocab-shard draw — %d warm launches", _n)
    except Exception:  # noqa: BLE001 — warm gap = first-call JIT, detector-reported
        logger.exception("serve-kernel warmup: sampler kernel pre-compile failed")
    try:
        # Structured output (``response_format``) is reachable on ANY
        # request, and its bitmask mask runs outside every captured
        # graph. The constrained-row count spans the flat verify slate,
        # so the warm covers the row classes that slate can reach.
        from arbi_serve.sampler.kernel_warmup import warm_structured_output_kernel

        _drafter = getattr(eng, "drafter", None)
        _kp1 = max(1, int(getattr(_drafter, "max_k", 0)) + 1)
        _n = warm_structured_output_kernel(
            eng.device,
            int(eng.model.dims.vocab_size),
            max(1, _kp1) * int(eng.cfg.batch.max_batch),
        )
        logger.info("serve-kernel warmup: structured-output mask — %d warm launches", _n)
    except Exception:  # noqa: BLE001 — warm gap = first-call JIT, detector-reported
        logger.exception("serve-kernel warmup: structured-output pre-compile failed")


def release_warm_transients(device: Any) -> int:
    """Hand the serve-kernel warmup's idle default-pool segments back to the driver.

    The warms run past the freeze, on the free VRAM the KV grow held out, and
    each drives a vocab-scale ``(rows, vocab)`` tensor family at every
    representative row count up to ``max_batch`` (plus the verify, drafter and
    watermark slates). The tensors are dead when a warm returns but the caching
    allocator keeps their segments reserved, so free VRAM falls by the warm's
    high-water although nothing a request will ever hold is left behind. That
    draw is not a floor term: what a served step takes is measured by the
    serving realization, which drives real steps, and a warm's synthetic slate
    is a different and wider quantity. Returning the idle segments leaves the
    post-freeze gate to read what the phase RETAINED (a loaded module, a named
    pool's mapping), which is the quantity the floor's rows describe.

    Returns the bytes handed back, read as the change in the caching
    allocator's reserved total: that is exactly what ``empty_cache`` released,
    and it is not a driver free-memory read, so it needs no ledger bracket.
    """
    if not torch.cuda.is_available():
        return 0
    torch.cuda.synchronize(device)
    reserved_before = torch.cuda.memory_reserved(device)
    torch.cuda.empty_cache()
    returned = max(0, int(reserved_before) - int(torch.cuda.memory_reserved(device)))
    logger.info(
        "serve-kernel warmup: returned %.1f MiB of idle default-pool segments to the driver",
        returned / (1 << 20),
    )
    return returned
# ---- shard_topk_triton.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Tiled shard top-k pairs and a compact top-k/top-p/min-p mask.

Selection carries an ordered fp32 value and inverse column in one uint64
key. Keeping K winners from each tile cannot omit a global top-K winner;
a second reduction therefore reads only the tile winners. Equal values
prefer the lower column. Output pairs retain the original fp32 values.

The compact mask includes the whole tie group at a nucleus boundary, like
the served CUDA mask. No device value controls a host branch.
"""

from __future__ import annotations

import torch
import triton
import triton.language as tl

from arbi_serve.sampler._gumbel_argmax_kernel import _philox_uniform

_LOGITS_TYPES = {torch.float32: tl.float32, torch.float16: tl.float16, torch.bfloat16: tl.bfloat16}


@triton.jit
def _pack(value, index):
    bits = value.to(tl.uint32, bitcast=True)
    # Numeric ties include both signed zeroes. NaNs sort before finite
    # values, as torch.topk does; the merge reloads the original payload.
    bits = tl.where(value == 0.0, 0, bits)
    ordered = tl.where((bits & 0x80000000) != 0, ~bits, bits ^ 0x80000000)
    ordered = tl.where(value != value, 0xFFFFFFFF, ordered)
    return (ordered.to(tl.uint64) << 32) | (0xFFFFFFFF - index.to(tl.uint32)).to(tl.uint64)


@triton.jit
def _tile_topk(
    X,
    Partial,
    WIDTH: tl.constexpr,
    STRIDE: tl.constexpr,
    TILES: tl.constexpr,
    K: tl.constexpr,
    BLOCK: tl.constexpr,
):
    row, tile = tl.program_id(0), tl.program_id(1)
    col = tile * BLOCK + tl.arange(0, BLOCK)
    value = tl.load(X + row * STRIDE + col, col < WIDTH, other=-float("inf")).to(tl.float32)
    key = _pack(value, col)
    key = tl.where(col < WIDTH, key, 0)
    best = tl.topk(key, K)
    out = tl.arange(0, K)
    tl.store(Partial + (row * TILES + tile) * K + out, best)


@triton.jit
def _merge_topk(
    X,
    Partial,
    Out,
    TILES: tl.constexpr,
    K: tl.constexpr,
    N: tl.constexpr,
    START: tl.constexpr,
    STRIDE: tl.constexpr,
    BLOCK: tl.constexpr,
):
    row = tl.program_id(0)
    col = tl.arange(0, BLOCK)
    key = tl.load(Partial + row * TILES * K + col, col < TILES * K, other=0)
    best = tl.topk(key, K)
    index = (0xFFFFFFFF - best.to(tl.uint32)).to(tl.int32)
    slot = tl.arange(0, K)
    valid = (slot < N) & (best != 0)
    value = tl.load(X + row * STRIDE + index, valid, other=-float("inf")).to(tl.float32)
    tl.store(Out + (row * N + slot) * 2, tl.where(valid, value, -float("inf")), slot < N)
    tl.store(Out + (row * N + slot) * 2 + 1, tl.where(valid, index + START, -1), slot < N)


@triton.jit(do_not_specialize=["ROWS"])
def _compact_mask(
    Values,
    Params,
    Ks,
    Out,
    TieCount,
    C: tl.constexpr,
    ROWS,
    S0: tl.constexpr,
    S1: tl.constexpr,
    SHARD_CANDIDATES: tl.constexpr,
    BLOCK: tl.constexpr,
):
    row = tl.program_id(0)
    col = tl.arange(0, BLOCK)
    raw = tl.load(Values + row * S0 + col * S1, col < C, other=-float("inf"))
    temp = tl.load(Params + row)
    top_p = tl.load(Params + ROWS + row)
    min_p = tl.load(Params + 2 * ROWS + row)
    k = tl.load(Ks + row)
    x = tl.div_rn(raw, temp)
    ordered_raw = tl.sort(raw, descending=True)
    ordered = tl.div_rn(ordered_raw, temp)
    kth_lane = col == tl.maximum(k - 1, 0)
    kth = tl.sum(tl.where(kth_lane, ordered, 0.0))
    if SHARD_CANDIDATES:
        raw_kth = tl.sum(tl.where(kth_lane, ordered_raw, 0.0))
        shard_last = (col < C) & ((col % SHARD_CANDIDATES) == SHARD_CANDIDATES - 1)
        hit = tl.sum((shard_last & (raw >= raw_kth)).to(tl.int32), 0) > 0
        finite = (raw_kth > -float("inf")) & (raw_kth < float("inf"))
        tl.atomic_add(TieCount, 1, mask=hit & finite & (k > 0))
    kept = tl.where((k == 0) | (ordered >= kth), ordered, -float("inf"))
    peak = tl.max(kept, 0)
    weight = tl.exp(kept - peak)
    probs = weight / tl.sum(weight, 0)
    before = tl.cumsum(probs, 0) - probs
    nucleus = (before < top_p) | (col == 0) | (top_p >= 1.0)
    pivot = tl.min(tl.where(nucleus & (col < C), kept, float("inf")), 0)
    keep = ((k == 0) | (x >= kth)) & ((top_p >= 1.0) | (x >= pivot))
    # The row maximum survives top-k and top-p, so min-p uses that peak.
    keep = keep & ((min_p <= 0.0) | (x >= peak + tl.log(min_p)))
    tl.store(Out + row * C + col, tl.where(keep, raw, -float("inf")), col < C)


def shard_topk_pairs(local: torch.Tensor, *, shard_start: int, n_cand: int) -> torch.Tensor:
    """CUDA ``(rows, width)`` -> fp32 ``(rows, n_cand, value/index)`` pairs."""
    if local.ndim != 2 or not local.is_cuda or local.stride(1) != 1:
        raise ValueError("shard top-k needs CUDA rows with contiguous columns")
    if not 0 < n_cand <= 64 or local.shape[1] < 1:
        raise ValueError("shard top-k needs 1..64 candidates and nonempty columns")
    if not 0 <= shard_start < 2**24 or shard_start + local.shape[1] > 2**24:
        raise ValueError("fp32 candidate indices require vocab below 2**24")
    rows, width = local.shape
    # A one-row slice is contiguous even when its unused row stride still
    # names the full vocabulary. Canonicalise it to the boot-warmed layout.
    stride = local.stride(0) if rows > 1 else width
    k = triton.next_power_of_2(n_cand)
    tiles = triton.cdiv(width, 1024)
    partial = torch.empty((rows, tiles, k), dtype=torch.uint64, device=local.device)
    out = torch.empty((rows, n_cand, 2), dtype=torch.float32, device=local.device)
    if rows:
        _tile_topk[(rows, tiles)](local, partial, width, stride, tiles, k, 1024)
        _merge_topk[(rows,)](
            local,
            partial,
            out,
            tiles,
            k,
            n_cand,
            shard_start,
            stride,
            triton.next_power_of_2(tiles * k),
            num_warps=8,
        )
    return out


def filter_candidate_values(
    values: torch.Tensor,
    params: torch.Tensor,
    top_k: torch.Tensor,
    *,
    tie_counter: torch.Tensor | None = None,
    shard_candidates: int = 0,
) -> torch.Tensor:
    """Mask compact fp32 rows; params contains temperature/top-p/min-p rows."""
    if values.ndim != 2 or not values.is_cuda or values.dtype != torch.float32:
        raise ValueError("compact mask needs CUDA fp32 rows")
    rows, count = values.shape
    if not 0 < count <= 4096:
        raise ValueError("compact mask needs 1..4096 candidates")
    if params.shape != (3, rows) or top_k.shape != (rows,):
        raise ValueError("compact mask parameter shapes do not match rows")
    if not params.is_contiguous() or not top_k.is_contiguous():
        raise ValueError("compact mask parameters must be contiguous")
    if params.device != values.device or top_k.device != values.device:
        raise ValueError("compact mask parameters must share the values' device")
    if params.dtype != torch.float32 or top_k.dtype not in (torch.int32, torch.int64):
        raise ValueError("compact mask needs fp32 parameters and integer top-k")
    if shard_candidates and (tie_counter is None or count % shard_candidates):
        raise ValueError("tie counting needs a counter and complete shards")
    out = torch.empty_like(values, memory_format=torch.contiguous_format)
    if rows:
        _compact_mask[(rows,)](
            values,
            params,
            top_k,
            out,
            tie_counter if tie_counter is not None else out,
            count,
            rows,
            values.stride(0),
            values.stride(1),
            shard_candidates,
            triton.next_power_of_2(count),
        )
    return out


@triton.jit
def _scaled_logit(raw, temp, DTYPE: tl.constexpr):
    # Sampler.apply_temperature divides into a tensor of the head's dtype.
    # Its rounding can merge raw values into a larger top-k boundary group.
    return tl.div_rn(raw, temp).to(DTYPE).to(tl.float32)


@triton.jit
def _boundary_partial(
    X,
    Pairs,
    Params,
    Seeds,
    WholeRow,
    Counts,
    Scores,
    Indices,
    WIDTH: tl.constexpr,
    STRIDE: tl.constexpr,
    TILES: tl.constexpr,
    N: tl.constexpr,
    START: tl.constexpr,
    BLOCK: tl.constexpr,
):
    row, tile = tl.program_id(0), tl.program_id(1)
    temp = tl.load(Params + row)
    boundary = _scaled_logit(tl.load(Pairs + (row * (N + 1) + N - 1) * 2), temp, X.dtype.element_ty)
    following = _scaled_logit(tl.load(Pairs + (row * (N + 1) + N) * 2), temp, X.dtype.element_ty)
    whole = tl.load(WholeRow + row)
    count = tl.full((), 0, tl.int32)
    best_score = tl.full((), -float("inf"), tl.float32)
    best_index = tl.full((), 0, tl.int32)
    # The lookahead proves whether any omitted token can tie the boundary.
    # A unique last candidate needs neither a scan nor a boundary winner.
    if whole | (following == boundary):
        col = tile * BLOCK + tl.arange(0, BLOCK)
        valid = col < WIDTH
        raw = tl.load(X + row * STRIDE + col, valid, other=-float("inf")).to(tl.float32)
        scaled = _scaled_logit(raw, temp, X.dtype.element_ty)
        tied = valid & (scaled == boundary)
        count = tl.sum(tied.to(tl.int32), 0)
        eligible = valid & (whole | tied)
        seed = tl.load(Seeds + row)
        lo = (seed & 0xFFFFFFFF).to(tl.uint32)
        hi = ((seed >> 32) & 0xFFFFFFFF).to(tl.uint32)
        uniform = _philox_uniform(col + START, lo, hi)
        noise = -tl.log(-tl.log(uniform))
        score = tl.where(eligible, scaled + noise, -float("inf"))
        best_score = tl.max(score, 0)
        best_index = tile * BLOCK + tl.argmax(score, 0)
    offset = row * TILES + tile
    tl.store(Counts + offset, count)
    tl.store(Scores + offset, best_score)
    tl.store(Indices + offset, best_index)


@triton.jit
def _finish_boundary(
    X,
    Pairs,
    Params,
    Counts,
    Scores,
    Indices,
    Out,
    STRIDE: tl.constexpr,
    TILES: tl.constexpr,
    N: tl.constexpr,
    START: tl.constexpr,
    BLOCK: tl.constexpr,
    PAIR_BLOCK: tl.constexpr,
):
    row = tl.program_id(0)
    tile = tl.arange(0, BLOCK)
    counts = tl.load(Counts + row * TILES + tile, tile < TILES, other=0)
    scores = tl.load(Scores + row * TILES + tile, tile < TILES, other=-float("inf"))
    winner = tl.argmax(scores, 0)
    local_index = tl.load(Indices + row * TILES + winner)
    winning_value = tl.load(X + row * STRIDE + local_index).to(tl.float32)
    pair_col = tl.arange(0, PAIR_BLOCK)
    pair_value = tl.load(Pairs + (row * (N + 1) + pair_col) * 2, pair_col < N, other=-float("inf"))
    pair_index = tl.load(Pairs + (row * (N + 1) + pair_col) * 2 + 1, pair_col < N, other=0)
    boundary = tl.load(Pairs + (row * (N + 1) + N - 1) * 2)
    temp = tl.load(Params + row)
    scaled_boundary = _scaled_logit(boundary, temp, X.dtype.element_ty)
    already_present = tl.sum(
        (
            (pair_col < N)
            & (_scaled_logit(pair_value, temp, X.dtype.element_ty) == scaled_boundary)
        ).to(tl.int32),
        0,
    )
    omitted = tl.maximum(tl.sum(counts, 0) - already_present, 0)
    base = Out + row * (N + 2) * 2
    tl.store(base + pair_col * 2, pair_value, pair_col < N)
    tl.store(base + pair_col * 2 + 1, pair_index, pair_col < N)
    tl.store(base + N * 2, boundary)
    tl.store(base + N * 2 + 1, omitted.to(tl.float32))
    # With no scan, a duplicate of the first retained candidate is harmless.
    # It avoids a fabricated index/value overwriting a real scatter column.
    has_winner = tl.max(scores, 0) > -float("inf")
    first_value = tl.load(Pairs + row * (N + 1) * 2)
    first_index = tl.load(Pairs + row * (N + 1) * 2 + 1)
    tl.store(base + (N + 1) * 2, tl.where(has_winner, winning_value, first_value))
    tl.store(base + (N + 1) * 2 + 1, tl.where(has_winner, local_index + START, first_index))


def complete_topk_ties(local, pairs, params, seeds, whole_row, *, shard_start, n_cand):
    """Append omitted boundary mass and its seeded winner to local candidates.

    ``pairs`` contains N+1 local winners; only the first N are sent. The
    lookahead gates a scan for omitted ties. The payload then carries N
    ordinary pairs, ``(boundary value, omitted count)``, and one boundary
    Gumbel winner. Unfiltered mixed rows send their whole-shard winner there.
    """
    rows, width = local.shape
    stride = local.stride(0) if rows > 1 else width
    if pairs.shape != (rows, n_cand + 1, 2) or params.shape != (3, rows):
        raise ValueError("boundary completion shapes do not match shard rows")
    if seeds.shape != (rows,) or whole_row.shape != (rows,):
        raise ValueError("boundary completion needs one seed and row kind per row")
    tiles = triton.cdiv(width, 1024)
    count = torch.empty((rows, tiles), dtype=torch.int32, device=local.device)
    score = torch.empty((rows, tiles), dtype=torch.float32, device=local.device)
    index = torch.empty((rows, tiles), dtype=torch.int32, device=local.device)
    out = torch.empty((rows, n_cand + 2, 2), dtype=torch.float32, device=local.device)
    if rows:
        _boundary_partial[(rows, tiles)](
            local,
            pairs,
            params,
            seeds,
            whole_row,
            count,
            score,
            index,
            width,
            stride,
            tiles,
            n_cand,
            shard_start,
            1024,
        )
        _finish_boundary[(rows,)](
            local,
            pairs,
            params,
            count,
            score,
            index,
            out,
            stride,
            tiles,
            n_cand,
            shard_start,
            triton.next_power_of_2(tiles),
            triton.next_power_of_2(n_cand),
        )
    return out


@triton.jit(do_not_specialize=["ROWS"])
def _payload_mask(
    Pairs,
    Params,
    Ks,
    OutValues,
    OutIndices,
    TieCount,
    ROWS,
    TP: tl.constexpr,
    N: tl.constexpr,
    COUNT_TIES: tl.constexpr,
    LOGITS_TYPE: tl.constexpr,
    BLOCK: tl.constexpr,
):
    row = tl.program_id(0)
    col = tl.arange(0, BLOCK)
    count: tl.constexpr = TP * (N + 2)
    slot = col % (N + 2)
    original = (col < count) & (slot < N)
    mass = (col < count) & (slot == N)
    winner = (col < count) & (slot == N + 1)
    raw = tl.load(Pairs + (row * count + col) * 2, col < count, other=-float("inf"))
    index = tl.load(Pairs + (row * count + col) * 2 + 1, col < count, other=0)
    temp = tl.load(Params + row)
    top_p = tl.load(Params + ROWS + row)
    min_p = tl.load(Params + 2 * ROWS + row)
    k = tl.load(Ks + row)
    scaled = _scaled_logit(raw, temp, LOGITS_TYPE)
    ordered = tl.sort(tl.where(original, scaled, -float("inf")), descending=True)
    kth = tl.sum(tl.where(col == tl.maximum(k - 1, 0), ordered, 0.0), 0)
    kept = tl.where((k == 0) | (ordered >= kth), ordered, -float("inf"))
    peak = tl.max(kept, 0)
    weight = tl.exp(kept - peak)
    relevant_mass = mass & (k > 0) & (scaled >= kth) & (index > 0)
    missing_weight = tl.sum(tl.where(relevant_mass, index * tl.exp(scaled - peak), 0.0), 0)
    probs = weight / (tl.sum(weight, 0) + missing_weight)
    before = tl.cumsum(probs, 0) - probs
    nucleus = (before < top_p) | (col == 0) | (top_p >= 1.0)
    pivot = tl.min(tl.where(nucleus & (col < TP * N), kept, float("inf")), 0)
    keep = ((k == 0) | (scaled >= kth)) & ((top_p >= 1.0) | (scaled >= pivot))
    keep = keep & ((min_p <= 0.0) | (scaled >= peak + tl.log(min_p)))
    out_col = (col // (N + 2)) * (N + 1) + tl.minimum(slot, N)
    emit = original | winner
    tl.store(OutValues + row * TP * (N + 1) + out_col, tl.where(keep, raw, -float("inf")), emit)
    tl.store(OutIndices + row * TP * (N + 1) + out_col, index.to(tl.int64), emit)
    if COUNT_TIES:
        finite = (kth > -float("inf")) & (kth < float("inf"))
        tl.atomic_add(TieCount, 1, mask=(tl.sum(relevant_mass.to(tl.int32), 0) > 0) & finite)


def filter_shard_payload(
    pairs, params, top_k, *, n_cand, tie_counter=None, logits_dtype=torch.float32
):
    """Filter completed payloads, excluding mass metadata from emitted tokens.

    The omitted tokens all equal a shard's last retained value. No token
    strictly above the global kth value can be omitted when N >= k or the
    candidates cover every column of the local shard, so their
    mass changes only that boundary group's normaliser. Its seeded winner
    suffices for the final counter-Gumbel draw whenever the group survives.
    """
    if pairs.ndim != 3 or pairs.shape[-1] != 2 or not pairs.is_contiguous():
        raise ValueError("completed payloads must be contiguous value/index pairs")
    rows, count, _ = pairs.shape
    if count % (n_cand + 2) or not 0 < n_cand < 64:
        raise ValueError("completed payloads must contain whole supported shards")
    if params.shape != (3, rows) or top_k.shape != (rows,):
        raise ValueError("completed payload parameters do not match rows")
    tp = count // (n_cand + 2)
    dtype = _LOGITS_TYPES[logits_dtype]
    vals = torch.empty((rows, tp * (n_cand + 1)), dtype=torch.float32, device=pairs.device)
    idx = torch.empty_like(vals, dtype=torch.int64)
    if rows:
        _payload_mask[(rows,)](
            pairs,
            params,
            top_k,
            vals,
            idx,
            tie_counter if tie_counter is not None else idx,
            rows,
            tp,
            n_cand,
            tie_counter is not None,
            dtype,
            triton.next_power_of_2(count),
        )
    return vals, idx
# ---- spec_verify_triton.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The stochastic verify tail in three launches, bit-identical to the ``p_target`` chain.

The chain it replaces (``rejection_sampler_ops._apply_sampling_params_*`` then
``mtp_sample_residual_philox``) widens and scales the slate, top-C masks it,
softmaxes it into a dense ``p_target`` and samples from that. Here the level-1
top-C partials read the native logits once (scaling in-register), and one
program per verify row derives the same cut (``_topc_threshold``), reproduces
``softmax_exact``'s summation order over the kept lanes, takes the accept test
and the Philox residual/bonus draw; a third launch counts the accepted prefix.
"""

from __future__ import annotations

from collections.abc import Callable, Iterator, Sequence
from dataclasses import dataclass
from functools import cache

import numpy as np
import torch

from arbi_serve.engine.request import SamplingParams

#: Columns per softmax_exact vector tile (aten's 1024 threads x ILP 4).
_TILE = 4096
#: Candidate columns kept per chunk, per unit of capacity: room for ties at the cut.
_IDX_PER_CAP = 2
#: Kept columns the finish folds one by one; more walks the row instead.
_KEEP_MAX = 256
#: Candidates the finish holds at once while it compacts the kept set.
_CAND_BLOCK = 1024
#: Widest row whose columns pack into the finish's 18-bit sort key.
_MAX_VOCAB = 1 << 18


Geometry = tuple[int, int, int, int, int]


@dataclass(frozen=True)
class FusedVerifyPlan:
    """Host-resolved launch shape and per-row parameters of one slate."""

    scale: int  # 1: x * inv (uniform slate), 2: x / temps[b] (heterogeneous)
    inv: float
    temps: tuple[float, ...]  # (B,), heterogeneous only
    greedy: tuple[int, ...]  # (B,), 1 = point mass on argmax
    top_ks: tuple[int, ...] | None  # (B,) per column, None = top_k disabled slate-wide
    top_ps: tuple[float, ...] | None
    capacity: int
    geometry: Geometry  # topc_mask._geometry


def _old_mask_rows(S: int, B: int, *, uniform: bool, chunked: bool) -> set[int]:
    """Row counts of the topc-mask calls the ``p_target`` chain makes for this slate."""
    from arbi_serve.spec_decode.rejection_sampler_ops import (
        _VERIFY_SAMPLER_CHUNK_ENGAGE_ROWS,
        _VERIFY_SAMPLER_CHUNK_STEP_ROWS,
    )

    if not uniform:
        return {B}
    if chunked and S * B > _VERIFY_SAMPLER_CHUNK_ENGAGE_ROWS:
        step = max(1, _VERIFY_SAMPLER_CHUNK_STEP_ROWS // B)
        return {min(step, S - lo) * B for lo in range(0, S, step)}
    return {S * B}


def _verify_geometry(
    row_counts: set[int], geometry_for_rows: Callable[[int], Geometry]
) -> Geometry | str:
    geos = {geometry_for_rows(rows) for rows in row_counts}
    if len(geos) != 1:
        return "mixed_geometry"
    geo = geos.pop()
    return "split_not_pow2" if geo[0] & (geo[0] - 1) else geo


def plan_fused_verify(
    main_logits: torch.Tensor,  # (K+1, B, V)
    sampling_params: Sequence[SamplingParams],
    *,
    chunked: bool,
) -> FusedVerifyPlan | str:
    """The slate's plan, or why the ``p_target`` chain must serve it (host values only)."""
    from arbi_serve.kernels.softmax_exact import serves_width
    from arbi_serve.sampler.topc_mask import _geometry, _part_budget_for
    from arbi_serve.spec_decode.rejection_sampler_ops import (
        SpecMaskPlan,
        _sampling_params_uniform,
        philox_verify_enabled,
    )

    S, B, V = (int(d) for d in main_logits.shape)
    dev = main_logits.device
    if not philox_verify_enabled(dev) or torch.compiler.is_compiling():
        return "no_triton"
    if main_logits.dtype not in (torch.float32, torch.bfloat16, torch.float16):
        return "logits_dtype"
    if main_logits.stride(-1) != 1:
        return "vocab_stride"
    if not serves_width(V, dev) or V > _MAX_VOCAB:
        return "vocab_width"
    if any(float(sp.min_p) > 0.0 for sp in sampling_params):
        return "min_p"
    uniform = _sampling_params_uniform(sampling_params)
    temps = [float(sp.temperature) for sp in sampling_params]
    if all(t <= 0.0 for t in temps):
        return "greedy_slate"
    if uniform:
        sp0 = sampling_params[0]
        k_on, p_on = 0 < int(sp0.top_k) < V, float(sp0.top_p) < 1.0
        ks = (int(sp0.top_k),) * B if k_on else None
        ps = (float(sp0.top_p),) * B if p_on else None
        mask_ks = (int(sp0.top_k) if k_on else V,)
        mask_ps = (float(sp0.top_p),)
    else:
        k_on = any(0 < int(sp.top_k) < V for sp in sampling_params)
        p_on = any(float(sp.top_p) < 1.0 for sp in sampling_params)
        mask_ks = tuple(int(sp.top_k) if 0 < int(sp.top_k) < V else V for sp in sampling_params)
        mask_ps = tuple(float(sp.top_p) for sp in sampling_params)
        ks = mask_ks if k_on else None
        ps = mask_ps if p_on else None
    # A sampled row's kept set must lie in the top_k candidates.
    if any(
        t > 0.0 and not 0 < int(sp.top_k) < V for t, sp in zip(temps, sampling_params, strict=True)
    ):
        return "unbounded_row"
    mplan = SpecMaskPlan.for_slate(
        device=dev, dtype=torch.float32, top_ks=mask_ks, top_ps=mask_ps, vocab_size=V
    )
    if mplan.refusal is not None:
        return f"pivot_mask:{mplan.refusal}"
    if mplan.nucleus:
        return "nucleus"
    cap = int(mplan.capacity)
    geo = _verify_geometry(
        _old_mask_rows(S, B, uniform=uniform, chunked=chunked),
        lambda rows: _geometry(V, cap, _part_budget_for(rows, V, cap, dev)),
    )
    if isinstance(geo, str):
        return geo
    return FusedVerifyPlan(
        scale=1 if uniform else 2,
        inv=float(np.float32(1.0 / temps[0])) if uniform else 1.0,
        temps=() if uniform else tuple(t if t > 0.0 else 1.0 for t in temps),
        greedy=tuple(1 if t <= 0.0 else 0 for t in temps),
        top_ks=ks,
        top_ps=ps,
        capacity=cap,
        geometry=geo,
    )


#: Warps of the finish program; its stack-frame budget is checked at this width.
FINISH_NUM_WARPS = 4


def finish_constants(
    plan: FusedVerifyPlan, vocab_size: int, *, dense: bool, per_row_seed: bool, draw_offset: int
) -> dict[str, int | bool]:
    """The finish kernel's constexprs for one slate (also what its stack-frame test compiles)."""
    from arbi_serve.sampler._triton_util import next_pow2

    split, _chunk, _block, part_block, _n_tiles = plan.geometry
    idx_cap = _IDX_PER_CAP * plan.capacity
    tail0 = vocab_size - vocab_size % _TILE
    return dict(
        VOCAB_SIZE=vocab_size, NVEC=tail0 // _TILE, TAIL0=tail0, SPLIT=split,
        SPLIT_BLOCK=next_pow2(split), CAP=plan.capacity, PART_BLOCK=part_block, IDX_CAP=idx_cap,
        KEEP_MAX=_KEEP_MAX, CAND_BLOCK=min(_CAND_BLOCK, split * idx_cap),
        TOPK_ENABLED=plan.top_ks is not None, TOPP_ENABLED=plan.top_ps is not None,
        SCALE=plan.scale, HAS_GREEDY=any(plan.greedy), Q_DENSE=dense,
        PER_ROW_SEED=per_row_seed, DRAW_OFFSET=int(draw_offset),
    )  # fmt: skip


def fused_verify_sample(
    plan: FusedVerifyPlan,
    main_logits: torch.Tensor,  # (K+1, B, V) native dtype, unit vocab stride
    draft_tokens: torch.Tensor,  # (K, B) int64
    draft_probs: torch.Tensor | None,  # (K, B, V) fp32, or None = point mass
    u_accept: torch.Tensor,  # (K, B) fp32
    seed_dev: torch.Tensor,  # (1,) int64, or ((K+1) * B,) per-row keys
    *,
    draw_offset: int,
) -> tuple[torch.Tensor, torch.Tensor]:
    """``(accepted_count (B,), accepted_tokens (K+1, B))``, int64, as ``mtp_sample_residual_philox``."""
    from arbi_serve.runtime.pinned_h2d import h2d_packed
    from arbi_serve.sampler._spec_verify_kernel import kernels
    from arbi_serve.sampler._topc_kernel import _topc_partials_kernel

    S, B, V = (int(d) for d in main_logits.shape)
    K, rows = S - 1, S * B
    dev = main_logits.device
    hetero = plan.scale == 2
    has_greedy = any(plan.greedy)
    hosts = [
        np.asarray(plan.top_ks * S if plan.top_ks else (0,), dtype=np.int64),
        np.asarray(plan.top_ps * S if plan.top_ps else (1.0,), dtype=np.float32),
        np.asarray(plan.temps if hetero else (1.0,), dtype=np.float32),
        np.asarray(plan.greedy if has_greedy else (0,), dtype=np.int32),
    ]
    top_k_d, top_p_d, temps_d, greedy_d = h2d_packed(hosts, dev)

    split, chunk, block, _part_block, n_tiles = plan.geometry
    cap = plan.capacity
    idx_cap = _IDX_PER_CAP * cap
    part = torch.empty((rows, split, cap), dtype=torch.float32, device=dev)
    part_idx = torch.empty((rows, split, idx_cap), dtype=torch.int32, device=dev)
    part_cnt = torch.empty((rows, split), dtype=torch.int32, device=dev)
    kept = torch.empty((rows, _KEEP_MAX), dtype=torch.int32, device=dev)
    _topc_partials_kernel[(rows * split,)](
        main_logits, part, part, part,
        main_logits.stride(0), main_logits.stride(1), B, plan.inv, temps_d, part_idx, part_cnt,
        VOCAB_SIZE=V, SPLIT=split, CHUNK=chunk, CAP=cap, BLOCK_SIZE=block, N_TILES=n_tiles,
        WRITE_MASS=False, SCALE=plan.scale, IDX_CAP=idx_cap,
    )  # fmt: skip

    finish, count = kernels()
    tokens = torch.empty((S, B), dtype=torch.int64, device=dev)
    accept = torch.empty((max(K, 1), B), dtype=torch.int8, device=dev)
    dense = draft_probs is not None
    if K > 0:
        draft = draft_tokens.to(torch.int64).contiguous()
        u = u_accept.to(torch.float32).contiguous()
        q = draft_probs if dense else part
        qsk, qsb = (draft_probs.stride(0), draft_probs.stride(1)) if dense else (0, 0)
    else:
        draft, u, q, qsk, qsb = tokens, part, part, 0, 0
    finish[(rows,)](
        main_logits, main_logits.stride(0), main_logits.stride(1), part, part_idx, part_cnt, kept,
        top_k_d, top_p_d, plan.inv, temps_d, greedy_d,
        q, qsk, qsb, draft, B, u, B, seed_dev, tokens, accept, B, K * B,
        **finish_constants(
            plan, V, dense=dense, per_row_seed=seed_dev.numel() != 1, draw_offset=draw_offset
        ),
        num_warps=FINISH_NUM_WARPS,
    )  # fmt: skip
    n_acc = torch.empty((B,), dtype=torch.int64, device=dev)
    if K > 0:
        count[(B,)](accept, n_acc, K, B, num_warps=1)
    else:
        n_acc.zero_()
    return n_acc, tokens


def _fused_warm_shapes(
    max_kp1: int, max_batch: int, geometry_for_rows: Callable[[int], Geometry], *, chunked: bool
) -> Iterator[tuple[int, int, bool]]:
    """One reachable launch per geometry and scalar/per-row temperature class.

    The partials, finish and count kernels exclude the row counts and leading
    strides from specialization. Fast-path eligibility and tile sizes still
    depend on the row counts seen by the mask, including its last short chunk.
    """
    seen = set()
    for kp1 in range(2, max_kp1 + 1):
        for b in range(1, max_batch + 1):
            for uniform in (True,) if b == 1 else (True, False):
                rows = _old_mask_rows(kp1, b, uniform=uniform, chunked=chunked)
                geo = _verify_geometry(rows, geometry_for_rows)
                if isinstance(geo, str) or (geo, uniform) in seen:
                    continue
                seen.add((geo, uniform))
                yield kp1, b, uniform


def warm_fused_verify(
    device: torch.device,
    max_kp1: int,
    max_batch: int,
    vocab_size: int,
    *,
    logits_dtype: torch.dtype,
    verify_draft_probs: torch.Tensor | None,
    chunked: bool,
    draw_offset: int,
) -> int:
    """Launch the finish variants reachable by this boot and its request presets."""
    from arbi_serve.kernels.softmax_exact import serves_width
    from arbi_serve.sampler.topc_mask import _geometry, _part_budget_for
    from arbi_serve.spec_decode.rejection_sampler_ops import (
        philox_verify_enabled,
        topc_mask_capacity,
    )

    cap = topc_mask_capacity(device)
    if not (
        0 < cap < vocab_size <= _MAX_VOCAB
        and philox_verify_enabled(device)
        and serves_width(vocab_size, device)
    ):
        return 0

    @cache
    def geometry_for_rows(rows: int) -> Geometry:
        return _geometry(vocab_size, cap, _part_budget_for(rows, vocab_size, cap, device))

    n = 0
    for kp1, b, uniform in _fused_warm_shapes(
        max_kp1, max_batch, geometry_for_rows, chunked=chunked
    ):
        logits = torch.empty((kp1, b, vocab_size), dtype=logits_dtype, device=device).zero_()
        draft = torch.zeros((kp1 - 1, b), dtype=torch.int64, device=device)
        u = torch.full_like(draft, 0.5, dtype=torch.float32)
        # mtp_verify_seed / MtpRows.verify and the watermark exact-match path
        # both supply a per-row key grid. The scalar seed used by the boot
        # memory probe is already compiled by that probe.
        seed = torch.ones(kp1 * b, dtype=torch.int64, device=device)
        proposals = [None]
        if verify_draft_probs is not None:
            proposals.append(verify_draft_probs[: kp1 - 1, :b])
        for top_p in (0.95, 1.0):
            for temp in (1.0,) if uniform else (0.7, 0.0):
                params = [SamplingParams(temperature=1.0, top_k=min(20, cap), top_p=top_p)] * b
                params[0] = SamplingParams(temperature=temp, top_k=min(20, cap), top_p=top_p)
                plan = plan_fused_verify(logits, params, chunked=chunked)
                if isinstance(plan, str):
                    continue
                for q in proposals:
                    fused_verify_sample(plan, logits, draft, q, u, seed, draw_offset=draw_offset)
                    n += 1
        del logits
    return n
# ---- structured.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Structured-output sampling parameters with mutual-exclusivity validation.

``StructuredOutputsParams`` is one container for every
structured-decoding mode (json_schema, regex, choice, grammar,
json_object, structural_tag) with **exactly one** mode active per
request, validated at construction time. The structured-decoding
backend (xgrammar, today) reads whichever field is set.

This module ships the param dataclass + validation plus
:meth:`StructuredOutputsParams.to_response_format`, the lowering onto the
:class:`arbi_serve.engine.request.ResponseFormat` contract that drives
xgrammar through the existing path — so only one spelling ever reaches the
backend.
"""

from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from arbi_serve.engine.request import ResponseFormat

# Names of the mutually-exclusive constraint fields. Kept here so
# ``__post_init__`` and any external introspection (e.g. an admin
# endpoint that lists which mode a request is in) read the same list.
_CONSTRAINT_FIELDS: tuple[str, ...] = (
    "json_schema",
    "regex",
    "choice",
    "grammar",
    "json_object",
    "structural_tag",
)


@dataclass
class StructuredOutputsParams:
    """One field per structured-decoding mode; **exactly one** must be set.

    Fields:
      * ``json_schema`` — JSON validating against this JSON Schema dict.
      * ``regex`` — output must match the regex.
      * ``choice`` — output must be one of these literal strings.
      * ``grammar`` — raw EBNF grammar.
      * ``json_object`` — free-form JSON (any well-formed JSON value).
        ``True`` enables, ``False``/``None`` disables. (boolean to keep
        the "exactly one set" semantics — ``True`` means "this mode is
        the active one".)
      * ``structural_tag`` — vendor tag (e.g. ``"tool_call"``) that the
        decoding backend translates into a built-in grammar.

    Mutual exclusivity is enforced in ``__post_init__``: zero set
    raises ``ValueError`` (caller should pass ``None`` instead);
    two-or-more set raises ``ValueError`` with the field names.
    """

    json_schema: dict | None = None
    regex: str | None = None
    choice: list[str] | None = None
    grammar: str | None = None
    json_object: bool | None = None
    structural_tag: str | None = None
    # Free-form options the decoder may consume (e.g. xgrammar
    # max_token_pad / disable_safety). Out of band of the
    # mutual-exclusivity check.
    backend_options: dict[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        active = self.active_fields()
        if len(active) == 0:
            raise ValueError(
                "StructuredOutputsParams: exactly one constraint field "
                f"must be set; got none. Choose one of {_CONSTRAINT_FIELDS}, "
                "or pass `None` instead of constructing a params object."
            )
        if len(active) > 1:
            raise ValueError(
                "StructuredOutputsParams: constraint fields are mutually "
                f"exclusive; got {active!r}. Set exactly one of "
                f"{_CONSTRAINT_FIELDS}."
            )
        # Field-shape validation (cheap): catch obviously wrong inputs
        # at construction so the decoder doesn't have to.
        if self.json_schema is not None and not isinstance(self.json_schema, dict):
            raise ValueError(
                f"StructuredOutputsParams.json_schema must be a dict, "
                f"got {type(self.json_schema).__name__}."
            )
        if self.regex is not None and not isinstance(self.regex, str):
            raise ValueError(
                f"StructuredOutputsParams.regex must be a str, got {type(self.regex).__name__}."
            )
        if self.choice is not None:
            if not isinstance(self.choice, list) or not self.choice:
                raise ValueError("StructuredOutputsParams.choice must be a non-empty list of str.")
            if not all(isinstance(c, str) for c in self.choice):
                raise ValueError("StructuredOutputsParams.choice items must all be str.")
        if self.grammar is not None and not isinstance(self.grammar, str):
            raise ValueError(
                f"StructuredOutputsParams.grammar must be a str, got {type(self.grammar).__name__}."
            )
        if self.json_object is not None and not isinstance(self.json_object, bool):
            raise ValueError("StructuredOutputsParams.json_object must be a bool when set.")
        if self.json_object is False:
            # `False` is meaningless — the slot signals "this mode is
            # active". Reject early so callers don't accidentally
            # think they disabled structured mode by setting False.
            raise ValueError(
                "StructuredOutputsParams.json_object must be True when set (use None to disable)."
            )
        if self.structural_tag is not None and not isinstance(self.structural_tag, str):
            raise ValueError("StructuredOutputsParams.structural_tag must be a str.")

    def active_fields(self) -> tuple[str, ...]:
        """Return the names of the constraint fields that are set."""
        out = []
        for name in _CONSTRAINT_FIELDS:
            v = getattr(self, name)
            if v is None:
                continue
            # `False` for json_object is not "set"; `__post_init__`
            # additionally rejects it so by here it's only `True`.
            if v is False:
                continue
            out.append(name)
        return tuple(out)

    @property
    def mode(self) -> str:
        """The single active mode name (e.g. ``"json_schema"``)."""
        active = self.active_fields()
        if len(active) != 1:
            # Defensive — __post_init__ guarantees exactly one.
            raise RuntimeError(f"StructuredOutputsParams.mode: invariant broken; active={active!r}")
        return active[0]

    def to_response_format(self) -> ResponseFormat:
        """Lower this params object onto the xgrammar-driving contract.

        The xgrammar compile path reads only
        :class:`arbi_serve.engine.request.ResponseFormat`, so this is the
        seam a caller uses to serve a ``StructuredOutputsParams`` request
        through the existing grammar machinery — no second spelling reaches
        the backend. ``choice`` has no ``ResponseFormat`` spelling and lowers
        to an anchored alternation of escaped literals, which constrains
        exactly the listed strings.
        """
        from arbi_serve.engine.request import ResponseFormat

        mode = self.mode
        if mode == "json_schema":
            assert isinstance(self.json_schema, dict)
            return ResponseFormat(type="json_schema", schema=self.json_schema)
        if mode == "regex":
            assert isinstance(self.regex, str)
            return ResponseFormat(type="regex", regex=self.regex)
        if mode == "choice":
            assert isinstance(self.choice, list)
            alternation = "(?:" + "|".join(re.escape(c) for c in self.choice) + ")"
            return ResponseFormat(type="regex", regex=alternation)
        if mode == "grammar":
            assert isinstance(self.grammar, str)
            return ResponseFormat(type="grammar", grammar=self.grammar)
        if mode == "json_object":
            return ResponseFormat(type="json_object")
        assert mode == "structural_tag", mode
        assert isinstance(self.structural_tag, str)
        return ResponseFormat(type="structural_tag", structural_tag=self.structural_tag)
# ---- thinking_budget.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Reasoning-block token accounting + the thinking-budget close guard.

A reasoning model spends tokens inside a ``<think>…</think>`` block before
its answer. This module owns BOTH halves of the engine's reasoning-block
bookkeeping, so the boundary is detected exactly once, in one place:

  * the COUNTING half — :func:`count_reasoning_token`, run per committed
    token by :func:`arbi_serve.engine.run_step.post_token`. It advances
    ``Request.reasoning_tokens`` (the boundary index the API surfaces as
    ``usage.completion_tokens_details.reasoning_tokens``, reported through
    :func:`reported_reasoning_tokens`), closes the block when the marker
    lands, and arms the budget when ``SamplingParams.thinking_token_budget``
    is exhausted;
  * the ENFORCEMENT half — :class:`ThinkingBudgetGuard`. For every row whose
    request is in the force-close state it masks all logits except the
    closing marker's next token id to ``-inf``, so the marker is really
    sampled — the token flows to the next step's input through the same path
    as any sampled token, keeping KV / positions consistent (a post-hoc
    overwrite of the sampled list would NOT reach the on-device input in the
    async-output pipeline). Multi-token markers are forced one id per step
    via ``Request.force_close_pos``, which the counting half advances as each
    forced id commits.

The marker is matched on TOKEN IDS, not text: ``Engine.think_end_ids`` is the
reasoning parser's ``think_end`` string encoded once at build
(:func:`resolve_think_end_ids`), so the per-token work stays a fixed handful
of integer compares with no detokenize, no string scan and no allocation on
the engine step. The text-side split
(:mod:`arbi_serve.engine.reasoning_parsing`) is the ROUTE's view of the same
boundary and stays independent — it consumes decoded text the engine loop
never has to wait for.

The guard's registration surface mirrors
:class:`~arbi_serve.sampler.omni_guard.OmniOutputGuard`
(``Sampler.set_logits_processors``): logits arrive ``(K, num_seqs, V)`` and
rows map 1:1 to ``requests``. Zero-cost pass-through for the common case —
no row forcing — mirroring the no-repeat-ngram blocker: one bool read per
row, then ``return logits`` unchanged.
"""

from __future__ import annotations

from collections.abc import Sequence
from typing import TYPE_CHECKING

import torch

from arbi_serve.engine.request import generated_token_ids, n_generated
from arbi_serve.flag_truth import path_counter
from arbi_serve.sampler.vocab_window import VocabWindow, window_bounds
from arbi_serve.server.instance_id import local_request_seq

if TYPE_CHECKING:
    from arbi_serve.engine.reasoning_parsers.base import ReasoningParser
    from arbi_serve.engine.request import Request
    from arbi_serve.tokenizer import Tokenizer

#: Fires once per request when the thinking budget is HIT and the close
#: marker starts being forced (bumped in ``post_token``, imported there).
#: A request that never exhausts its budget never bumps it; a served config
#: whose reasoning always fits under the cap shows ``fired == 0`` — which is
#: the honest signal that the lever, though configured, did not engage.
thinking_budget_forced = path_counter("thinking_budget_forced")

#: Distinct from the budget's counter ON PURPOSE. Both close a thinking block
#: the same way, so a single counter would let an operator's decision be read
#: back as the budget lever engaging — and the two answer different questions
#: ("is the configured cap doing anything" vs "did somebody intervene"). A
#: reader who cannot separate them cannot answer either.
thinking_closed_by_operator = path_counter("thinking_closed_by_operator")


def resolve_think_end_ids(parser: ReasoningParser | None, tokenizer: Tokenizer) -> tuple[int, ...]:
    """Encode the reasoning parser's closing marker to token ids. Build-time.

    The engine-side boundary detector. ``()`` for a model with no reasoning
    surface (``parser is None``) — which turns BOTH halves off: nothing is
    counted, nothing is forced, and ``reasoning_token_count`` stays ``None``
    on every request. Called once per build (and per hotswap), never on the
    step path.

    ``validate_markers`` has already proven this marker tokenizes and
    survives a ``skip_special_tokens`` round-trip, so an empty encoding here
    can only mean "no parser".

    Assumes the model emits the marker as its own canonical encoding — true
    for every registered family (Qwen3.x ``</think>`` is one dedicated id,
    which is also what the chat template feeds back in). A checkpoint that
    emitted some other tokenization of the same string would never close the
    block, so the request would report ALL its tokens as reasoning — the
    conservative direction (it never claims answer tokens were reasoning),
    and visible in the ``done#`` log line's ``content=0``.
    """
    if parser is None:
        return ()
    return tuple(int(t) for t in tokenizer.encode(parser.think_end, add_special_tokens=False))


def resolve_block_reasoning_ids(
    parser: ReasoningParser | None, tokenizer: Tokenizer
) -> tuple[int, ...]:
    """``(open_id, close_id)`` of a block-protocol parser's thinking block, else ``()``. Build-time.

    A block-protocol model (Inkling) opens a thinking block ITSELF, so the prompt never does and
    the prompt-opened counter (:func:`count_reasoning_token`) stays off for it. Both markers must
    be single token ids so the finished request's ids can be walked without a detokenize; anything
    else is refused at boot rather than counted wrongly.
    """
    if parser is None or not getattr(parser, "block_protocol", False):
        return ()
    ids = []
    for marker in (parser.think_start, parser.think_end):
        encoded = tokenizer.encode(marker, add_special_tokens=False)
        if len(encoded) != 1:
            raise ValueError(
                f"reasoning parser {parser.name!r} block marker {marker!r} encodes to "
                f"{len(encoded)} tokens; block-protocol reasoning accounting needs one."
            )
        ids.append(int(encoded[0]))
    return tuple(ids)


def block_reasoning_tokens(generated: Sequence[int], block_ids: tuple[int, ...]) -> int:
    """Generated tokens inside thinking blocks: ``open_id`` .. ``close_id``, both markers included.

    The same boundary convention as :func:`count_reasoning_token` (the closing marker is
    pre-answer and counts), summed over every block the model opened, and a block still open at the
    end of generation (``max_tokens``) counts to the last token. One pass over the finished ids,
    at finish only: nothing runs per step, so there is no per-request state to mirror across ranks.
    """
    open_id, close_id = block_ids
    inside = False
    total = 0
    for token in generated:
        if inside:
            total += 1
            inside = token != close_id
        elif token == open_id:
            total += 1
            inside = True
    return total


def _latch_first_answer(req) -> None:
    """The reasoning block closed: stamp it, and say so.

    Every close path — forced, natural, and a tool call starting inside the
    block — lands here, so the stamp and the push are one implementation rather
    than three. The push is what makes a still-running request stop rendering
    as "thinking" the moment it starts answering; there is no state change at
    this boundary, so the lifecycle door cannot see it and this is the seam.
    """
    if req.timing is None:
        return
    req.timing.stamp_first_answer()
    from arbi_serve.server.live_events import note_stage

    note_stage(req, req.state)


def reasoning_counting_active(req: Request, end_ids: tuple[int, ...]) -> bool:
    """Does this request have a reasoning block to account for at all?

    The ONE predicate behind both "count this token" and "report a count":
    the model has a closing marker AND the RENDERED prompt left generation
    inside an unclosed block (``SamplingParams.opens_in_reasoning``, read off
    the prompt by ``ReasoningParser.prompt_opens_reasoning``). A raw
    completion, a thinking-OFF chat turn, or a model with no reasoning
    markers is False here and reports ``None`` — never a misleading ``0``.
    """
    return bool(end_ids) and bool(req.sampling.opens_in_reasoning)


def count_reasoning_token(
    req: Request,
    token: int,
    end_ids: tuple[int, ...],
    force_close_ids: tuple[int, ...] | None = None,
    tool_call_start_ids: tuple[int, ...] = (),
) -> None:
    """Advance the reasoning state machine for one COMMITTED token.

    ``end_ids`` is the ``</think>`` marker used to DETECT a natural close;
    ``force_close_ids`` (defaults to ``end_ids``) is the sequence the budget
    guard FORCES — a short transition + the marker — advanced one id per step.

    Called from :func:`arbi_serve.engine.run_step.post_token` once per
    committed token — including the token that FINISHES the request, so a
    request truncated at ``max_tokens`` while still inside the block reports
    ``reasoning_token_count == output_token_count`` (every token was
    reasoning) rather than a count that stops short of the truth.

    Counts the closing marker itself, so ``reasoning_tokens`` is the boundary
    INDEX: ``output_token_count − reasoning_tokens`` is exactly the
    visible-answer length. Once the block closes, answer tokens are not
    counted (the ``thinking_closed`` gate at the top makes the post-answer
    steps a single bool read).

    Cost: O(len(end_ids)) integer compares — one for the usual single-id
    ``</think>`` — plus one int increment. No allocation, no decode, no
    device work.
    """
    if force_close_ids is None:
        force_close_ids = end_ids
    if req.thinking_closed or not reasoning_counting_active(req, end_ids):
        return
    # The marker's own tokens (and any forced transition) are pre-answer and count too.
    req.reasoning_tokens += 1
    if req.force_close_thinking:
        # Budget hit: the guard is feeding the transition + marker one id per
        # step. Advance the cursor as each forced id actually commits.
        if (
            req.force_close_pos < len(force_close_ids)
            and token == force_close_ids[req.force_close_pos]
        ):
            req.force_close_pos += 1
        if req.force_close_pos >= len(force_close_ids):
            req.thinking_closed = True
            req.force_close_thinking = False
            req.content_token_start = n_generated(req)
            _latch_first_answer(req)
        return
    # Natural close: the model emitted the marker on its own. Match on the
    # tail of the committed ids so a multi-token marker closes only on its
    # LAST id (the cheap single-id case short-circuits on the first compare).
    n = len(end_ids)
    if token == end_ids[-1] and (n == 1 or tuple(req.output_token_ids[-n:]) == end_ids):
        req.thinking_closed = True
        req.content_token_start = n_generated(req)
        _latch_first_answer(req)
        return
    # A tool call STARTING inside the block ends reasoning for most models (the
    # call IS the turn's output); model-specific — ``tool_call_start_ids`` is ()
    # when there is no tool parser or the model is trained to call mid-reasoning.
    if tool_call_start_ids:
        m = len(tool_call_start_ids)
        if token == tool_call_start_ids[-1] and (
            m == 1 or tuple(req.output_token_ids[-m:]) == tool_call_start_ids
        ):
            req.thinking_closed = True
            req.content_token_start = n_generated(req)
            _latch_first_answer(req)
            return
    budget = req.sampling.thinking_token_budget
    if budget is not None and req.reasoning_tokens >= budget:
        # Arm the guard for the NEXT step; it masks everything but the
        # marker so the model transitions to answering instead of being
        # truncated mid-trace at max_tokens.
        req.force_close_thinking = True
        req.force_close_pos = 0
        thinking_budget_forced.fired = 1


def _find_request(running, request_id: str):
    """The running request ``request_id`` names, by either of its two ids.

    THE CALLER'S OWN ID WINS. ``client_request_id`` is the ``X-Request-ID`` the
    caller supplied and can correlate, so a caller acting on their own request
    is matched first. The fallback is the request's
    :func:`~arbi_serve.server.instance_id.request_uid` -- the id a swimlane bar
    carries. A uid minted by another process (another replica, an earlier boot)
    names nothing here, so it matches nothing rather than whichever request now
    holds the same counter value.
    """
    key = str(request_id)
    for r in running:
        if str(getattr(r, "client_request_id", "") or "") == key:
            return r
    n = local_request_seq(key)
    if n is None:
        return None
    return next((r for r in running if int(getattr(r, "request_id", -1)) == n), None)


def answer_now(eng, *, request_id: str) -> dict:
    """Make one in-flight request stop reasoning and start answering.

    The same transition the thinking budget performs, decided by an operator
    instead of by a token count: arm ``force_close_thinking`` and the
    :class:`ThinkingBudgetGuard` — already attached and already consulted for
    every row on every step — masks the row to the closing marker on the next
    forward pass. The model therefore TRANSITIONS to answering rather than
    being truncated: the response stays well-formed, ``thinking_closed`` flips,
    and ``stamp_first_answer`` fires, so the reasoning→answer boundary is
    recorded exactly as a natural close would record it.

    Refuses rather than no-ops. Three ways this cannot act, and each returns
    the reason instead of a success a caller would believe:

      * the model has no reasoning surface (``think_end_ids`` empty) — the
        guard degrades to pass-through, so arming the flag would change
        nothing and report that it had;
      * the request is not running (matched by the caller's own
        ``X-Request-ID`` first, then by its request uid -- see
        :func:`_find_request`);
      * it is not inside an open thinking block, so there is nothing to close.

    FIELD ORDER IS LOAD-BEARING. This runs on the caller's thread while the
    engine loop reads both fields; writing ``force_close_pos`` first means the
    guard can never observe ``force_close_thinking`` set against a stale
    cursor, which would emit the tail of the marker rather than its head.
    """
    end_ids = tuple(getattr(eng, "think_end_ids", ()) or ())
    if not end_ids:
        return {
            "closed": False,
            "reason": (
                "this model exposes no reasoning surface (no closing marker), so there "
                "is no thinking block to close"
            ),
        }
    scheduler = getattr(eng, "scheduler", None)
    running = list(getattr(scheduler, "running", None) or ())
    req = _find_request(running, request_id)
    if req is None:
        return {"closed": False, "reason": f"request {request_id!r} is not running"}
    if getattr(req, "thinking_closed", False):
        return {"closed": False, "reason": f"request {request_id} has already stopped reasoning"}
    if not (getattr(req, "reasoning_tokens", 0) or 0) > 0:
        return {
            "closed": False,
            "reason": (
                f"request {request_id} has committed no reasoning tokens, so it is not "
                "inside a thinking block"
            ),
        }
    if getattr(req, "force_close_thinking", False):
        return {
            "closed": True,
            "reason": "already closing",
            "reasoning_tokens": req.reasoning_tokens,
        }
    req.force_close_pos = 0
    req.force_close_thinking = True
    thinking_closed_by_operator.fired = 1
    return {"closed": True, "reason": "", "reasoning_tokens": int(req.reasoning_tokens)}


def reported_reasoning_tokens(
    req: Request, end_ids: tuple[int, ...], block_ids: tuple[int, ...] = ()
) -> int | None:
    """``FinishOut.reasoning_token_count`` for a finished request.

    An int — the boundary index — for any request that entered a reasoning
    block, INCLUDING one truncated at ``max_tokens`` before ``</think>`` (the
    count then equals the output length: it was all reasoning). ``None``, and
    therefore ``usage.completion_tokens_details`` omitted entirely, for a
    request that never entered one.

    ``block_ids`` (a block-protocol model's thinking markers, see
    :func:`resolve_block_reasoning_ids`) reports a chat request's own thinking blocks instead,
    where ``0`` is true: the model chose not to think.
    """
    if reasoning_counting_active(req, end_ids):
        return req.reasoning_tokens
    if block_ids and getattr(req.sampling, "is_chat", False):
        return block_reasoning_tokens(generated_token_ids(req), block_ids)
    return None


#: Wrap-up text FORCED ahead of ``</think>`` when a thinking_token_budget is
#: hit, so the hand-off to the answer reads as a sentence rather than a cut.
#: Emitted one token id per step, ahead of the marker.
_TRANSITION = "\n\nI've reached the reasoning budget; let me give the answer now.\n"


def resolve_force_close_ids(
    parser: ReasoningParser | None,
    tokenizer: Tokenizer,
    think_end_ids: tuple[int, ...],
) -> tuple[int, ...]:
    """The token sequence the guard FORCES at the budget: a short transition +
    the ``</think>`` marker, so the hand-off to the answer reads smoothly.

    Distinct from ``think_end_ids`` (which stays the DETECTION marker for a
    natural close): forcing emits this whole sequence one id per step. Falls
    back to the bare marker when there is no reasoning surface. Resolved once
    at build, never on the step path.
    """
    if parser is None or not think_end_ids:
        return tuple(think_end_ids)
    trans = tuple(int(t) for t in tokenizer.encode(_TRANSITION, add_special_tokens=False))
    return trans + tuple(think_end_ids)


def resolve_tool_call_start_ids(tool_parser, tokenizer: Tokenizer) -> tuple[int, ...]:
    """The tool-call START marker (e.g. ``<tool_call>``) as token ids — treated
    as an IMPLICIT reasoning close.

    A tool call is the end of the turn for every checkpoint this server has a
    parser for, so a call emitted while still inside ``<think>`` means the
    reasoning is done — and the budget guard must never force ``</think>`` into
    the middle of a call (the open vLLM bug). Returns ``()`` when the model has
    no tool parser. Resolved once at build, never on the step path.

    A checkpoint trained to call tools MID-reasoning needs the opposite, and
    that is a property of the MODEL: it lives on
    :attr:`~arbi_serve.engine.tool_parsers.base.ToolParser.tool_call_ends_reasoning`,
    the parser that knows which checkpoint this is, not on a server-wide env
    var an operator would have to discover. A parser declaring ``False``
    returns ``()`` here, exactly as a model with no tool parser does, so the
    trace runs to its real ``</think>``.
    """
    if tool_parser is None:
        return ()
    if not getattr(tool_parser, "tool_call_ends_reasoning", True):
        return ()
    trigger = getattr(tool_parser, "tool_call_trigger", "") or ""
    if not trigger:
        return ()
    return tuple(int(t) for t in tokenizer.encode(trigger, add_special_tokens=False))


def force_close_token_id(req, force_close_ids: tuple[int, ...]) -> int | None:
    """The close-marker id to FORCE for this row THIS step, or ``None``.

    The ONE force-close decision, shared by :class:`ThinkingBudgetGuard`'s
    main-path ``__call__`` and its verify-slate form, so the ``K=1`` draw and
    the speculative draw can never disagree about which rows are forcing.
    ``None`` unless the row is in the force-close state AND the marker is not
    already fully emitted — then the id at ``force_close_pos`` (one id per
    step for a multi-token marker). Duck-typed on ``force_close_thinking`` / ``force_close_pos`` so it
    reads a real ``Request``, the SPMD mirror, or the verify shim identically.
    """
    if not getattr(req, "force_close_thinking", False):
        return None
    pos = getattr(req, "force_close_pos", 0)
    if pos >= len(force_close_ids):
        # Whole sequence already emitted; post_token clears the flag next pass.
        return None
    return int(force_close_ids[pos])


def mask_verify_slate_force_close(
    logits: torch.Tensor,  # (K+1, B, W) — masked in place
    requests: Sequence[Request],
    force_close_ids: Sequence[int],
    *,
    window: VocabWindow | None = None,
) -> None:
    """Mask verify position ``p == 0`` to the forced close marker.

    The verify-slate force-close body behind
    :meth:`ThinkingBudgetGuard.apply_to_verify_slate`, kept a free function so
    the mask can be driven against a slate directly in a test. No-op when the
    model has no marker or no row is forcing (one bool read per column).

    Under a vocab-parallel ``window`` every rank still bans its whole slice —
    the ban is the whole vocabulary minus one token — and only the rank that
    OWNS the forced id reopens it. The finite value lands exactly once across
    the group, which is what makes the restriction exact rather than merely
    consistent.
    """
    if not force_close_ids:
        return
    ids = tuple(int(t) for t in force_close_ids)
    lo, hi = window_bounds(window, logits.shape[-1])
    neg_inf = float("-inf")
    for col, req in enumerate(requests):
        if req is None:
            continue
        forced = force_close_token_id(req, ids)
        if forced is None:
            continue
        logits[0, col, :] = neg_inf
        if lo <= forced < hi:
            logits[0, col, forced - lo] = 0.0


class ThinkingBudgetGuard:
    """Logits processor forcing ``</think>`` for over-budget reasoning rows.

    ``think_end_ids`` is the model's closing marker as token ids (resolved
    once at build from the reasoning parser's ``think_end`` string). Empty
    means no reasoning surface — the guard is not attached in that case, but
    an empty tuple degrades to an unconditional pass-through rather than
    forcing a bogus id.
    """

    def __init__(self, think_end_ids: tuple[int, ...], *, vocab_size: int) -> None:
        self._end_ids = tuple(int(t) for t in think_end_ids)
        self._vocab_size = int(vocab_size)

    def __call__(self, logits: torch.Tensor, requests: list[Request]) -> torch.Tensor:
        if not self._end_ids:
            return logits
        # (row_index, forced_token_id) for every row that must emit the next
        # close-marker id this step. Cheap bool read per row; the common
        # case (nobody forcing) exits without touching the logits.
        forced: list[tuple[int, int]] = []
        for i, req in enumerate(requests):
            if req is None:
                continue
            tok = force_close_token_id(req, self._end_ids)
            if tok is not None:
                forced.append((i, tok))
        if not forced:
            return logits
        out = logits.clone()
        neg_inf = float("-inf")
        for i, tok in forced:
            # Mask the whole row to -inf, then reopen only the forced id so no
            # downstream greedy / top-k / stochastic step can select anything
            # else. The forced id is set to a FINITE constant (0.0) rather than
            # its original logit: if the model happened to assign ``</think>``
            # ``-inf`` the row would otherwise be all-``-inf`` and argmax /
            # softmax would be undefined. ``logits`` is ``(K, num_seqs, V)``.
            forced_col = torch.full_like(out[:, i, :], neg_inf)
            forced_col[:, tok] = 0.0
            out[:, i, :] = forced_col
        return out

    def constrains_verify_slate(self, requests: Sequence[Request]) -> bool:
        """Whether any column is mid-force-close this step.

        Keyed on :func:`force_close_token_id`, the same read the mask makes,
        so a row that has already emitted the whole marker answers False.
        """
        if not self._end_ids:
            return False
        return any(
            r is not None and force_close_token_id(r, self._end_ids) is not None for r in requests
        )

    def verify_slate_reads_drafts(self, requests: Sequence[Request]) -> bool:
        """The slate form does not read the draft tokens."""
        del requests
        return False

    def apply_to_verify_slate(
        self,
        logits: torch.Tensor,  # (K+1, B, W) — masked in place
        requests: Sequence[Request],
        drafts_per_row: Sequence[Sequence[int]],
        *,
        window: VocabWindow | None = None,
    ) -> None:
        """Force the next close-marker id at the IMMEDIATE verify position.

        Only ``p == 0`` is constrained: it is the one position whose context
        is the committed history the budget was measured against, so it is
        where the marker must land. Positions ``p > 0`` are the
        post-``</think>`` answer and stay free — the row's drafts at those
        positions are then rejected against the forced marker and exactly
        the marker is emitted.
        """
        del drafts_per_row  # only p == 0 is constrained
        mask_verify_slate_force_close(logits, requests, self._end_ids, window=window)
# ---- thinking_eos_guard.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Redirect a stop id sampled inside an open reasoning block to the closing marker.

Qwen3.8-27B samples ``<|im_end|>`` mid-thought, inside ``<think>``, on long reasoning chains
(QwenLM/Qwen3.8#216; reproduced on bf16, fp8, GGUF and on stock vLLM, with and without
speculation). The request then ends with no answer at all. Every row still inside its reasoning
block has its stop ids' probability moved onto ``</think>``: wherever the model would have ended the
turn, it closes the block instead and answers. A stop sampled there is otherwise always an empty
answer, so the redirect cannot spoil a good one. On by default; ``ARBI_THINKING_EOS_GUARD=0`` turns it
off.

On the served verify step the redirect is recorded in the captured verify graph
(:func:`bind_verify_fold`): the per-row flags ride the step's one staged H2D arena, the graph's own
input ids give the per-position mask, and one kernel (:mod:`.thinking_eos_guard_triton`) rewrites the
slate the head wrote, so every accept consumer reads redirected logits and the step launches nothing
for the guard. Every other draw (``K=1``, a slate the eager head served, the tree, a vocab shard)
runs the processor below: the flags in one pinned non-blocking H2D copy, the mask from the DEVICE
draft tensor, a fixed set of elementwise kernels over the ``1 + len(stops)`` columns. No host read,
no sync on either path; ``thinking_eos_guard_folded`` / ``thinking_eos_guard_eager`` say which ran.
"""

from __future__ import annotations

from collections.abc import Sequence
from typing import TYPE_CHECKING

import torch

from arbi_serve.flag_truth import FiringWindow, path_counter
from arbi_serve.runtime_flags import runtime_flags
from arbi_serve.sampler.sampling_metadata import _staging_empty
from arbi_serve.sampler.vocab_window import window_bounds

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request
    from arbi_serve.sampler.vocab_window import VocabWindow

#: The guard covered at least one row (an open reasoning block) on a served step.
thinking_eos_guard = path_counter("thinking_eos_guard", FiringWindow.SERVE)
#: ...by the redirect recorded in the verify graph (no launch of its own).
_FOLDED = path_counter("thinking_eos_guard_folded", FiringWindow.SERVE)
#: ...by the eager processor (``K=1``, an eager-head slate, the tree, a vocab shard).
_EAGER = path_counter("thinking_eos_guard_eager", FiringWindow.SERVE)


def in_open_reasoning(req) -> bool:
    """Inside a reasoning block the prompt opened and nothing has closed or is closing."""
    return (
        bool(getattr(getattr(req, "sampling", None), "opens_in_reasoning", False))
        and not getattr(req, "thinking_closed", False)
        and not getattr(req, "force_close_thinking", False)
    )


def open_positions(
    row_open: torch.Tensor, draft_ids: torch.Tensor, closers: torch.Tensor
) -> torch.Tensor:
    """``(K+1, B)`` bool: slate position ``p`` of column ``b`` is still inside the block.

    ``row_open`` ``(B,)`` is the committed history's state; a position past a draft that closed the
    block or ended the turn (``draft_ids[:p]`` holds one of ``closers``) is not.
    """
    hit = torch.isin(draft_ids, closers)  # (K, B)
    closed = torch.cumsum(hit.to(torch.int32), dim=0) > 0
    closed = torch.cat([torch.zeros_like(closed[:1]), closed], dim=0)  # (K+1, B)
    return row_open[None, :] & ~closed


def redirect_stop_mass(logits: torch.Tensor, mask: torch.Tensor, ids: torch.Tensor) -> None:
    """In place on ``(P, B, V)`` where ``mask`` ``(P, B)``: ``logit[ids[0]] = logsumexp(logit[ids])``, the rest -inf."""
    sel = logits.index_select(-1, ids)  # (P, B, 1 + S)
    lse = torch.logsumexp(sel.float(), dim=-1).to(sel.dtype)
    new = torch.cat(
        [
            torch.where(mask, lse, sel[..., 0]).unsqueeze(-1),
            sel[..., 1:].masked_fill(mask.unsqueeze(-1), float("-inf")),
        ],
        dim=-1,
    )
    logits.index_copy_(-1, ids, new)


class ThinkingEosGuard:
    """Logits processor: stop-id mass inside an open reasoning block goes to ``</think>``.

    Attached when the model has a single-id closing marker. One bool read per row while no row is
    inside a block. Its slate form takes the verify's device draft tensor (``takes_draft_ids``), so it
    never asks for the drafts on the host.
    """

    takes_draft_ids = True

    def __init__(self, end_id: int, stop_ids: Sequence[int]) -> None:
        self._end = int(end_id)
        self._stops = tuple(int(t) for t in stop_ids if int(t) != int(end_id))
        self._ids: dict[tuple, torch.Tensor] = {}

    def _cached(self, key: tuple, vals: Sequence[int], device: torch.device) -> torch.Tensor:
        """An id tensor on ``device``, built once with a pinned async copy (never a sync)."""
        if key not in self._ids:
            host = _staging_empty(len(vals), dtype=torch.int64, device=device)
            host.copy_(torch.tensor(list(vals), dtype=torch.int64))
            self._ids[key] = host.to(device, non_blocking=True)
        return self._ids[key]

    def _id_tensor(self, device: torch.device, lo: int = 0) -> torch.Tensor:
        return self._cached(
            ("ids", device, lo), [t - lo for t in (self._end, *self._stops)], device
        )

    def _flags(
        self, requests: Sequence[Request], device: torch.device
    ) -> tuple[torch.Tensor, int] | None:
        """The ``(B,)`` open-block flags on ``device`` (one pinned async copy), or None when no row is open."""
        flags = [r is not None and in_open_reasoning(r) for r in requests]
        n = sum(flags)
        if not n:
            return None
        host = _staging_empty(len(flags), dtype=torch.bool, device=device)
        host.copy_(torch.tensor(flags, dtype=torch.bool))
        return host.to(device, non_blocking=True), n

    def _engaged(self, requests: Sequence[Request]) -> bool:
        if not self._stops or not runtime_flags().thinking_eos_guard:
            return False
        return any(r is not None and in_open_reasoning(r) for r in requests)

    def __call__(self, logits: torch.Tensor, requests: Sequence[Request]) -> torch.Tensor:
        if not self._stops or not runtime_flags().thinking_eos_guard:
            return logits
        got = self._flags(requests, logits.device)
        if got is None:
            return logits
        row_open, n = got
        out = logits.clone()
        redirect_stop_mass(
            out, row_open[None, :].expand(out.shape[0], -1), self._id_tensor(out.device)
        )
        thinking_eos_guard.fired = _EAGER.fired = 1
        return out

    async def accept_token(self, request: Request, token: int) -> None:
        del request, token

    def constrains_verify_slate(self, requests: Sequence[Request]) -> bool:
        return self._engaged(requests)

    def verify_slate_reads_drafts(self, requests: Sequence[Request]) -> bool:
        """The slate form reads the DEVICE draft tensor, never the host lists."""
        del requests
        return False

    def apply_to_verify_slate(
        self,
        logits: torch.Tensor,  # (K+1, B, W) — modified in place
        requests: Sequence[Request],
        drafts_per_row: Sequence[Sequence[int]],
        *,
        window: VocabWindow | None = None,
        draft_ids: torch.Tensor | None = None,  # (K, B) device drafts, bucket-column order
    ) -> None:
        """Position ``p`` is inside the block until a draft before it closed it or ended the turn."""
        if not self._stops or not runtime_flags().thinking_eos_guard:
            return
        dev = logits.device
        got = self._flags(requests, dev)
        if got is None:
            return
        row_open, n = got
        closers = self._id_tensor(dev)
        if draft_ids is None:
            # A verify path that hands no device drafts already holds them on the host.
            k = logits.shape[0] - 1
            rows = [[(list(d) + [-1] * k)[p] for d in drafts_per_row] for p in range(k)]
            host = _staging_empty(k * len(drafts_per_row), dtype=torch.int64, device=dev)
            host.copy_(torch.tensor(rows, dtype=torch.int64).reshape(-1))
            draft_ids = host.to(dev, non_blocking=True).view(k, len(drafts_per_row))
        mask = open_positions(row_open, draft_ids[: logits.shape[0] - 1].to(dev), closers)
        lo, hi = window_bounds(window, logits.shape[-1])
        ids = (self._end, *self._stops)
        if all(lo <= t < hi for t in ids):
            redirect_stop_mass(logits, mask, self._id_tensor(dev, lo))
        else:
            # A vocab-parallel shard holds only part of the ids, so the mass cannot move across ranks:
            # each rank bans the stop ids it owns, and the row samples its next-best token instead.
            own = [t - lo for t in self._stops if lo <= t < hi]
            if own:
                cols = self._cached(("own", dev, lo), own, dev)
                sel = logits.index_select(-1, cols)
                logits.index_copy_(-1, cols, sel.masked_fill(mask.unsqueeze(-1), float("-inf")))
        thinking_eos_guard.fired = _EAGER.fired = 1

    def note_folded(self, requests: Sequence[Request]) -> None:
        """Count the rows the verify graph's recorded redirect covered this step."""
        if any(r is not None and in_open_reasoning(r) for r in requests):
            thinking_eos_guard.fired = _FOLDED.fired = 1


def bind_verify_fold(vb, procs: Sequence[object]) -> None:
    """Arm the verify graphs' recorded redirect on ``vb`` for the chain's guard, before any capture.

    Left unbound (every slate eager) when the pool has no logits scratch or the ids exceed the
    kernel's column slots.
    """
    from arbi_serve.sampler.thinking_eos_guard_triton import MAX_IDS

    guard = next((p for p in procs if isinstance(p, ThinkingEosGuard)), None)
    ids = (guard._end, *guard._stops) if guard is not None and guard._stops else ()
    if not ids or len(ids) > MAX_IDS or getattr(vb, "eos_guard_ids", None) is None:
        return
    vb.eos_guard_ids[: len(ids)].copy_(torch.tensor(ids, dtype=torch.int64))
    vb.eos_guard, vb.eos_guard_n_ids = guard, len(ids)


def fold_row_flags(eng, requests: Sequence[Request]) -> list[int] | None:
    """The per-row open flags to stage for the verify graph, or None when this step stays eager.

    The recorded redirect runs before the whole chain, so it is taken only when no processor ahead
    of the guard constrains the slate (then the two orders are the same map); a tree's slots are
    not a chain, so a tree step keeps the processor too.
    """
    from arbi_serve.spec_decode.tree_spec import active_tree_spec

    vb = getattr(eng, "verify_buffers", None)
    guard = getattr(vb, "eos_guard", None)
    if guard is None or not runtime_flags().thinking_eos_guard or active_tree_spec() is not None:
        return None
    for proc in eng.sampler.logits_processors:
        if proc is guard:
            return [int(r is not None and in_open_reasoning(r)) for r in requests]
        if proc.constrains_verify_slate(requests):
            return None
    return None


def folded_guard(eng, logits: torch.Tensor) -> ThinkingEosGuard | None:
    """The guard whose redirect the replay already applied to ``logits``, else None."""
    vb = getattr(eng, "verify_buffers", None)
    if vb is None or not getattr(vb, "eos_guard_folded", False):
        return None
    if logits.data_ptr() != vb.sc_verify_logits.data_ptr():
        return None
    return vb.eos_guard


def restore_raw_columns(eng, logits: torch.Tensor, scores: torch.Tensor) -> None:
    """Put the pre-redirect columns back into the logprob lane's copy of a folded slate."""
    if folded_guard(eng, logits) is None:
        return
    from arbi_serve.sampler.thinking_eos_guard_triton import MAX_IDS

    vb = eng.verify_buffers
    s, b, n = int(scores.shape[0]), int(scores.shape[1]), int(vb.eos_guard_n_ids)
    stash = vb.eos_guard_stash[: s * b * MAX_IDS].view(s, b, MAX_IDS)[..., :n]
    scores.index_copy_(-1, vb.eos_guard_ids[:n], stash)


def record_verify_fold(vb, batch: int, seq_len: int) -> None:
    """Rewrite the slot-major slate rows in ``vb.sc_verify_logits`` (recorded into the verify graph)."""
    if not getattr(vb, "eos_guard_n_ids", 0):
        return
    from arbi_serve.sampler.thinking_eos_guard_triton import redirect_slate

    redirect_slate(
        vb.sc_verify_logits[: batch * seq_len], vb.input_ids, vb.eos_guard_open,
        vb.eos_guard_ids, vb.eos_guard_stash, batch=batch, seq_len=seq_len,
        n_ids=vb.eos_guard_n_ids,
    )  # fmt: skip
# ---- thinking_eos_guard_triton.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The thinking EOS guard's verify-slate redirect as one kernel, recorded in the verify graph.

One program per slate row ``(s, b)`` of the slot-major ``(S*B, V)`` verify logits: it reads the
row's open-block flag, decides from the graph's own input ids (``ids[b*S + 1 + j]`` is draft ``j``)
whether a draft before slot ``s`` closed the block or ended the turn, saves the ``1 + stops``
affected columns for the logprob lane, and writes ``logit[end] = logsumexp(logit[end, stops])``,
``logit[stops] = -inf`` where the slot is still inside the block. Same arithmetic as
:func:`~arbi_serve.sampler.thinking_eos_guard.redirect_stop_mass` (fp32, max-shifted, libdevice
``exp``/``log``, cast back); ``tests/test_thinking_eos_guard_fold_gpu.py`` holds it to
``torch.equal`` against that chain.
"""

from __future__ import annotations

from functools import lru_cache

import torch

#: Column slots the guard reserves: ``</think>`` plus up to seven stop ids.
MAX_IDS = 8


@lru_cache(maxsize=1)
def _kernel():
    import triton
    import triton.language as tl
    from triton.language.extra import libdevice

    @triton.jit(do_not_specialize=["B", "S", "STRIDE"])
    def _eos_redirect(
        LOGITS, IN_IDS, OPEN, IDS, STASH, B, S, STRIDE,
        N_IDS: tl.constexpr, BLOCK_S: tl.constexpr, BLOCK_E: tl.constexpr,
    ):  # fmt: skip
        pid = tl.program_id(0)
        s = pid // B
        b = pid - s * B
        e = tl.arange(0, BLOCK_E)
        em = e < N_IDS
        col = tl.load(IDS + e, mask=em, other=-1)
        row = LOGITS + pid.to(tl.int64) * STRIDE
        x = tl.load(row + col, mask=em, other=float("-inf"))
        tl.store(STASH + pid * BLOCK_E + e, x, mask=em)
        j = tl.arange(0, BLOCK_S)
        tok = tl.load(IN_IDS + b * S + 1 + j, mask=j < s, other=-1).to(tl.int64)
        hit = (tok[:, None] == col[None, :]) & (col[None, :] >= 0)
        closed = tl.sum(hit.to(tl.int32), axis=1)
        closed = tl.sum(closed, axis=0)
        if (tl.load(OPEN + b) != 0) & (closed == 0):
            xf = x.to(tl.float32)
            m = tl.max(xf, axis=0)
            m = tl.where(m == float("-inf"), 0.0, m)
            lse = libdevice.log(tl.sum(libdevice.exp(xf - m), axis=0)) + m
            new = tl.where(e == 0, lse, float("-inf")).to(x.dtype)
            tl.store(row + col, new, mask=em)

    return _eos_redirect


def redirect_slate(
    logits: torch.Tensor,  # (S*B, V) slot-major, written in place
    input_ids: torch.Tensor,  # (>= B*S,) flat verify input ids, row-major (b, s)
    row_open: torch.Tensor,  # (>= B,) int32, nonzero = inside an open reasoning block
    ids: torch.Tensor,  # (MAX_IDS,) int64: [end, *stops, ...]
    stash: torch.Tensor,  # (>= S*B*MAX_IDS,) logits dtype: the pre-redirect columns
    *,
    batch: int,
    seq_len: int,
    n_ids: int,
) -> None:
    """Launch the redirect over the ``seq_len * batch`` slate rows (graph-capturable, no host read)."""
    import triton

    rows = int(seq_len) * int(batch)
    _kernel()[(rows,)](
        logits, input_ids, row_open, ids, stash, int(batch), int(seq_len), logits.stride(0),
        N_IDS=int(n_ids), BLOCK_S=max(triton.next_power_of_2(int(seq_len)), 2),
        BLOCK_E=MAX_IDS, num_warps=1,
    )  # fmt: skip
# ---- tool_grammar.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Build an xgrammar *structural tag* that constrains tool-call generation.

This is the enforcement half of tool calling (the parsing half lives in
:mod:`arbi_serve.engine.tool_parsers`). Given the request's ``tools`` and
``tool_choice`` it builds an ``xgrammar.structural_tag.StructuralTag`` that
forces the model's output into the *exact* surface its
:class:`~arbi_serve.engine.tool_parsers.base.ToolParser` reads back — so
enforce and parse never drift.

The per-family wire format (the ``<function=>`` Qwen XML vs Hermes JSON body,
the trigger, the scaffolding) is owned by the serving model's ``ToolParser``,
resolved from its chat template at engine build and passed in by the caller
(:class:`~arbi_serve.sampler.xgrammar_grammar_source.ModelGrammar`). This
module only owns the family-agnostic ``tool_choice`` scaffolding:

  * ``"auto"`` / ``None`` → ``TriggeredTagsFormat`` on the family trigger: the
    model may emit plain text OR open a tool call; once opened it is forced
    valid + parseable.
  * ``"required"`` → ``TriggeredTagsFormat(at_least_one=True)``: same shape but
    at least one valid call; parallel calls + inter-call text allowed.
  * named → ``TagsWithSeparatorFormat`` restricted to that function with
    ``stop_after_first``: exactly one call to the named function.
  * ``"none"`` → no grammar (handled by the caller; never reaches here).

xgrammar is imported lazily so importing this module never needs it present.
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from arbi_serve.engine.tool_parsers.base import ToolParser

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


def _resolve_parser(parser: ToolParser | None) -> ToolParser:
    """The explicit parser, else the Hermes-JSON default."""
    if parser is not None:
        return parser
    from arbi_serve.engine.tool_parsers import HermesJsonToolParser

    return HermesJsonToolParser()


def _resolve_choice(tool_choice: Any) -> tuple[str, str | None]:
    """Map ``tool_choice`` → ``(mode, only_name)``.

    ``mode`` ∈ ``{"auto","required","named"}``; ``only_name`` is the single
    permitted function for ``named`` (else ``None``). ``"none"`` is filtered
    by the caller, so anything falsy/auto-ish maps to ``"auto"``.
    """
    if isinstance(tool_choice, dict):
        fn = tool_choice.get("function")
        name = fn.get("name") if isinstance(fn, dict) else None
        if name:
            return "named", name
        return "auto", None
    if tool_choice == "required":
        return "required", None
    return "auto", None


def _function_name_and_params(tool: Any) -> tuple[str | None, dict]:
    """Pull ``(name, parameters)`` from an engine ``ToolSpec`` or a dict."""
    fn = getattr(tool, "function", None)
    if fn is None and isinstance(tool, dict):
        fn = tool.get("function")
    name = getattr(fn, "name", None)
    if name is None and isinstance(fn, dict):
        name = fn.get("name")
    params = getattr(fn, "parameters", None)
    if params is None and isinstance(fn, dict):
        params = fn.get("parameters")
    if not isinstance(params, dict):
        params = {"type": "object", "properties": {}}
    return name, params


def build_tool_structural_tag(
    tools: Any, tool_choice: Any, parser: ToolParser | None = None
) -> Any | None:
    """Build the ``StructuralTag`` for ``(tools, tool_choice)``, or ``None``.

    The tag set + trigger come from ``parser`` (the serving model's parser;
    ``None`` is the Hermes-JSON default), so the enforced surface matches that model's own tool-call
    format. Returns ``None`` when there is nothing to enforce (no tools, or no
    tool matched a named choice). Per-tool schema problems degrade to permissive.

    The tag set is built in ONE call
    (:meth:`~arbi_serve.engine.tool_parsers.base.ToolParser.build_tool_tags`)
    rather than per tool, because how many tags a request needs is a
    family property: Hermes / Qwen3-Coder put one call per marker span, so
    each tool is its own alternative tag, while NemotronVoiceChat wraps a
    JSON ARRAY of calls in one ``<TOOLCALL>`` span and therefore needs a
    single tag covering every offered tool. The default implementation is
    still one ``build_tool_body_tag`` per tool, so the two existing
    families' tag sets are unchanged.
    """
    if not tools:
        return None
    from xgrammar import structural_tag as st

    p = _resolve_parser(parser)
    mode, only_name = _resolve_choice(tool_choice)
    specs: list[tuple[str, dict]] = []
    for tool in tools:
        name, params = _function_name_and_params(tool)
        if not name:
            continue
        if only_name is not None and name != only_name:
            continue
        specs.append((name, params))
    if not specs:
        return None
    tags = p.build_tool_tags(st, specs)
    if not tags:
        return None

    trigger = p.tool_call_trigger
    if mode == "auto":
        fmt = st.TriggeredTagsFormat(triggers=[trigger], tags=tags)
    elif mode == "named":
        fmt = st.TagsWithSeparatorFormat(
            tags=tags, separator="", at_least_one=True, stop_after_first=True
        )
    else:  # required — ≥1 call, parallel calls + inter-call text allowed
        fmt = st.TriggeredTagsFormat(triggers=[trigger], tags=tags, at_least_one=True)
    return st.StructuralTag(format=fmt)


def tool_structural_tag_json(
    tools: Any, tool_choice: Any, parser: ToolParser | None = None
) -> str | None:
    """Convenience: the built tag as a JSON string (the compile/cache key
    source), or ``None`` when nothing to enforce."""
    tag = build_tool_structural_tag(tools, tool_choice, parser)
    if tag is None:
        return None
    return tag.model_dump_json()
# ---- tool_grammar_fallback.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Tool-grammar degrade ladder: a schema xgrammar cannot compile costs that
tool its full schema, never the request its grammar.

Per JSON-schema node of the tool structural tag: as built -> structural
skeleton (property names, ``required``, ``const`` pins) -> any JSON value.
Only when the degraded tag still fails does the request run unconstrained.
Every rung below "as built" logs the request's reason at WARNING and counts
``arbi_serve.tool_grammar.fallback_total{reason}`` (``skeleton`` /
``permissive`` / ``unconstrained``). The happy path costs nothing: the ladder
runs only after a compile raised, and its outcome is cached by grammar key.
"""

from __future__ import annotations

import asyncio
import json
import logging
import threading
from collections import Counter, OrderedDict
from typing import Any

from arbi_serve.engine.request import ResponseFormat
from arbi_serve.sampler.xgrammar_capability import UnsupportedXGrammarCompiler

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

#: ``StatsMsg.counter_deltas`` key prefix; the suffix is the reason.
FALLBACK_DELTA = "tool_grammar_fallback:"
_RANK = {"skeleton": 0, "permissive": 1, "unconstrained": 2}

_TOTALS: Counter[str] = Counter()
_LOCK = threading.Lock()
#: grammar key -> (degraded rf or None, reason, detail). Pure in its key.
_PLANS: OrderedDict[str, tuple[ResponseFormat | None, str, str]] = OrderedDict()
_PLANS_MAX = 256


def fallback_totals() -> dict[str, int]:
    """Lifetime fallback counts by reason (the heartbeat diffs these)."""
    with _LOCK:
        return dict(_TOTALS)


def skeleton_schema(node: Any) -> Any:
    """The shape of ``node`` with every leaf loosened to any value."""
    if not isinstance(node, dict):
        return {}
    if "const" in node:
        return {"const": node["const"]}
    props = node.get("properties")
    if not isinstance(props, dict) or not props:
        return {}
    out: dict[str, Any] = {
        "type": "object",
        "properties": {k: skeleton_schema(v) for k, v in props.items()},
    }
    req = [r for r in node.get("required") or () if isinstance(r, str) and r in props]
    if req:
        out["required"] = req
    if isinstance(node.get("additionalProperties"), bool):
        out["additionalProperties"] = node["additionalProperties"]
    return out


def _first_line(e: BaseException) -> str:
    return (str(e).strip().splitlines() or [type(e).__name__])[0][:300]


def _compile_error(fmt: dict) -> str | None:
    import xgrammar as xg

    try:
        xg.Grammar.from_structural_tag(json.dumps({"type": "structural_tag", "format": fmt}))
    except Exception as e:  # noqa: BLE001 — the error IS the answer
        return _first_line(e)
    return None


def degrade_structural_tag(tag_json: str) -> tuple[str, str, list[str]]:
    """Loosen every non-compiling JSON-schema node of a structural tag.

    Returns ``(tag_json, worst_reason, notes)``; ``worst_reason`` is ``""``
    when every node compiled as built.
    """
    tag = json.loads(tag_json)
    worst, notes = "", []

    def walk(node: Any, label: str) -> None:
        nonlocal worst
        if isinstance(node, list):
            for v in node:
                walk(v, label)
            return
        if not isinstance(node, dict):
            return
        label = str(node.get("begin") or label).strip()
        if node.get("type") == "json_schema" and "json_schema" in node:
            err = _compile_error(node)
            if err is None:
                return
            node["json_schema"] = skeleton_schema(node["json_schema"])
            reason = "skeleton" if _compile_error(node) is None else "permissive"
            if reason == "permissive":
                node["json_schema"] = True
            if _RANK[reason] > _RANK.get(worst, -1):
                worst = reason
            notes.append(f"{label or '<root>'}: {reason} ({err})")
            return
        for v in node.values():
            walk(v, label)

    walk(tag, "")
    return json.dumps(tag), worst, notes


def _plan(rf: ResponseFormat, err: BaseException) -> tuple[ResponseFormat | None, str, str]:
    detail = _first_line(err)
    if rf.type != "structural_tag" or not rf.structural_tag:
        return None, "unconstrained", detail
    try:
        tag_json, reason, notes = degrade_structural_tag(rf.structural_tag)
    except Exception as e:  # noqa: BLE001 — a ladder bug must not 500 the request
        return None, "unconstrained", f"{detail}; degrade failed: {_first_line(e)}"
    if not reason:  # every node compiles alone; the combination does not
        return None, "unconstrained", detail
    return ResponseFormat(type="structural_tag", structural_tag=tag_json), reason, "; ".join(notes)


def _remember(key: str, plan: tuple[ResponseFormat | None, str, str]) -> None:
    with _LOCK:
        _PLANS[key] = plan
        _PLANS.move_to_end(key)
        while len(_PLANS) > _PLANS_MAX:
            _PLANS.popitem(last=False)


def _report(reason: str, detail: str) -> None:
    with _LOCK:
        _TOTALS[reason] += 1
    logger.warning(
        "tool-grammar fallback=%s: %s%s",
        reason,
        detail,
        "; proceeding without enforcement (output parser still applies)"
        if reason == "unconstrained"
        else "",
    )


async def compile_tool_grammar(
    processor: Any, rf: ResponseFormat
) -> tuple[Any, ResponseFormat] | None:
    """``(compiled, rf_used)`` for a tool grammar, degraded as needed; ``None``
    means run unconstrained. Async twin of :func:`compile_tool_grammar_sync`."""
    key = processor._cache_key(rf)
    with _LOCK:
        plan = _PLANS.get(key)
    if plan is None:
        try:
            return await processor.get_or_compile(rf), rf
        except UnsupportedXGrammarCompiler:
            raise
        except Exception as e:  # noqa: BLE001 — degrade, never 500 a tool call
            plan = await asyncio.to_thread(_plan, rf, e)
            _remember(key, plan)
    degraded, reason, detail = plan
    if degraded is not None:
        try:
            compiled = await processor.get_or_compile(degraded)
        except UnsupportedXGrammarCompiler:
            raise
        except Exception as e:  # noqa: BLE001
            plan = (None, "unconstrained", f"{detail}; degraded grammar: {_first_line(e)}")
            _remember(key, plan)
            _, reason, detail = plan
        else:
            _report(reason, detail)
            return compiled, degraded
    _report(reason, detail)
    return None


def compile_tool_grammar_sync(
    processor: Any, rf: ResponseFormat
) -> tuple[Any, ResponseFormat] | None:
    """Synchronous :func:`compile_tool_grammar` (SPMD rank-local build)."""
    key = processor._cache_key(rf)
    with _LOCK:
        plan = _PLANS.get(key)
    if plan is None:
        try:
            return processor.get_or_compile_sync(rf), rf
        except UnsupportedXGrammarCompiler:
            raise
        except Exception as e:  # noqa: BLE001 — degrade identically on all ranks
            plan = _plan(rf, e)
            _remember(key, plan)
    degraded, reason, detail = plan
    if degraded is not None:
        try:
            compiled = processor.get_or_compile_sync(degraded)
        except UnsupportedXGrammarCompiler:
            raise
        except Exception as e:  # noqa: BLE001
            plan = (None, "unconstrained", f"{detail}; degraded grammar: {_first_line(e)}")
            _remember(key, plan)
            _, reason, detail = plan
        else:
            _report(reason, detail)
            return compiled, degraded
    _report(reason, detail)
    return None


def emit_fallback_deltas(eng: Any, accumulate: Any) -> None:
    """Heartbeat hook: per-tick fallback deltas onto the counter bridge
    (process mode) and the engine's own metrics (in-process mode). The first
    call on an engine only baselines; the heartbeat ticks before serving."""
    totals = fallback_totals()
    seen = getattr(eng, "_tool_grammar_fallback_emitted", None)
    eng._tool_grammar_fallback_emitted = totals
    if seen is None:  # first tick baselines: the totals are process-wide
        return
    metrics = getattr(eng, "metrics", None)
    for reason, n in totals.items():
        d = n - seen.get(reason, 0)
        if d <= 0:
            continue
        accumulate(FALLBACK_DELTA + reason, d)
        add = getattr(metrics, "add_tool_grammar_fallback", None)
        if add is not None:
            try:
                add(reason=reason, n=float(d))
            except Exception:  # noqa: BLE001 — observability never raises into the loop
                logger.debug("tool-grammar fallback metric failed", exc_info=True)
# ---- topc_mask.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Fanned-out top_k/top_p/min_p mask for the small-batch decode row.

WHY THIS EXISTS. :func:`~arbi_serve.sampler.topk_topp_triton.apply_top_k_top_p_triton`
(the vendored Qrita pivot kernel) launches ``NUM_PROGRAMS = min(num_sm,
batch_size)``. Its cost is therefore set by the SLATE HEIGHT, not by the
work: at the ``B = 1`` the speculative drafter serves it is ONE CTA of 128
threads running a multi-pass ternary pivot search over the whole vocabulary
while 127 SMs idle. Measured live (RTX 4090, Qwen3.8-27B, ``V = 248320``,
``K = 4``, ``B = 1``): **276 us** per drafter slot, x K of them per step, and
**271 us** for the ``(K+1) * B = 5``-row verify mask. The row it reads is
993 KB; at ~1 TB/s that is ~1 us.

THOSE ARE K=4 / B=1 FIGURES AND THE SERVED SLATE IS NEITHER. At the served
``K=7`` and ``--max-batch 8`` the verify mask is ``(K+1) * B = 64`` rows, so
the pivot kernel launches 64 programs rather than 5 and the idle-SM pathology
this module exists to delete is largely gone on the verify leg — the drafter
leg, still one row per slot, keeps it in full. Neither the crossover nor the
per-step totals above have been re-profiled at the served slate height.

The verify mask is on the BASELINE path — every request pays it, greedy or
stochastic, no flag — but it is the GATHERED verify tail, so a TP>1 config
running ``sharded_verify`` (default ON) does not reach it: that path never
builds a dense ``(rows, V)`` row to mask, it compacts to per-shard candidates
first. The 271 us is the TP1 cost, which is the configuration it was profiled
on. The drafter mask needs ``ARBI_TRUE_STOCHASTIC_DRAFT != 0``.

WHAT REPLACES IT. Two launches, both gridded ``(rows x vocab-chunk)`` so one
row occupies every SM:

  1. :func:`~arbi_serve.sampler._topc_kernel._topc_partials_kernel` — each
     program ``tl.topk``-selects the top-``capacity`` of its own contiguous
     vocab chunk. This is the only pass that reads all of ``V``.
  2. :func:`~arbi_serve.sampler._topc_kernel._topc_mask_kernel` — each
     program re-derives the row's global top-``capacity`` from the level-1
     partials (their union provably contains it), turns the filter chain
     into ONE scalar threshold, and applies ``keep iff logit >= T`` to its
     own chunk, writing only the dropped lanes.

THE NUCLEUS, AND THE THIRD LAUNCH. One row shape has no bound a candidate set
can supply on its own: ``top_p`` active with ``top_k`` DISABLED — the standard
OpenAI request shape, and every row of a checkpoint whose
``generation_config.json`` ships no ``top_k``. The nucleus renormalises over
the WHOLE vocabulary and its depth is set by the row's flatness, so it can run
past any capacity.

Two things make it representable anyway. The denominator is real: the level-1
pass also emits each chunk's softmax mass in its own max's units, which the
level-2 reduction rescales onto the row max, so the nucleus is taken against
the row's true normaliser and not against the candidates — for the price of
the ``exp`` on bytes the selection was already reading. And the row is served
only when the candidates PROVABLY contain the boundary, which the threshold
kernel decides per row. A row it cannot claim keeps its ``top_p`` in a
device-written residual and reaches
:func:`~arbi_serve.sampler.topk_topp_triton.apply_top_k_top_p_triton`
UNMASKED; a served row's residual reads ``1.0``, the DISABLED encoding, so
that launch walks past it. The escalation is unconditional in SHAPE and
selective in EFFECT, which is what keeps the chain capturable: nothing about
any launch depends on a host-visible value.

That escalation also takes over ``min_p`` and the fused LSE whenever it is
built, because both must observe the FINAL kept set and an escalated row is
not masked until it runs.

The nucleus path runs at its own capacity (:data:`_NUCLEUS_CAPACITY`), which a
``top_k``-capped slate never pays: holding a served ``top_k`` and holding a
whole nucleus are different requirements, and the mask's cost is linear in the
capacity.

The threshold is recomputed redundantly by every masking program on purpose:
a grid-``(rows,)`` kernel to compute it once would reintroduce exactly the
single-CTA step this design exists to delete, and the programs run
concurrently so the redundancy is free in wall time.

WHY A THRESHOLD, NOT A KEPT-SET. top_k, top_p and min_p are all
"keep the high tail" rules, so each is a cut at a VALUE:

  * top_k → the ``k``-th largest logit;
  * top_p → the smallest value whose descending prefix reaches ``p``, over
    the top_k survivors, renormalised;
  * min_p → ``row_max + log(min_p)`` (the logit-space rewrite the eager
    chain and the pivot kernel both use).

``T`` is the largest of the three and the kept set is ``{logit >= T}``.
Placing each cut AT a real logit value rather than strictly between two is
what makes this agree with the pivot kernel on an exact tie: both keep the
WHOLE tie group at the cut (the Qrita mask pass admits the full duplicate
group, ``_topk_topp_kernel``'s sixth pass).

WHAT IS AND IS NOT BIT-IDENTICAL. The masked ``(rows, V)`` tensor is
bit-identical to the pivot kernel's — same kept set, and kept lanes are never
written so they carry their input bits. ``lse_out`` is NOT, and cannot be: the
pivot kernel accumulates ``sum(exp(logit - max))`` serially inside one
program, and a mask that fans the row across programs necessarily groups that
sum differently. Measured within a few fp32 ULPs (pinned at 8 in
``tests/_topc_mask_interpret_harness.py``; 0 across the whole served grid at
``V = 248320`` on a 4090). That is the SAME drift class the fused-LSE epilogue
already ships with against a separate ``torch.logsumexp``, and its only
consumer effect is that a verify accept can flip at an exact-tie boundary —
the output distribution is unchanged (Leviathan-2023 Thm 1 holds for the
target law; the accept test is comparing the same two real numbers).

EXACTNESS OF THE NUCLEUS BOUNDARY. A nucleus boundary is where a cumulative
mass crosses ``p``, and two exact statements of that rule still disagree about
the crossing when they sum the same terms in different orders and the boundary
token's own mass is comparable to the summation error. A flipped boundary
token is a different sampled distribution, not a rounding detail, so the row
is served only when the crossing clears :data:`_NUCLEUS_MARGIN` of relative
slack on BOTH sides — no reordering smaller than that can move the cut — and
handed to the pivot kernel otherwise. Serving fewer rows is the safe
direction; serving one whose boundary is in doubt is not.

EXACTNESS OF THE SELECTION. It is exact, not heuristic: a chunk can
contribute at most ``capacity`` members to the global top-``capacity``, so
the top-``capacity`` of the union of the per-chunk top-``capacity`` sets IS
the global one. A chunk too wide for one tile is folded by a running merge
inside the program, which is the same argument applied again.

The one boundary this cannot see is a tie group at the ``k``-th logit long
enough to run PAST ``capacity`` entries: top_p's renormaliser would then sum
a truncated top_k set and close the nucleus early. It needs
``capacity - k + 1`` bit-identical fp32 logits at the cut, which an fp32
lm_head over a 248k vocabulary does not produce — but "does not happen" is a
claim, so the behaviour is recorded rather than assumed away
(``test_a_tie_group_wider_than_the_capacity_is_a_known_boundary``). The top_k
cut itself is unaffected: it is a value, so the dense pass keeps every tied
entry wherever it sits in the vocabulary.

CAPTURE SAFETY. ``capacity``, ``split``, ``chunk`` and every block size are
launch constants and the two grids are static in ``(rows, V)``. There is no
host readback, no data-dependent shape and no branch on a device value, so
the pair records into a cudagraph and replays against whatever ``copy_()``
last wrote into the parameter buffers. Because ``capacity`` is BAKED at
record time, a slate it cannot represent must be kept off the captured
chain by the routing layer — :func:`topc_mask_eligible` is the single
predicate both the router and the live dispatch ask. Whether the escalation
was RECORDED is the same class of fact and rides the same predicate
(``nucleus=``): a launch cannot be added by ``copy_()`` either."""

from __future__ import annotations

import torch

from arbi_serve.sampler._triton_util import next_pow2, num_sm

NEG_INF = float("-inf")

#: Width budget for the level-2 candidate tile, and the ONE knob the geometry
#: is derived from. Level 2 re-selects over ``split * capacity`` partials
#: INSIDE EVERY masking program, so an unbounded ``split`` makes that
#: redundant tile the dominant cost — measured on a 4090 at ``V = 248320``,
#: ``capacity = 64`` with ``split = 243`` (a 16384-wide tile) ran at 0.9x the
#: pivot kernel it replaces, i.e. it lost. Deriving ``split`` from this budget
#: instead of from a chunk width makes that regression unreachable at ANY
#: vocabulary size, rather than merely absent at the one that was measured.
#:
#: The shipped value resolves, at ``capacity = 32``, to ``split = 128`` — one
#: wave on a 128-SM device for a SINGLE decode row, which is the geometry it
#: was chosen for. It was the fastest cell of the ``capacity x geometry``
#: sweep, but that sweep was run at ``rows = 1`` and ``rows = 5`` (a K=4
#: verify slate), and the served verify slate is ``(K+1) * B = 64`` rows.
#: Above a wave the one-wave argument stops applying, so the optimum at 48 and
#: 64 rows is not known to be this one. *Needs: the ``capacity x geometry``
#: sweep re-run at rows 48 and 64 on 27B exl3 4.0bpw, DFlash2 K=7,
#: --max-batch 8, one 4090.* The drafter leg is still one row per slot and is
#: covered by the existing sweep.
_PART_BUDGET = 4096

#: Programs (``rows * split``) above which the budget halves, in waves of the
#: device's SMs. ``split`` is chosen for ONE row filling one wave; a slate of
#: several rows multiplies the programs, and past about two waves the extra
#: fan buys nothing but more level-2 re-selection. Halving the budget halves
#: ``split`` (and the level-2 tile) for exactly those slates. Measured on a
#: 4090 at ``V = 248320`` (median us, budget 4096 -> 2048):
#:
#: | slate | rows 1 | rows 5 | rows 16 | rows 48 | rows 64 |
#: |---|---|---|---|---|---|
#: | top_k 20, capacity 32 | 41 (kept) | 60 -> 50 | 127 -> 81 | 397 -> 256 | 543 -> 345 |
#: | top_k 40, capacity 64 | 49 (kept) | 71 -> 72 | 132 -> 101 | 409 -> 295 | 544 -> 407 |
#: | nucleus, capacity 128 | 303 (kept) | 388 (kept) | 428 -> 414 | 765 -> 682 | 907 -> 783 |
#:
#: Every cell the rule keeps at 4096 is one where 4096 was the faster (or
#: equal) budget. Like ``split`` itself the choice depends only on the launch
#: shape, so a captured graph bakes the same geometry its eager twin runs.
_PART_BUDGET_WAVES = 2

#: Minimum chunk width in units of ``capacity``. Below it, level 1 is barely
#: a filter — it hands nearly its whole chunk to level 2 — so the redundant
#: tile grows for no reduction. Only binds on narrow vocabularies; at the
#: served widths the level-2 budget is what binds.
_MIN_CHUNK_PER_CAPACITY = 8

#: Relative slack the nucleus crossing must clear before a row is served from
#: the candidates rather than escalated. It is the ONE number that turns "the
#: same kept set" from a hope into a condition.
#:
#: The nucleus boundary is where a cumulative mass crosses ``p``. Two exact
#: implementations of that rule still disagree about the crossing when they
#: sum the same terms in different orders and the boundary token's own mass is
#: comparable to the summation error — the fanned mask groups the row by
#: chunk, the pivot kernel accumulates it serially, and a single flipped
#: boundary token is a different sampled distribution, not a rounding detail.
#: So the row is served only when the crossing clears this much slack on BOTH
#: sides, which makes the boundary invariant to any reordering that moves the
#: sums by less than it.
#:
#: 1e-5 is ~168 fp32 ULPs of relative headroom against a bound of roughly 30
#: ULPs for the whole chain (per-term ``exp`` plus a tree reduction over the
#: vocabulary), so it is loose by more than 5x on purpose: the cost of an
#: over-tight bound is a wrong kept set, and the cost of a loose one is that a
#: row whose boundary token carries under ~2e-5 of the mass takes the pivot
#: kernel it would have taken anyway.
_NUCLEUS_MARGIN = 1e-5

#: Candidate capacity the nucleus path runs at, independent of the operator's
#: ``ARBI_TOPC_MASK``. The two answer different questions: the flag's capacity
#: only has to hold a served ``top_k`` (20 in every published Qwen recipe),
#: while this one has to hold a whole NUCLEUS, whose depth is set by the row's
#: flatness and can be hundreds of tokens at the ``top_p`` values clients
#: actually send.
#:
#: The mask's cost is linear in the capacity while coverage of the served
#: ``top_p`` grid saturates well before the cost does, so the value sits at
#: that knee — and it is charged ONLY to a slate that actually presents the
#: shape: a ``top_k``-capped slate never widens.
#:
#: SCOPE, and it matters twice over. The cost/coverage curve was taken on a
#: 4090 at ``V = 248320`` with LM-shaped rows under cudagraph replay, at
#: ``rows = 1`` and on a five-row (K=4) verify slate. The served verify slate
#: is 64 rows, where the per-row cost is amortized differently, so the knee is
#: not known to be in the same place. And this value is BAKED at cudagraph
#: record time — it cannot be re-chosen live — so moving it is a re-capture.
#: *Needs: the same curve at rows 48 and 64 on 27B exl3 4.0bpw, DFlash2 K=7,
#: --max-batch 8.*
_NUCLEUS_CAPACITY = 128

#: Ceiling on the level-1 tile. A chunk wider than this is folded by a running
#: merge inside the program (see ``_topc_partials_kernel``), so the register
#: footprint stays put as ``V`` grows instead of scaling with ``V / split``.
_MAX_TILE = 2048


def topc_capacity_floor(value: int) -> int:
    """Largest power of two ``<= value`` (``0`` for anything non-positive).

    The level-2 selection is a ``tl.topk``, which takes only power-of-two
    widths. Rounding DOWN rather than up matters: rounding up would quietly
    serve slates the operator's number excludes, so the flag would be lying
    about what it baked.
    """
    return 0 if value <= 0 else 1 << (int(value).bit_length() - 1)


def topc_mask_refusal(
    top_ks: list[int] | tuple[int, ...],
    top_ps: list[float] | tuple[float, ...],
    *,
    vocab_size: int,
    capacity: int,
    nucleus: bool = False,
) -> str | None:
    """``None`` if the slate is representable, else WHY it is not.

    The single decision :func:`topc_mask_eligible` is defined as, split out
    so a refusal carries a machine-readable reason to the flag-truth counter
    instead of collapsing to a bare ``False``. A bare ``False`` makes a
    dormant fast path indistinguishable from a fast path the traffic keeps
    stepping around, which is the exact question a fallback count exists to
    answer.

    ``top_ks`` / ``top_ps`` are the encoded per-row values
    (:meth:`~arbi_serve.spec_decode.rejection_sampler_ops.DrafterSamplingTensors.encode_params_host`
    conventions: ``top_k == vocab_size`` means DISABLED, ``top_p >= 1.0``
    means disabled).

    A row is representable when its top_k caps the kept set inside the
    capacity, or when nothing needs a rank/nucleus search at all:

      * ``0 < top_k <= capacity`` — the whole chain (top_k, then top_p over
        its survivors, then min_p) lives inside the top-``capacity`` set;
      * ``top_k`` disabled AND ``top_p`` disabled — nothing but min_p can
        cut, and min_p needs only the row max, which the partials carry.

    ``top_k`` disabled with ``top_p`` ACTIVE needs the third launch
    (``nucleus``): the nucleus renormalises over the whole vocabulary and can
    extend past the capacity, so the mask can only serve the rows whose
    boundary it proves lies inside the candidates and must hand the rest back.
    A caller that can run that escalation passes ``nucleus=True``; a caller
    replaying a chain that did not RECORD it passes ``False``, because a
    launch cannot be added by ``copy_()``.

    ``capacity <= 0`` disables the path outright (the rollback).
    """
    if capacity <= 0:
        return "topc_mask_off"
    if vocab_size <= capacity:
        return "vocab_within_capacity"
    if not top_ks:
        return "empty_slate"
    ps = list(top_ps) if top_ps else [1.0] * len(top_ks)
    if len(ps) != len(top_ks):
        return "param_length_mismatch"
    for k, p in zip(top_ks, ps, strict=True):
        k = int(k)
        if 0 < k <= capacity:
            continue
        if k >= vocab_size:
            if float(p) >= 1.0 or nucleus:
                continue
            # An OpenAI-style request that sets top_p and leaves top_k unset.
            # Named separately from a too-wide top_k because the two need
            # different fixes: this one needs a launch, that one needs a
            # bigger capacity.
            return "topp_without_topk"
        return "topk_over_capacity" if k > capacity else "topk_nonpositive"
    return None


def topc_mask_eligible(
    top_ks: list[int] | tuple[int, ...],
    top_ps: list[float] | tuple[float, ...],
    *,
    vocab_size: int,
    capacity: int,
    nucleus: bool = False,
) -> bool:
    """True iff every row of a slate can be masked from a top-``capacity`` set.

    The one predicate the routing layer and the live dispatch both ask; see
    :func:`topc_mask_refusal` for the rule and the per-shape reasons. Kept as
    a thin wrapper rather than a second copy of the rule so the two can never
    disagree about a slate.
    """
    return (
        topc_mask_refusal(top_ks, top_ps, vocab_size=vocab_size, capacity=capacity, nucleus=nucleus)
        is None
    )


def _nucleus_capacity_for(capacity: int, *, vocab_size: int, nucleus_capacity: int) -> int:
    """Capacity the nucleus path runs at for a row of ``vocab_size``.

    A nucleus needs a candidate set deep enough to CONTAIN it, which is a
    different requirement from holding a served ``top_k`` — so the path widens
    past the operator's capacity, and only for the slates that present the
    shape. The widening stops below the vocabulary: a candidate set that IS
    the row selects nothing and leaves no tail to cut, so a narrow vocabulary
    keeps the operator's capacity and escalates more rows instead.
    """
    return max(int(capacity), min(int(nucleus_capacity), topc_capacity_floor(vocab_size - 1)))


def _geometry(
    vocab_size: int,
    capacity: int,
    part_budget: int = _PART_BUDGET,
    max_tile: int = _MAX_TILE,
) -> tuple[int, int, int, int, int]:
    """``(split, chunk, block_size, part_block, n_tiles)`` for a row width.

    ``split`` — how far one row fans — is derived from the level-2 budget
    rather than chosen independently, because those two are the same number:
    every masking program re-selects over a ``split * capacity``-wide tile, so
    letting ``split`` grow to fill the device is exactly how the level-2 cost
    runs away. Bounding the product bounds both, at every vocabulary size.

    ``block_size`` is then capped separately and a wider chunk is folded by a
    running merge, so neither tile scales with ``V``. Both are powers of two
    (``tl.topk`` takes no other width) and both are at least ``capacity``.

    Both bounds are arguments rather than constants so the geometry can be
    TESTED and MEASURED across them. In particular the running-merge branch is
    unreachable at any served width — it needs a chunk wider than ``max_tile``
    — so without a way to shrink the cap it would ship exercised only by
    arithmetic.
    """
    # Three bounds, all of them the same idea from different sides: the
    # level-2 tile must stay inside its budget; a chunk must be able to HOLD
    # ``capacity`` entries for the two-level selection to stay exact; and a
    # chunk comparable to ``capacity`` means level 1 selects nearly everything
    # it reads, which just moves the work into the level-2 tile instead of
    # reducing it.
    split = max(
        1,
        min(
            part_budget // capacity,
            vocab_size // capacity,
            vocab_size // (_MIN_CHUNK_PER_CAPACITY * capacity),
        ),
    )
    chunk = -(-vocab_size // split)
    block_size = max(next_pow2(min(chunk, max_tile)), capacity)
    n_tiles = -(-chunk // block_size)
    part_block = max(next_pow2(split * capacity), capacity)
    return split, chunk, block_size, part_block, n_tiles


def _part_budget_for(rows: int, vocab_size: int, capacity: int, device: torch.device) -> int:
    """The level-2 budget for a ``rows``-row slate (see :data:`_PART_BUDGET_WAVES`)."""
    if device.type != "cuda":  # the interpreter has no waves to fill
        return _PART_BUDGET
    split = _geometry(vocab_size, capacity, _PART_BUDGET)[0]
    if rows * split > _PART_BUDGET_WAVES * num_sm(device):
        return _PART_BUDGET // 2
    return _PART_BUDGET


def apply_topc_mask_(
    logits: torch.Tensor,  # (rows, V) fp32 CUDA contiguous — masked IN PLACE
    k: torch.Tensor | None,  # (rows,) int per-row top_k (>= V disables the row)
    p: torch.Tensor | None,  # (rows,) fp32 per-row top_p (>= 1.0 disables)
    *,
    min_p: torch.Tensor | None = None,  # (rows,) fp32 (0.0 disables the row)
    lse_out: torch.Tensor | None = None,  # (rows,) fp32 — masked-row logsumexp
    capacity: int,
    nucleus: bool = False,
    nucleus_capacity: int = _NUCLEUS_CAPACITY,
    margin: float = _NUCLEUS_MARGIN,
    part_budget: int | None = None,
    max_tile: int = _MAX_TILE,
) -> torch.Tensor:
    """Mask ``logits`` to the top_k → top_p → min_p kept set; returns it.

    Drop-in for :func:`~arbi_serve.sampler.topk_topp_triton.apply_top_k_top_p_triton`
    on a slate :func:`topc_mask_eligible` accepts (the caller MUST have
    checked). Masked positions get ``-inf``; kept positions are untouched,
    so they keep the exact fp32 bits they came in with.

    ``lse_out`` reproduces the pivot kernel's fused LSE epilogue — the
    masked row's ``logsumexp``, which the fused MTP verify tail consumes in
    place of a separate ``torch.logsumexp`` launch. It is finished on the
    host from per-chunk partial sums, so it differs from the pivot kernel's
    single-program accumulation by fp32 reduction order only — the same
    drift class that path already ships with.

    ``nucleus`` adds the third launch that makes a ``top_k``-disabled row with
    an active ``top_p`` representable: the mask kernel serves the rows whose
    nucleus it can bound exactly and hands the rest to the pivot kernel
    through a device-written residual ``top_p``, which reads ``1.0`` —
    DISABLED — for every row already served. The escalation is therefore
    unconditional in SHAPE and selective in EFFECT, which is what a captured
    chain needs: nothing about the launch depends on a host-visible value.
    It also takes over ``min_p`` and the LSE, because both must observe the
    FINAL kept set and an escalated row is not masked until it runs.
    """
    from arbi_serve.sampler._topc_kernel import _topc_mask_kernel, _topc_partials_kernel

    assert logits.ndim == 2, f"topc mask expects (rows, V); got {tuple(logits.shape)}"
    assert logits.dtype == torch.float32, "topc mask expects fp32 logits"
    assert logits.is_contiguous(), "topc mask needs a contiguous vocab dim"
    rows, V = logits.shape
    if rows == 0:
        return logits
    nucleus = bool(nucleus) and p is not None
    # A nucleus needs a candidate set deep enough to CONTAIN it, which is a
    # different requirement from holding a served top_k; widening only for the
    # slates that present the shape keeps the top_k path at its own optimum.
    # The widening still stops below the vocabulary — a candidate set that IS
    # the row selects nothing and has no tail to cut — so a narrow vocabulary
    # keeps the operator's capacity and escalates more rows instead.
    cap = (
        _nucleus_capacity_for(capacity, vocab_size=V, nucleus_capacity=nucleus_capacity)
        if nucleus
        else int(capacity)
    )
    assert cap > 0 and cap & (cap - 1) == 0, f"capacity must be a power of two; got {cap}"
    assert cap < V, f"capacity {cap} must be below the vocab width {V}"

    if part_budget is None:
        part_budget = _part_budget_for(rows, V, cap, logits.device)
    split, chunk, block_size, part_block, n_tiles = _geometry(V, cap, part_budget, max_tile)
    n_programs = rows * split
    dev = logits.device
    part = torch.empty((rows, split, cap), dtype=torch.float32, device=dev)
    # Dummy pointers for the disabled specializations; never read.
    part_max = torch.empty((rows, split), dtype=torch.float32, device=dev) if nucleus else part
    part_mass = torch.empty((rows, split), dtype=torch.float32, device=dev) if nucleus else part
    p_resid = torch.empty((rows,), dtype=torch.float32, device=dev) if nucleus else part

    _topc_partials_kernel[(n_programs,)](
        logits,
        part,
        part_max,
        part_mass,
        0,
        0,
        1,
        1.0,
        part,
        part,
        part,
        VOCAB_SIZE=V,
        SPLIT=split,
        CHUNK=chunk,
        CAP=cap,
        BLOCK_SIZE=block_size,
        N_TILES=n_tiles,
        WRITE_MASS=nucleus,
    )

    # An escalated row is not masked until the pivot launch runs, so the two
    # filters that must see the FINAL kept set travel with it rather than
    # being fused here.
    fuse_tail = not nucleus
    write_lse = lse_out is not None and fuse_tail
    part_sum = (
        torch.empty((rows, split), dtype=torch.float32, device=dev)
        if write_lse
        else part  # dummy pointer; unread when WRITE_LSE is False
    )
    row_max = torch.empty((rows,), dtype=torch.float32, device=dev) if write_lse else part
    _topc_mask_kernel[(n_programs,)](
        logits,
        part,
        part_max,
        part_mass,
        torch.empty((n_programs, cap), dtype=torch.float32, device=dev),
        k if k is not None else part,
        p if p is not None else part,
        min_p if (min_p is not None and fuse_tail) else part,
        part_sum,
        row_max,
        p_resid,
        float(margin),
        MASK_VALUE=float("-inf"),
        VOCAB_SIZE=V,
        SPLIT=split,
        SPLIT_BLOCK=next_pow2(split),
        CHUNK=chunk,
        CAP=cap,
        PART_BLOCK=part_block,
        BLOCK_SIZE=block_size,
        N_TILES=n_tiles,
        TOPK_ENABLED=k is not None,
        TOPP_ENABLED=p is not None,
        MINP_ENABLED=min_p is not None and fuse_tail,
        NUCLEUS=nucleus,
        WRITE_LSE=write_lse,
    )
    if write_lse:
        lse_out.copy_(part_sum.sum(dim=1).log() + row_max)
    if nucleus:
        from arbi_serve.sampler.topk_topp_triton import apply_top_k_top_p_triton

        apply_top_k_top_p_triton(logits, None, p_resid, min_p=min_p, lse_out=lse_out)
    return logits


def topc_threshold_reference(
    logits: torch.Tensor,  # (rows, V) fp32
    k: torch.Tensor | None,
    p: torch.Tensor | None,
    *,
    min_p: torch.Tensor | None = None,
    capacity: int,
    nucleus: bool = False,
    margin: float = _NUCLEUS_MARGIN,
) -> torch.Tensor:
    """Pure-torch twin of :func:`apply_topc_mask_`'s threshold — ``(rows,)``.

    The device-free statement of the rule the kernel implements, so the CPU
    suite can pin the SEMANTICS (which value each filter cuts at, and that
    the cuts compose by ``max``) without a GPU, leaving the GPU suite to pin
    the one thing only it can: agreement with the kernel this replaces.
    Deliberately written against ``torch.topk`` rather than by reusing the
    kernel's host helpers — a reference that shares the implementation
    proves nothing.

    Under ``nucleus`` a ``top_k``-disabled row renormalises over the whole
    row, and a row whose boundary the candidates cannot pin down with
    ``margin`` to spare reads ``-inf``: not "keep everything", but "this row
    is the escalation's, and the mask must leave it alone".
    """
    rows, V = logits.shape
    cap = min(int(capacity), V)
    top, _ = torch.topk(logits.float(), cap, dim=-1)  # (rows, cap) descending
    row_max = top[:, 0]
    thresh = logits.new_full((rows,), float("-inf"))
    handled = torch.ones(rows, dtype=torch.bool, device=logits.device)
    keep_k = top > float("-inf")
    topk_live = torch.zeros(rows, dtype=torch.bool, device=logits.device)
    if k is not None:
        # ``k >= V`` is the DISABLED encoding, not a cap of the whole vocab.
        topk_live = k.view(rows) < V
        kk = k.to(torch.int64).clamp(1, cap).view(rows, 1)
        t_k = torch.where(topk_live, top.gather(1, kk - 1).squeeze(1), thresh)
        keep_k = top >= t_k.view(rows, 1)
        thresh = torch.maximum(thresh, t_k)
    if p is not None:
        e = torch.where(keep_k, (top - row_max.view(rows, 1)).exp(), top.new_zeros(()))
        cand_mass = e.sum(dim=-1, keepdim=True)
        denom = cand_mass
        if nucleus:
            # A row with no finite max shifts to NaN, so the non-finite lanes
            # are pushed to -inf and contribute an exact zero instead.
            shifted = logits.float() - row_max.view(rows, 1)
            shifted = torch.where(torch.isfinite(shifted), shifted, shifted.new_full((), NEG_INF))
            row_mass = shifted.exp().sum(dim=-1, keepdim=True)
            denom = torch.where(topk_live.view(rows, 1), cand_mass, row_mass)
        probs = e / denom
        exclusive = probs.cumsum(dim=-1) - probs
        keep_p = keep_k & (exclusive < p.view(rows, 1))
        t_p = torch.where(keep_p, top, top.new_full((), float("inf"))).amin(dim=-1)
        thresh = torch.maximum(thresh, torch.where(p >= 1.0, thresh, t_p))
        if nucleus:
            target = (p.view(rows, 1) * denom).squeeze(1)
            slack = margin * denom.squeeze(1)
            at = torch.where(top >= t_p.view(rows, 1), e, top.new_zeros(())).sum(dim=-1)
            above = torch.where(top > t_p.view(rows, 1), e, top.new_zeros(())).sum(dim=-1)
            ok = (
                (cand_mass.squeeze(1) >= target + slack)
                & (at >= target + slack)
                & (above + slack <= target)
            )
            handled = torch.where(topk_live | (p.view(rows) >= 1.0), handled, ok)
    if min_p is not None:
        t_mp = row_max + min_p.clamp_min(torch.finfo(torch.float32).tiny).log()
        thresh = torch.maximum(thresh, torch.where(min_p > 0.0, t_mp, thresh))
    return torch.where(handled, thresh, logits.new_full((rows,), float("-inf")))
# ---- topk_topp_triton.py ----
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Combined Top-K + Top-P Triton kernel — vendored from vLLM.

Source: ``vllm/v1/sample/ops/topk_topp_triton.py`` (vLLM project, Apache 2.0).

Vendoring rationale. The Python-batched
sampling chain in ``arbi_serve.sampler.sampler`` runs one PyTorch op
per stage: ``torch.topk`` for top-k threshold, ``sort`` + ``cumsum`` +
``scatter`` for top-p, ``logits.max(...)`` for min-p, ``softmax`` +
``argmax`` for the Gumbel-max sample — several kernel launches per
step of pure launch overhead. vLLM fused
top-k + top-p into one Triton kernel using the **Qrita pivot
algorithm** (Park et al., arXiv:2602.01518): one kernel launch +
one buffer scratch, no global sort. This module brings that kernel
into ``arbi-serve`` so the Python-batched chain collapses to a
single launch for the top-k / top-p mask. Min-p stays in PyTorch
(one batched ``masked_fill_`` using the
``logit_i >= log(mp) + max_logit`` rewrite).

Local adaptations vs. the vLLM source:

  * Imports rewritten to use top-level ``triton`` / ``triton.language``
    instead of ``vllm.triton_utils`` (we don't have that wrapper).
  * ``next_power_of_2`` lifted from ``vllm.utils.math_utils`` (3 LOC).
  * ``num_compute_units`` replaced with
    ``torch.cuda.get_device_properties(...).multi_processor_count``
    (one call site).
  * ``SAMPLE`` epilogue (arbi-serve): optional fused softmax → Gumbel-max
    → argmax tail so the masked logits never round-trip to Python
    (:func:`sample_top_k_top_p_triton`).
  * ``MINP_ENABLED`` / ``WRITE_LSE`` epilogue (arbi-serve): optional
    per-row min-p mask (the ``logit >= max_logit + log(min_p)`` rewrite —
    the same form :func:`arbi_serve.sampler.sampler._vectorized_min_p_mask`
    uses) and/or the masked-row ``logsumexp`` written to ``OUT_LSE`` in
    the SAME launch. This is what lets the fused MTP rejection sampler
    serve a filtered slate without adding
    a launch: the mask kernel REPLACES the ``torch.logsumexp`` launch the
    no-filter fused path issues, keeping the launch count identical.

DIVERGED FROM UPSTREAM — the ``top_p`` search is ours now. This file
used to promise that "the pivot-search body is byte-for-byte identical to the
upstream version", so the mask math stayed cherry-pick-able. That is no
longer true and must not be assumed by a future sync.

The upstream ``top_p`` search is a ternary search over the CONTINUOUS
probability range, capped at 18 iterations with a ``1e-9`` convergence floor
and an interval-MIDPOINT fallback when neither probe satisfies its acceptance
test in budget. Ternary search narrows by ~1/3 a step, so 18 steps from
``[0, 1]`` bottoms out at ~``1.4e-9`` — the floor itself. Two adjacent
probabilities closer than that cannot be separated, and the midpoint lands on
whichever side of the true boundary the interval happened to straddle. The
served nucleus was therefore not the one ``top_p`` asks for: measured against
a ``torch.sort`` reference it comes out too small OR too large, both observed,
on rows whose boundary sits inside a plateau of near-identical logits — which
is what a real ``lm_head`` produces over a 248k vocabulary. On well-separated
rows it is exact, which is why this survived.

It is replaced by :func:`~arbi_serve.sampler._topp_exact._nucleus_pivot`,
which bisects the IEEE754 ORDERED-INTEGER KEY in LOGIT space: representable
floats are a contiguous integer range, so bisecting them terminates on an
exact value with no tolerance constant anywhere, and staying in logit space
avoids a ``log(p * Z) + max`` round-trip that would reintroduce a ULP of slop
at exactly the boundary being fixed. It also runs FEWER passes than what it
replaces — one per iteration instead of two, and no probability buffer at
all.

The top_k heuristic's early exit uses exact tie counts to prove its
boundary. If the search cannot prove a cut, ordered-key bisection repairs
it; guessing a float midpoint cannot retain a kth-value group at the row
minimum. ``tests/test_topk_minimum_tie_boundary.py`` holds those cases.
The arbi-serve epilogues remain constexpr-gated blocks whose disabled
specialization compiles out entirely.

A future vLLM sync must therefore MERGE rather than overwrite: taking the
upstream search body wholesale reintroduces the defect silently, and the
regression test that catches it
(``tests/test_topp_nucleus_exact.py``) needs rows with a plateau at the
boundary to fail at all."""

from __future__ import annotations

from collections.abc import Callable, Sequence

import torch

from arbi_serve.sampler._topk_topp_kernel import _topk_topp_kernel
from arbi_serve.sampler._triton_util import next_pow2 as _next_power_of_2
from arbi_serve.sampler._triton_util import num_sm as _num_sm

_TRITON_TABLE_CACHE: dict[torch.device, tuple[torch.Tensor, torch.Tensor]] = {}
_TRITON_BUFFER_CACHE: dict[tuple[torch.device, torch.dtype, int], torch.Tensor] = {}

#: Engine boot hook routing the sampler's device scratch into a NAMED cuMem
#: pool. ``None`` = no engine has installed one, and the allocations below
#: fall back to the default allocator.
#:
#: Why this exists: the scratch buffer is ``(programs, vocab)`` fp32 and the
#: tables are two fp32 vectors, all allocated OUTSIDE every named pool by
#: default. That lands them in ``unpooled.torch_default_pool``, which the VRAM
#: ledger reports as unbudgeted BY CONSTRUCTION — and KV sizing has already
#: spent those bytes. At a 248,320 vocab the scratch alone is ~3.8 MiB at four
#: programs, and it GROWS with the program count: an MTP verify slate presents
#: ``(K+1) x B`` rows, so a K=4 batch-4 slate asks for 20 programs and ~19 MiB,
#: capped at the SM count (~127 MiB on a 128-SM card).
#:
#: Unlike the penalty accumulator, this scratch is NOT optional — the mask
#: kernel cannot run without it — so a missing hook must fall back rather than
#: refuse. The fallback is exactly today's behaviour, which is why installing
#: the hook is a pure accounting fix and changes no served bytes.
_POOL_ALLOCATE: Callable[[tuple[int, ...], torch.dtype, torch.device], torch.Tensor] | None = None


def install_sampler_scratch_pool(
    allocate: Callable[[tuple[int, ...], torch.dtype, torch.device], torch.Tensor] | None,
) -> None:
    """Engine boot hook: route sampler scratch/table allocations into a named pool.

    Drops the existing caches so the next sampler call rebuilds them INSIDE
    the pool; without that the process would keep serving the unpooled tensors
    it had already cached and the ledger row would read zero while the bytes
    stayed unbudgeted.

    Passing ``None`` uninstalls (used by tests and by member teardown).
    """
    global _POOL_ALLOCATE
    _POOL_ALLOCATE = allocate
    clear_kernel_caches()


def _scratch_empty(
    shape: tuple[int, ...], dtype: torch.dtype, device: torch.device
) -> torch.Tensor:
    """Allocate sampler scratch in the named pool when one is installed."""
    if _POOL_ALLOCATE is not None:
        return _POOL_ALLOCATE(shape, dtype, device)
    return torch.empty(shape, device=device, dtype=dtype)


def presize_sampler_scratch(device: torch.device, widths: Sequence[int], rows: int) -> int:
    """Materialise every mask-kernel buffer the serving path will need.

    Two things make this a boot step rather than a lazy one.

    The pivot scratch is cached per ``(device, row width)`` and reallocated
    only when a WIDER row count arrives, so the widest slate must run first or
    the widening lands later. And the cache is keyed per LOGITS width: the
    full-vocab mask and the sharded candidate-width mask
    (``n_cand * tp_size``) are separate entries, so covering one leaves the
    other to allocate on first use.

    Both matter because the pool is capped at the bytes it holds when the boot
    freeze snapshots it. A later entry needs a fresh segment mapped into that
    pool, and the cap denies the map however much device memory is free — the
    itself wants.

    Returns the bytes allocated."""
    if not torch.cuda.is_available() or int(rows) <= 0:
        return 0
    num_sm = _num_sm(device)
    programs = min(num_sm, int(rows))
    size = min(_next_power_of_2(programs), num_sm)
    total = 0
    for w in widths:
        w = int(w)
        if w <= 0:
            continue
        key = (device, torch.float32, w)
        cached = _TRITON_BUFFER_CACHE.get(key)
        if cached is not None and cached.shape[0] >= size:
            continue
        buf = _scratch_empty((size, w), torch.float32, device)
        _TRITON_BUFFER_CACHE[key] = buf
        total += buf.numel() * buf.element_size()

    # The CDF/percentile lookup tables are built with a bare ``torch.tensor``
    # on first use, which lands them outside the pool. Build them here through
    # the same allocator so the pool holds them before the cap arms.
    if _TRITON_TABLE_CACHE.get(device) is None:
        tables = []
        for host in (_NORMAL_CDF_TO_SIGMA_TABLE, _PERCENTILE_TO_STD_TABLE):
            t = _scratch_empty((len(host),), torch.float32, device)
            t.copy_(torch.tensor(host, dtype=torch.float32))
            tables.append(t)
            total += t.numel() * t.element_size()
        _TRITON_TABLE_CACHE[device] = tuple(tables)
    return total


def clear_kernel_caches() -> int:
    """Drop the process-global sampler scratch/table device tensors.

    These caches (:data:`_TRITON_BUFFER_CACHE` — the per-(device, vocab) fp32
    pivot-search scratch; :data:`_TRITON_TABLE_CACHE` — the CDF→sigma lookup
    tables) hold DEVICE tensors first allocated by whichever member happened to
    run the sampler first. They are process-global, NOT per-member, so a
    stable-VA member swap does NOT rebuild them — the incoming member reuses
    the OUTGOING member's tensors. When the outgoing member is parked its pool
    physical is unmapped/evicted; the retained cache tensors then reference
    freed/unmapped VRAM and the next ``_topk_topp_kernel`` launch reads
    unbacked memory → ``cudaErrorIllegalAddress``. Clearing on member reset
    forces the incoming member to re-allocate them in ITS OWN live context
    on the next sampler call.

    Same class as :func:`~arbi_serve.engine.engine_model_state._EngineModelStateMixin.
    _reset_workspace_pool_state` (the FLA / cuBLAS workspace globals). Returns
    the number of cache entries dropped (for the reset log). Safe to call any
    time — the caches lazy-rebuild on the next sampler call."""
    n = len(_TRITON_TABLE_CACHE) + len(_TRITON_BUFFER_CACHE)
    _TRITON_TABLE_CACHE.clear()
    _TRITON_BUFFER_CACHE.clear()
    return n


# fmt: off
_NORMAL_CDF_TO_SIGMA_TABLE = [
  3.656,  3.650,  3.650,  3.650,  3.626,  3.626,  3.626,  3.514,  3.514,  3.503,
  3.503,  3.434,  3.434,  3.428,  3.428,  3.387,  3.380,  3.380,  3.376,  3.373,
  3.373,  3.356,  3.354,  3.354,  3.291,  3.249,  3.234,  3.214,  3.198,  3.198,
  3.185,  3.177,  3.177,  3.165,  3.164,  3.161,  3.138,  3.120,  3.115,  3.113,
  3.093,  3.066,  3.054,  3.043,  3.037,  3.023,  2.993,  2.991,  2.976,  2.970,
  2.952,  2.946,  2.932,  2.908,  2.902,  2.895,  2.886,  2.874,  2.861,  2.844,
  2.836,  2.810,  2.801,  2.790,  2.784,  2.779,  2.767,  2.757,  2.745,  2.733,
  2.723,  2.716,  2.693,  2.678,  2.671,  2.656,  2.649,  2.629,  2.611,  2.595,
  2.592,  2.585,  2.574,  2.550,  2.543,  2.534,  2.521,  2.518,  2.497,  2.485,
  2.468,  2.450,  2.441,  2.430,  2.412,  2.402,  2.389,  2.383,  2.377,  2.364,
  2.349,  2.338,  2.332,  2.319,  2.310,  2.301,  2.282,  2.274,  2.266,  2.250,
  2.242,  2.236,  2.226,  2.215,  2.207,  2.196,  2.179,  2.171,  2.162,  2.147,
  2.135,  2.121,  2.109,  2.095,  2.085,  2.073,  2.063,  2.045,  2.030,  2.016,
  2.003,  1.992,  1.983,  1.972,  1.960,  1.949,  1.940,  1.928,  1.912,  1.897,
  1.881,  1.869,  1.854,  1.838,  1.824,  1.807,  1.792,  1.779,  1.764,  1.751,
  1.739,  1.726,  1.711,  1.697,  1.685,  1.668,  1.652,  1.636,  1.622,  1.603,
  1.585,  1.568,  1.551,  1.534,  1.513,  1.499,  1.480,  1.464,  1.441,  1.422,
  1.394,  1.373,  1.347,  1.320,  1.296,  1.270,  1.246,  1.219,  1.190,  1.163,
  1.135,  1.104,  1.073,  1.041,  1.006,  0.969,  0.931,  0.894,  0.851,  0.806,
  0.757,  0.702,  0.643,  0.574,  0.498,  0.405,  0.288,  0.134, -0.110, -3.813,
]

_PERCENTILE_TO_STD_TABLE = [
  2.576,  2.319,  2.178,  2.064,  1.968,  1.892,  1.819,  1.757,  1.708,  1.659,
  1.616,  1.568,  1.526,  1.492,  1.456,  1.420,  1.382,  1.342,  1.309,  1.280,
  1.249,  1.221,  1.193,  1.169,  1.145,  1.121,  1.095,  1.073,  1.050,  1.030,
  1.008,  0.987,  0.966,  0.945,  0.926,  0.910,  0.891,  0.871,  0.854,  0.837,
  0.819,  0.803,  0.784,  0.767,  0.753,  0.734,  0.719,  0.702,  0.690,  0.675,
  0.658,  0.640,  0.625,  0.609,  0.595,  0.578,  0.564,  0.550,  0.537,  0.521,
  0.509,  0.495,  0.481,  0.466,  0.453,  0.439,  0.424,  0.410,  0.397,  0.383,
  0.370,  0.356,  0.343,  0.330,  0.316,  0.302,  0.289,  0.274,  0.261,  0.247,
  0.235,  0.223,  0.209,  0.196,  0.184,  0.172,  0.159,  0.149,  0.137,  0.124,
  0.112,  0.100,  0.086,  0.074,  0.062,  0.050,  0.035,  0.023,  0.009, -0.003,
 -0.015, -0.027, -0.039, -0.052, -0.063, -0.074, -0.085, -0.097, -0.109, -0.122,
 -0.134, -0.147, -0.158, -0.171, -0.184, -0.196, -0.210, -0.223, -0.235, -0.248,
 -0.261, -0.275, -0.289, -0.302, -0.317, -0.328, -0.341, -0.353, -0.368, -0.382,
 -0.396, -0.410, -0.426, -0.439, -0.452, -0.465, -0.480, -0.493, -0.507, -0.521,
 -0.537, -0.551, -0.568, -0.582, -0.597, -0.614, -0.628, -0.643, -0.658, -0.673,
 -0.691, -0.706, -0.721, -0.738, -0.754, -0.769, -0.789, -0.808, -0.824, -0.838,
 -0.857, -0.877, -0.893, -0.912, -0.929, -0.947, -0.965, -0.983, -1.003, -1.027,
 -1.050, -1.070, -1.092, -1.117, -1.139, -1.162, -1.189, -1.216, -1.241, -1.272,
 -1.300, -1.330, -1.367, -1.404, -1.441, -1.485, -1.523, -1.564, -1.607, -1.658,
 -1.710, -1.778, -1.832, -1.901, -1.978, -2.068, -2.174, -2.325, -2.577, -3.813,
]
# fmt: on


def _mask_num_warps(batch_size: int) -> int:
    """Warps per program for the mask kernel.

    One program owns a whole row and walks it pass after pass (max/mass,
    candidate compaction, the nucleus search, the masked write), each pass a
    chain of tile loads and block reductions. At the default four warps a
    program keeps too few loads in flight and spends its time waiting on
    reductions, so a row costs the same whether the card is otherwise idle or
    not. More warps per program shorten every pass; sixteen pays most where a
    few rows each own an SM, eight where a full batch already fills the card.
    The warp count changes which thread sums which element, never which
    elements are kept beyond fp32 reduction order, the same freedom the
    nucleus search's own tile order already has.
    """
    return 16 if batch_size <= 8 else 8


def _launch_topk_topp(
    logits: torch.Tensor,
    k: torch.Tensor | None,
    p: torch.Tensor | None,
    mask_value: float,
    noise: torch.Tensor | None,
    out_tokens: torch.Tensor | None,
    min_p: torch.Tensor | None = None,
    lse_out: torch.Tensor | None = None,
) -> None:
    """Launch the fused top-k/top-p (+ optional epilogue) kernel once.

    Shared by :func:`apply_top_k_top_p_triton` (mask, optionally + min-p
    mask and/or masked-row logsumexp) and :func:`sample_top_k_top_p_triton`
    (mask + in-kernel Gumbel-max). ``min_p`` / ``lse_out`` and the SAMPLE
    tail are mutually exclusive (no caller combines them; the assert keeps
    an accidental combination loud instead of silently mis-normalized).
    """
    batch_size, vocab_size = logits.shape

    topk_enabled = k is not None
    topp_enabled = p is not None
    minp_enabled = min_p is not None
    sample = out_tokens is not None
    write_lse = lse_out is not None

    if minp_enabled or write_lse:
        assert not sample, "min_p/lse_out epilogue and SAMPLE tail are mutually exclusive"
        # The LSE treats masked lanes as exp(-inf) == 0; a finite mask
        # value would silently corrupt the normalizer.
        assert mask_value == float("-inf"), "min_p/lse_out require mask_value=-inf"

    if k is not None:
        assert k.ndim == 1 and k.shape[0] == batch_size
        k_ptr = k.to(torch.int32)
    else:
        k_ptr = logits  # Dummy pointer (won't be read by the kernel).

    if p is not None:
        assert p.ndim == 1 and p.shape[0] == batch_size
        p_ptr = p.to(torch.float32)
    else:
        p_ptr = logits  # Dummy pointer (won't be read by the kernel).

    if min_p is not None:
        assert min_p.ndim == 1 and min_p.shape[0] == batch_size
        mp_ptr = min_p.to(torch.float32)
    else:
        mp_ptr = logits  # Dummy pointer (won't be read by the kernel).

    if lse_out is not None:
        assert lse_out.ndim == 1 and lse_out.shape[0] == batch_size
        assert lse_out.dtype == torch.float32
        lse_ptr = lse_out
    else:
        lse_ptr = logits  # Dummy pointer (won't be written by the kernel).

    if sample:
        assert noise is not None and noise.shape == logits.shape
        noise_ptr = noise
        out_ptr = out_tokens
    else:
        noise_ptr = logits  # Dummy pointer (won't be read by the kernel).
        out_ptr = logits  # Dummy pointer (won't be written by the kernel).

    num_sm = _num_sm(logits.device)
    NUM_PROGRAMS = min(num_sm, batch_size)

    # Cache the per-program scratch buffer per (device, vocab). The
    # buffer holds fp32 intermediates (outlier logits, normalized probs,
    # pivot-search partials) regardless of the LOGITS input dtype — the
    # kernel upcasts bf16 logits to fp32 in-register before any store
    # here, so a bf16 buffer would corrupt the pivot search. Key on
    # device + vocab only (no dtype: the buffer is always fp32).
    buf_key = (logits.device, torch.float32, vocab_size)
    buffer = _TRITON_BUFFER_CACHE.get(buf_key)
    if buffer is None or buffer.shape[0] < NUM_PROGRAMS:
        size = min(_next_power_of_2(NUM_PROGRAMS), num_sm)
        buffer = _scratch_empty((size, vocab_size), torch.float32, logits.device)
        _TRITON_BUFFER_CACHE[buf_key] = buffer
    if buffer.shape[0] > NUM_PROGRAMS:
        buffer = buffer[:NUM_PROGRAMS]

    tables = _TRITON_TABLE_CACHE.get(logits.device)
    if tables is None:
        normal_cdf_to_sigma_table = torch.tensor(
            _NORMAL_CDF_TO_SIGMA_TABLE, device=logits.device, dtype=torch.float32
        )
        percentile_to_std_table = torch.tensor(
            _PERCENTILE_TO_STD_TABLE, device=logits.device, dtype=torch.float32
        )
        _TRITON_TABLE_CACHE[logits.device] = (
            normal_cdf_to_sigma_table,
            percentile_to_std_table,
        )
    else:
        normal_cdf_to_sigma_table, percentile_to_std_table = tables

    _topk_topp_kernel[(NUM_PROGRAMS,)](
        logits,
        buffer,
        percentile_to_std_table,
        normal_cdf_to_sigma_table,
        k_ptr,
        p_ptr,
        mp_ptr,
        noise_ptr,
        out_ptr,
        lse_ptr,
        BATCH_SIZE=batch_size,
        MASK_VALUE=mask_value,
        VOCAB_SIZE=vocab_size,
        BLOCK_SIZE=8192,
        BLOCK_SIZE_TRUNC=4096,
        TOPK_ENABLED=topk_enabled,
        TOPP_ENABLED=topp_enabled,
        MINP_ENABLED=minp_enabled,
        SAMPLE=sample,
        WRITE_LSE=write_lse,
        num_warps=_mask_num_warps(batch_size),
    )


def apply_top_k_top_p_triton(
    logits: torch.Tensor,
    k: torch.Tensor | None,
    p: torch.Tensor | None,
    mask_value: float = float("-inf"),
    *,
    min_p: torch.Tensor | None = None,
    lse_out: torch.Tensor | None = None,
) -> torch.Tensor:
    """Apply combined top-k and top-p masking with one Triton kernel launch.

    Top-k is applied first (by logit value), then top-p is applied to
    the surviving logits' softmax probabilities. ``logits`` is modified
    in-place; the same tensor is returned for chaining.

    Args:
        logits: ``(batch_size, vocab_size)`` fp32 OR bf16/fp16 tensor;
            modified in place. Must be CUDA-resident and contiguous.
            bf16/fp16 logits are upcast to fp32 IN-REGISTER per tile (the
            softmax max/sum accumulators stay fp32); the in-place mask
            write-back downcasts the kept (already-bf16) logits losslessly,
            so the masked output is bit-identical to the fp32-input path
            while halving the HBM read bytes.
        k: ``(batch_size,)`` int tensor of per-row top-k caps, or
            ``None`` to disable top-k. Rows whose ``k >= vocab_size``
            are no-ops in the kernel.
        p: ``(batch_size,)`` fp32 tensor of per-row top-p (nucleus)
            probabilities in ``[0, 1]``, or ``None`` to disable top-p.
            Rows whose ``p >= 1.0`` are no-ops in the kernel.
        mask_value: Value to write at masked-out positions. Default
            ``-inf`` (so a downstream softmax zeroes them). Must stay
            ``-inf`` when ``min_p`` / ``lse_out`` are supplied.
        min_p: ``(batch_size,)`` fp32 tensor of per-row min-p thresholds
            (``0.0`` = disabled per row), or ``None`` to disable. Applied
            AFTER top-k/top-p in the same launch via the logit-space
            rewrite ``keep iff logit >= max_logit + log(min_p)`` — the
            identical form :func:`~arbi_serve.sampler.sampler._vectorized_min_p_mask`
            uses, so the kept set matches the eager chain's.
        lse_out: optional ``(batch_size,)`` fp32 tensor; when supplied the
            kernel ALSO writes each row's masked-logits ``logsumexp``
            (fp32 ``log(sum(exp(l - max))) + max`` over the post-mask
            row) — the softmax normalizer, produced in the same launch so
            a fused consumer (the MTP rejection sampler) needs no separate
            ``torch.logsumexp`` launch.

    Returns:
        The input ``logits`` tensor (modified in-place).
    """
    assert logits.ndim == 2
    assert logits.dtype in (torch.float32, torch.bfloat16, torch.float16)

    batch_size, _vocab_size = logits.shape

    if batch_size == 0 or not (
        k is not None or p is not None or min_p is not None or lse_out is not None
    ):
        return logits

    _launch_topk_topp(
        logits, k, p, mask_value, noise=None, out_tokens=None, min_p=min_p, lse_out=lse_out
    )
    return logits


def sample_top_k_top_p_triton(
    logits: torch.Tensor,
    k: torch.Tensor | None,
    p: torch.Tensor | None,
    noise: torch.Tensor,
) -> torch.Tensor:
    """Fused top-k/top-p mask + Gumbel-max sample in ONE kernel launch.

    Masks ``logits`` exactly as :func:`apply_top_k_top_p_triton` (in
    place), then folds the stochastic tail —
    ``softmax`` -> ``probs / noise`` -> ``argmax`` — into the same
    kernel so the masked logits never round-trip to Python. Returns the
    sampled token index per row.

    The result is op-for-op identical to the unfused chain
    ``argmax(softmax(masked_logits) / noise)`` (same fp32 softmax
    denominator, same two divides, same lowest-index argmax tie-break).

    Args:
        logits: ``(batch_size, vocab_size)`` fp32 OR bf16/fp16 CUDA
            tensor; masked in place (so it is NOT reusable as raw logits
            afterwards). bf16/fp16 is read directly and upcast to fp32
            in-register (half the HBM read); the result is bit-identical
            to passing the same logits pre-cast to fp32, because a bf16
            value widens to fp32 exactly and the masked write-back
            round-trips losslessly.
        k: per-row top-k caps (``None`` disables); see
            :func:`apply_top_k_top_p_triton`.
        p: per-row top-p (``None`` disables).
        noise: ``(batch_size, vocab_size)`` fp32 Exp(1) Gumbel-max draw
            — supplied by the caller so every TP rank draws the same
            token (rank-symmetric SPMD). Consumed read-only.

    Returns:
        ``(batch_size,)`` int64 sampled token indices.
    """
    assert logits.ndim == 2
    assert logits.dtype in (torch.float32, torch.bfloat16, torch.float16)
    assert noise.shape == logits.shape

    batch_size, _vocab_size = logits.shape
    out_tokens = logits.new_empty((batch_size,), dtype=torch.int64)
    if batch_size == 0:
        return out_tokens

    _launch_topk_topp(logits, k, p, float("-inf"), noise=noise, out_tokens=out_tokens)
    return out_tokens
# ---- vocab_shard_draw.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Shard-local candidate draw for a vocab-parallel output head (plain decode).

A head cut by vocab rows (:class:`~arbi_serve.models._deepseek_v4_vocab_head.
DSv4VocabParallelHead`) composes the sampler's row with an fp32 gather of
``B x vocab x 4`` bytes per decode step. On a narrow checkpoint that gather
costs more than the head bytes the cut saves. A decode slate whose draw reads
only a handful of tokens per row does not need the row: each rank sends the
tokens of ITS shard that the draw can pick, and every rank rebuilds the row
from them, as the sharded MTP verify does (:mod:`~arbi_serve.spec_decode.
mtp_verify_sharded`).

What a rank contributes per row, and why the draw is the gathered row's
-----------------------------------------------------------------------

* a greedy row: its shard argmax. The global argmax is some shard's argmax,
  and the rebuilt row's ``argmax`` breaks a tie toward the lowest index, as the
  full row's does. Bit-identical.
* an unfiltered stochastic row (``top_k`` off, ``top_p = 1``, ``min_p = 0``):
  its shard's Gumbel-max winner. The served draw is ``argmax_v(logit_v / T +
  g(seed, v))`` with the noise a pure function of the row seed and the GLOBAL
  token index (``gumbel_argmax_from_seeds``), so the whole row's winner is the
  winner of whichever shard holds it, and that shard computes the same score
  for it with the same temperature division (``apply_temperature``) and
  ``index_base``. The sampler then runs unchanged on the rebuilt row and picks
  the same token with the same noise. Bit-identical.
* a ``top_k <= N_CAND`` row (with any ``top_p`` / ``min_p``): the shard's top
  ``N_CAND`` logits, omitted boundary-tie mass and that tie group's seeded
  Gumbel winner. Every token strictly above the global kth value is a
  candidate. Missing tokens can only belong to a boundary tie group; its
  count restores the top-p normaliser and its winner preserves the final
  draw without materialising that group. The tie counter records when this
  completion is needed. A normaliser may round differently because compact
  and full rows group their fp32 sums differently.

The rebuilt row is ``-inf`` outside the candidates, which every mask in the
chain already treats as excluded, so the sampler, its row seeds and its
greedy merge are the ones the gathered row runs.

What falls back to the gather
-----------------------------

The decision is made BEFORE the forward from rank-replicated mirror state, so
every rank of the head's group takes the same branch and the exchange pairs.
A tick takes the gathered row when any emitting row has a penalty, a
``logit_bias``, a grammar, a processor that would write
(``constrains_verify_slate``), sampled logprobs, a ``top_k`` above
:data:`SERVED_TOP_K_CANDIDATES`, or
``top_p < 1`` / ``min_p > 0`` without a ``top_k``: those read tokens outside
any small candidate set, or (penalties) move logits before the selection could
see them. Keyed watermarking and the legacy full-noise
draw derive their noise differently, and a CPU tensor samples through the
generator path, so its stochastic rows fall back too. Prefill ticks keep the gather: a
measurement tool's raw-logits tap reads them (``fire_calibration_taps``).
"""

from __future__ import annotations

import logging
from collections.abc import Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any

import torch

from arbi_serve.flag_truth import FiringWindow, path_counter

if TYPE_CHECKING:
    from collections.abc import Iterator

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

#: Decode ticks drawn from shard candidates. Rank symmetry is readable off it:
#: every rank of a head group counts the same ticks.
_SHARD_DRAW = path_counter("vocab_shard_draw_step", FiringWindow.SERVE, counted=True)

#: Rows needing omitted boundary-tie mass, accumulated on device. Their
#: completed payload still carries the whole group's mass and seeded winner.
_tie_overflow: dict[torch.device, torch.Tensor] = {}

#: The largest ``top_k`` a served slate may draw from candidates. Wider
#: filters retain the head's full-row gather.
SERVED_TOP_K_CANDIDATES = 40
_tap_warned = False


@dataclass(frozen=True)
class ShardDrawPlan:
    """One tick's shard draw, decided before its forward."""

    head: Any
    n_cand: int
    #: Emitting-row positions drawn by the unfiltered Gumbel-max.
    gumbel_rows: tuple[int, ...]
    #: ``top_k`` per emitting row (0 where the row keeps no top-k set).
    top_k: tuple[int, ...]


def shard_head(model: Any) -> Any:
    """The model's output head when it can hand back un-gathered shard rows, else ``None``."""
    head = getattr(model, "lm_head", None)
    return head if getattr(head, "defers_gather", False) else None


@contextmanager
def keep_vocab_shards(plan: ShardDrawPlan | None) -> Iterator[None]:
    """Run a forward whose head returns shard rows (``plan`` given) or full rows."""
    if plan is None:
        yield
        return
    plan.head.keep_shards = True
    try:
        yield
    finally:
        plan.head.keep_shards = False


@contextmanager
def capture_shard_rows(model: Any, enabled: bool) -> Iterator[Any]:
    """Record a decode graph whose head writes shard rows; yields its replay finisher.

    The graph then carries no vocab gather at all, and the finisher
    (``CapturedGraph.vocab_finish``) composes the full row after each replay
    unless the reader asked for shards (:func:`keep_vocab_shards`). ``None``
    when the head cannot defer: the graph keeps its gather.
    """
    head = shard_head(model) if enabled else None
    if head is None:
        yield None
        return
    head.keep_shards = True
    try:
        yield head.finish_shards
    finally:
        head.keep_shards = False


def _row_kind(sp: Any, vocab: int, n_cand: int) -> int | None:
    """0 greedy, -1 unfiltered stochastic, k for a top-k row; ``None``: needs the row."""
    if sp.is_greedy:
        return 0
    tk = sp.top_k
    if tk is not None and 0 < tk < vocab:
        return int(tk) if tk <= n_cand else None
    if sp.top_p < 1.0 or sp.min_p > 0.0:
        return None
    return -1


def _row_needs_full_vocab(mreq: Any, sp: Any) -> bool:
    if mreq.grammar is not None or mreq.grammar_state is not None or mreq.grammar_required:
        return True
    if sp.repetition_penalty != 1.0 or sp.frequency_penalty != 0.0 or sp.presence_penalty != 0.0:
        return True
    return bool(sp.logit_bias) or int(getattr(sp, "logprobs", 0) or 0) > 0


def plan_shard_draw(
    eng: Any, batch: Any, mirror: Any, slate: Sequence, emit_idx: Sequence[int]
) -> ShardDrawPlan | None:
    """This tick's :class:`ShardDrawPlan`, or ``None`` for the gathered row.

    A pure function of the head, the batch shape and the replicated mirror, so
    every rank of the head's group answers alike (module docstring).
    """
    head = shard_head(getattr(eng, "model", None))
    if head is None or not emit_idx or batch.is_prefill:
        return None
    from arbi_serve.distributed.spmd import _MirrorSamplingRequest
    from arbi_serve.engine._distributed_driver_ops import _spmd_needs_full_noise
    from arbi_serve.sampler.sampler import _USE_COUNTER_GUMBEL_FILTERED
    from arbi_serve.sampler.watermark_request import step_watermark_cache
    from arbi_serve.spec_decode.mtp_verify_sharded import N_CAND

    device = torch.device(eng.device)
    mreqs = [mirror.reqs[slate[i][0]] for i in emit_idx]
    views = [_MirrorSamplingRequest(m) for m in mreqs]
    if step_watermark_cache(device, views, eng.sampler.watermark_store) is not None:
        return None
    vocab = int(head.shard_vocab)
    kinds: list[int] = []
    for m, v in zip(mreqs, views, strict=True):
        kind = (
            None
            if _row_needs_full_vocab(m, v.sampling)
            else _row_kind(v.sampling, vocab, SERVED_TOP_K_CANDIDATES)
        )
        if kind is None:
            return None
        kinds.append(kind)
    # Off CUDA a stochastic row samples through the generator path, whose
    # noise is not keyed by token; a greedy slate draws the same anywhere.
    if device.type != "cuda" and any(kinds):
        return None
    if not _USE_COUNTER_GUMBEL_FILTERED and _spmd_needs_full_noise(views):
        return None
    if any(p.constrains_verify_slate(views) for p in eng.sampler.logits_processors):
        return None
    top_k = tuple(max(k, 0) for k in kinds)
    return ShardDrawPlan(
        head=head,
        n_cand=min(N_CAND, int(head.shard_window[1])) if any(top_k) else 1,
        gumbel_rows=tuple(i for i, k in enumerate(kinds) if k < 0),
        top_k=top_k,
    )


def tap_logits(plan: ShardDrawPlan | None, logits: torch.Tensor, model_runner: Any):
    """What the raw-logits tap may read this tick: nothing from a shard row.

    The tap is armed on one rank by a measurement tool, so it cannot steer a
    decision every rank has to share; its prefill-tick readers never meet a
    shard row (:func:`plan_shard_draw`). A decode-tick reader is told, once.
    """
    global _tap_warned
    if plan is None:
        return logits
    if getattr(model_runner, "_raw_logits_sink", None) is not None and not _tap_warned:
        _tap_warned = True
        logger.error(
            "raw-logits tap armed on a shard-drawn decode tick: the tick holds no full "
            "row, so the tap gets none (vocab_shard_draw, prefill ticks are unaffected)."
        )
    return None


def _winner_pairs(
    local: torch.Tensor, reqs: Sequence, row_seeds: torch.Tensor, start: int
) -> torch.Tensor:
    """``(E, 2)`` ``(raw logit, global index)`` of each row's shard Gumbel-max winner."""
    from arbi_serve.sampler.gumbel_argmax_triton import gumbel_argmax_from_seeds
    from arbi_serve.sampler.processors import apply_temperature

    scaled = apply_temperature(local.unsqueeze(0), reqs)[0]
    win = gumbel_argmax_from_seeds(scaled, row_seeds, index_base=start).unsqueeze(-1)
    return torch.cat([local.gather(-1, win).float(), (win + start).to(torch.float32)], dim=-1)


def _note_tie_overflow(gathered: torch.Tensor, vals: torch.Tensor, plan: ShardDrawPlan) -> None:
    """Count, on device, top-k rows where a shard's worst candidate reaches the k-th value."""
    from arbi_serve.spec_decode.mtp_draft_meta import h2d_async

    k = h2d_async(list(plan.top_k), dtype=torch.int64, device=vals.device)
    ordered = vals.sort(dim=-1, descending=True).values
    thresh = ordered.gather(-1, (k - 1).clamp_min(0).unsqueeze(-1)).squeeze(-1)
    shard_last = gathered[..., -1, 0]  # (tp, E)
    hit = (shard_last >= thresh).any(dim=0) & torch.isfinite(thresh) & (k > 0)
    acc = _tie_overflow.get(vals.device)
    if acc is None:
        acc = _tie_overflow[vals.device] = torch.zeros((), dtype=torch.int64, device=vals.device)
    acc.add_(hit.sum())


class _UnfilteredSampling:
    """A request's sampling view with the top-k / top-p / min-p filters spent."""

    __slots__ = ("_sp",)

    def __init__(self, sp: Any) -> None:
        self._sp = sp

    top_k = -1
    top_p = 1.0
    min_p = 0.0

    def __getattr__(self, name: str):
        if name.startswith("_"):
            raise AttributeError(name)
        return getattr(self._sp, name)


class _UnfilteredRequest:
    """A slate row whose filters the candidate row already applied (:func:`_filter_candidates`)."""

    __slots__ = ("_req", "sampling")

    def __init__(self, req: Any) -> None:
        self._req = req
        self.sampling = _UnfilteredSampling(req.sampling)

    def __getattr__(self, name: str):
        if name.startswith("_"):
            raise AttributeError(name)
        return getattr(self._req, name)


def _filter_params(plan, reqs, dev):
    """Stage replicated sampling metadata without reading the device."""
    from arbi_serve.spec_decode.mtp_draft_meta import h2d_async

    temps, tops_p, mins_p = [], [], []
    for r in reqs:
        sp = r.sampling
        t = float(sp.temperature)
        temps.append(1.0 if sp.is_greedy or t <= 0.0 else t)
        tops_p.append(float(sp.top_p) if not sp.is_greedy else 1.0)
        mins_p.append(float(sp.min_p) if not sp.is_greedy else 0.0)
    params = h2d_async(temps + tops_p + mins_p, dtype=torch.float32, device=dev).view(3, -1)
    k = h2d_async(list(plan.top_k), dtype=torch.int64, device=dev)
    return params, k


def _filter_candidates(vals: torch.Tensor, plan: ShardDrawPlan, reqs: Sequence) -> torch.Tensor:
    """Mask bounded candidates; CUDA serving completes omitted ties separately."""
    dev = vals.device
    params, k = _filter_params(plan, reqs, dev)
    if vals.is_cuda:
        from arbi_serve.sampler.shard_topk_triton import filter_candidate_values

        acc = _tie_overflow.get(dev)
        if acc is None:
            acc = _tie_overflow[dev] = torch.zeros((), dtype=torch.int64, device=dev)
        return filter_candidate_values(
            vals, params, k, tie_counter=acc, shard_candidates=plan.n_cand
        )
    x = vals.float() / params[0].unsqueeze(-1)
    ordered, order = x.sort(dim=-1, descending=True)
    rank = torch.arange(x.shape[-1], device=dev).unsqueeze(0)
    kth = ordered.gather(-1, (k - 1).clamp_min(0).unsqueeze(-1))
    keep_sorted = (k.unsqueeze(-1) == 0) | (ordered >= kth)
    masked = ordered.masked_fill(~keep_sorted, float("-inf"))
    probs = masked.softmax(dim=-1)
    before = probs.cumsum(dim=-1) - probs
    top_p = params[1].unsqueeze(-1)
    nucleus = (before < top_p) | (rank == 0) | (top_p >= 1.0)
    # The served CUDA nucleus includes the entire boundary tie group.
    pivot = masked.masked_fill(~nucleus, float("inf")).min(dim=-1, keepdim=True).values
    keep_sorted &= ordered >= pivot
    keep_sorted &= probs >= params[2].unsqueeze(-1) * probs[:, :1]
    keep = torch.empty_like(keep_sorted).scatter_(-1, order, keep_sorted)
    return vals.masked_fill(~keep, float("-inf"))


def _completed_cuda_candidates(local, plan, reqs, row_seeds, start):
    from arbi_serve.sampler.shard_topk_triton import (
        complete_topk_ties,
        filter_shard_payload,
        shard_topk_pairs,
    )
    from arbi_serve.spec_decode.mtp_draft_meta import h2d_async

    params, k = _filter_params(plan, reqs, local.device)
    whole = h2d_async(
        [i in plan.gumbel_rows for i in range(local.shape[0])],
        dtype=torch.bool,
        device=local.device,
    )
    pairs = shard_topk_pairs(local, shard_start=start, n_cand=plan.n_cand + 1)
    payload = complete_topk_ties(
        local, pairs, params, row_seeds, whole, shard_start=start, n_cand=plan.n_cand
    )
    tp = int(plan.head.shard_group.size)
    gathered = plan.head.shard_group.all_gather(payload, dim=0).view(tp, *payload.shape)
    merged = gathered.permute(1, 0, 2, 3).reshape(local.shape[0], tp * (plan.n_cand + 2), 2)
    acc = _tie_overflow.get(local.device)
    if acc is None:
        acc = _tie_overflow[local.device] = torch.zeros((), dtype=torch.int64, device=local.device)
    return filter_shard_payload(
        merged, params, k, n_cand=plan.n_cand, tie_counter=acc, logits_dtype=local.dtype
    )


def _candidate_row(vals, idx, head, dtype):
    row = torch.full(
        (vals.shape[0], int(head.shard_vocab)), float("-inf"), dtype=dtype, device=vals.device
    )
    row.scatter_(1, idx, vals.to(dtype))
    return row


def shard_candidate_row(
    logits: torch.Tensor,  # (E, vocab) shard rows: this rank's columns valid
    plan: ShardDrawPlan,
    reqs: Sequence,
    row_seeds: torch.Tensor,  # (E,) int64, the sampler's own row seeds
) -> tuple[torch.Tensor, Sequence]:
    """The ``(E, vocab)`` row the sampler draws from, and the rows to draw it for.

    The row is ``-inf`` but the candidates (filtered, for a slate with a top-k
    row: :func:`_filter_candidates`, whose rows come back with their filters
    spent). One small exchange over the head's group replaces the vocab gather;
    see the module docstring for why the sampler's draw on this row is the
    gathered row's. Stream-ordered and host-sync free.
    """
    from arbi_serve.spec_decode.mtp_draft_meta import h2d_async
    from arbi_serve.spec_decode.verify_sharded import shard_topk_candidates

    head = plan.head
    start, width = head.shard_window
    local = logits[:, start : start + width].contiguous()
    if local.is_cuda and any(plan.top_k):
        vals, idx = _completed_cuda_candidates(local, plan, reqs, row_seeds, start)
        _SHARD_DRAW.fired += 1
        return _candidate_row(vals, idx, head, logits.dtype), [_UnfilteredRequest(r) for r in reqs]
    every_row_gumbel = len(plan.gumbel_rows) == local.shape[0]
    if plan.n_cand == 1 and every_row_gumbel:
        pairs = _winner_pairs(local, reqs, row_seeds, start)
    elif plan.n_cand == 1:
        best = local.argmax(dim=-1, keepdim=True)
        pairs = torch.cat(
            [local.gather(-1, best).float(), (best + start).to(torch.float32)], dim=-1
        )
    else:
        pairs = shard_topk_candidates(local, shard_start=start, n_valid=width, n_cand=plan.n_cand)
    if plan.gumbel_rows and not (plan.n_cand == 1 and every_row_gumbel):
        win = _winner_pairs(local, reqs, row_seeds, start)
        rows = h2d_async(list(plan.gumbel_rows), dtype=torch.int64, device=local.device)
        if plan.n_cand == 1:
            pairs.index_copy_(0, rows, win.index_select(0, rows))
        else:
            # The last slot: a top-k row never draws from it and an
            # unfiltered row draws from nothing else.
            pairs[:, -1, :].index_copy_(0, rows, win.index_select(0, rows))
    pairs = pairs.view(local.shape[0], plan.n_cand, 2)
    group = head.shard_group
    tp = int(group.size)
    gathered = group.all_gather(pairs, dim=0).view(tp, *pairs.shape)  # (tp, E, n, 2)
    merged = gathered.permute(1, 0, 2, 3).reshape(pairs.shape[0], tp * plan.n_cand, 2)
    vals = merged[..., 0]
    idx = merged[..., 1].to(torch.int64)
    if any(plan.top_k):
        if not vals.is_cuda:
            _note_tie_overflow(gathered, vals, plan)
        vals = _filter_candidates(vals, plan, reqs)
        reqs = [_UnfilteredRequest(r) for r in reqs]
    # The row keeps the head's dtype: the candidates are its values exactly,
    # and the chain then rounds (temperature) as it rounds the gathered row.
    row = _candidate_row(vals, idx, head, logits.dtype)
    _SHARD_DRAW.fired += 1
    return row, reqs


def warm_shard_draw_kernels(eng: Any) -> int:
    """Compile shard draw kernels at the served row classes, before ready.

    The kernel specializes on the row width, and a shard is narrower than the
    vocab :func:`~arbi_serve.sampler.kernel_warmup.warm_sampler_kernels` warms.
    """
    head = shard_head(getattr(eng, "model", None))
    if head is None or not torch.cuda.is_available():
        return 0
    from arbi_serve.sampler.gumbel_argmax_triton import gumbel_argmax_from_seeds
    from arbi_serve.sampler.kernel_warmup import _representative_rows

    start, width = head.shard_window
    n_cand = min(SERVED_TOP_K_CANDIDATES, width)
    rows = _representative_rows(eng.device, width, int(eng.cfg.batch.max_batch))
    for b in rows:
        seeds = torch.arange(1, b + 1, dtype=torch.int64, device=eng.device)
        for dtype in (torch.bfloat16, torch.float32):
            logits = torch.randn(b, width, dtype=dtype, device=eng.device)
            gumbel_argmax_from_seeds(logits, seeds, index_base=start)
            if SERVED_TOP_K_CANDIDATES:
                from arbi_serve.sampler.shard_topk_triton import (
                    complete_topk_ties,
                    filter_shard_payload,
                    shard_topk_pairs,
                )

                params = torch.tensor([0.7, 0.9, 0.05], device=eng.device)
                params = params[:, None].expand(3, b).contiguous()
                k = torch.full(
                    (b,),
                    min(SERVED_TOP_K_CANDIDATES, int(head.shard_vocab) - 1),
                    dtype=torch.int64,
                    device=eng.device,
                )
                pairs = shard_topk_pairs(logits, shard_start=start, n_cand=n_cand + 1)
                whole = torch.zeros((b,), dtype=torch.bool, device=eng.device)
                payload = complete_topk_ties(
                    logits,
                    pairs,
                    params,
                    seeds,
                    whole,
                    shard_start=start,
                    n_cand=n_cand,
                )
                merged = payload.repeat(1, int(head.shard_group.size), 1)
                acc = _tie_overflow.setdefault(
                    torch.device(eng.device),
                    torch.zeros((), dtype=torch.int64, device=eng.device),
                )
                filter_shard_payload(
                    merged,
                    params,
                    k,
                    tie_counter=acc,
                    n_cand=n_cand,
                    logits_dtype=dtype,
                )
                acc.zero_()
    return 2 * len(rows) * (3 if SERVED_TOP_K_CANDIDATES else 1)


def shard_draw_stats() -> dict[str, int]:
    """Lifetime counters (reads the device tie counter: call off the step path)."""
    ties = sum(int(t.item()) for t in _tie_overflow.values())
    return {"vocab_shard_draw_steps": _SHARD_DRAW.fired, "vocab_shard_draw_tie_overflow": ties}


__all__ = [
    "ShardDrawPlan",
    "capture_shard_rows",
    "keep_vocab_shards",
    "plan_shard_draw",
    "shard_candidate_row",
    "shard_draw_stats",
    "shard_head",
    "tap_logits",
    "warm_shard_draw_kernels",
]
# ---- vocab_window.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""The global-vocab range a rank-local logits slice covers.

A vocab-parallel rank holds a contiguous slice of the vocabulary, so every
per-token logits transform the K=1 sampler applies to a full row — a
``logit_bias`` offset, the three penalties, a grammar mask — has an exact
restriction to that slice: keep the entries whose GLOBAL id lands inside
the window, drop the rest, and index by ``global_id - start``.

This exists so those transforms take the window as a PARAMETER rather than
being reimplemented shard-side. A second copy of penalty or bias arithmetic
would be a second thing to keep in step with the K=1 chain, and the two
would drift silently — the sharded draw would honour a knob the gathered
draw had since changed the meaning of, with nothing comparing them.

``None`` everywhere a window is accepted means the full vocabulary, and the
full-vocab case must stay byte-identical to the un-windowed code it
replaced: the shard-resident path is an optimisation, never a change to
what the K=1 draw would have produced.
"""

from __future__ import annotations

from dataclasses import dataclass

import torch

__all__ = ["BITMASK_WORD", "VocabWindow", "window_bounds"]

#: Tokens per word of a packed int32 token bitmask (xgrammar's mask format).
#: A window can address its own bits of such a mask only when its bounds are
#: multiples of this, so the gate that screens for the property and the
#: masker that requires it must agree on the number — one definition, not
#: two literals that happen to match today.
BITMASK_WORD = 32


@dataclass(frozen=True)
class VocabWindow:
    """Global ids ``[start, start + width)``, out of a ``vocab_size`` vocab.

    ``width`` is the number of REAL vocab columns the local logits tensor
    carries, which is not always its last dimension: a short final shard is
    zero-padded up to the uniform per-rank width, and those pad columns are
    not tokens. The caller passes the tensor already trimmed to ``width``.
    """

    start: int
    width: int
    vocab_size: int

    def __post_init__(self) -> None:
        if self.start < 0 or self.width < 0:
            raise ValueError(f"VocabWindow: start={self.start} width={self.width} must be >= 0")
        if self.stop > self.vocab_size:
            raise ValueError(
                f"VocabWindow: [{self.start}, {self.stop}) escapes the "
                f"vocabulary (vocab_size={self.vocab_size})"
            )

    @property
    def stop(self) -> int:
        """One past the last global id this window covers."""
        return self.start + self.width

    @property
    def is_bitmask_aligned(self) -> bool:
        """Whether this window slices a packed token bitmask on a word."""
        return self.start % BITMASK_WORD == 0 and self.width % BITMASK_WORD == 0

    @property
    def bitmask_word_start(self) -> int:
        """Index of the first bitmask word this window carries."""
        return self.start // BITMASK_WORD

    @property
    def is_full(self) -> bool:
        """Whether the window is the whole vocabulary."""
        return self.start == 0 and self.width == self.vocab_size

    def slice_rows(self, full: torch.Tensor) -> torch.Tensor:
        """Restrict a full-vocab ``(..., vocab_size)`` tensor to the window.

        A VIEW, not a copy: the shard-resident path's whole point is not to
        materialise anything vocab-shaped per step, and a windowed view of
        a resident buffer (the penalty accumulator's counts, its additive
        entry) costs nothing. Row stride survives, so a Triton kernel that
        takes ``stride(0)`` reads it directly.
        """
        return full[..., self.start : self.stop]

    def localize(self, global_ids: torch.Tensor) -> torch.Tensor:
        """Global ids → local columns. Only valid for ids inside the window."""
        return global_ids - self.start

    def contains(self, global_ids: torch.Tensor) -> torch.Tensor:
        """Boolean mask of which ``global_ids`` this window carries."""
        return (global_ids >= self.start) & (global_ids < self.stop)


def window_bounds(window: VocabWindow | None, vocab_size: int) -> tuple[int, int]:
    """``(start, stop)`` for ``window``, or the full vocab when it is ``None``."""
    if window is None:
        return 0, vocab_size
    return window.start, window.stop
# ---- watermark.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Keyed-noise text watermark for the counter-based Gumbel-max sampler.

The Aaronson-family watermark (the scheme SynthID-Text descends from)
changes ONLY the source of the sampler's randomness: instead of a fresh
per-step Philox seed, the stochastic draw for each row is keyed on
``PRF(watermark_key, last-H sampled tokens)``. The drawn token is still
``argmax_v(logit_v + Gumbel(seed, v))`` — an exact categorical draw from
``softmax(logits)`` for any fixed seed source — so the per-token sampling
distribution, support, temperature/top-k/top-p semantics, and greedy
behaviour are all unchanged. What changes is that the choice becomes a
deterministic function of ``(key, context)``, which a key-holder can
verify after the fact (see :func:`detect_tokens`).

Context state lives ON DEVICE. Under async output the host does not yet
know the previous sampled token when the next step's seeds are needed, so
the last-``H``-token window per request is kept in a pooled ``(rows, H)``
device ring advanced from the sampler's own output tensor each step (a
D2D shift — no host sync). A row is (re)built from the host-side
``prompt_token_ids + output_token_ids`` tail only when the host state is
provably current: at a request's first sample (nothing sampled yet) and
after a preemption/recompute prompt rewrite (detected by a changed prompt
length, exactly like :mod:`arbi_serve.sampler.penalty_history`).

Repeated-context masking (the SynthID rule): a context window that has
already keyed a draw for this request must not key another one — the same
seed would force the same token and can lock a generation into a cycle.
Each row carries a device-side Bloom filter of the context hashes it has
used; a hit falls that step back to the normal (non-watermark) seed. A
Bloom false positive merely skips the watermark on one extra step (the
statistic just loses one token of signal); a false negative is impossible,
so a genuinely repeated context can never re-key a draw.

Detection needs no model and no GPU: recompute each position's seed from
the preceding ``H`` tokens with the same hash, evaluate the SAME
Philox4x32-10 uniform the sampling kernel generated at the chosen token
(:func:`philox_uniform_host` mirrors ``_philox_uniform`` bit-for-bit),
and test the uniforms for the upward bias the argmax leaves. Under the
null (text not produced with this key) each scored uniform is i.i.d.
``U(0,1)`` and the summed ``-log(1-u)`` statistic is ``Gamma(n, 1)``.

Scope: the watermark keys the K=1 counter-Gumbel decode paths AND the
MTP spec-decode path,
where keyed determinism collapses verification to EXACT-MATCH against
the target's keyed draw (see
:meth:`~arbi_serve.spec_decode.rejection_sampler.GraphSafeRejectionSampler.
_sample_batched_keyed_exact`) — full-density watermark, emitted stream
bit-identical to non-speculative keyed sampling. Both MTP verify layouts
are keyed — gathered via the residual/bonus kernel, TP>1 sharded via the
rank-symmetric keyed argmax — and any bypassing layout is refused by name.
"""

from __future__ import annotations

import math
from collections.abc import Callable, Sequence

import torch

from arbi_serve.sampler.rank_symmetric import (
    _GOLDEN_GAMMA,
    _S63,
    _U64,
    _splitmix64,
)
from arbi_serve.sampler.watermark_request import watermark_keep_mask  # noqa: F401 — re-export

#: Ring pad for context positions before the sequence start (a prompt
#: shorter than ``H``). Never a real token id; hashes to a defined value.
_CTX_SENTINEL = -1

#: Per-row Bloom filter geometry: 2048 int64 words = 131072 bits, 2
#: probes. At 4k generated tokens the false-positive rate is ~0.4%; at
#: 32k it is ~15% — a FP only skips the watermark for one step, so the
#: cost is a slightly sparser mark on very long generations, never a
#: wrong token distribution.
_BLOOM_WORDS = 2048
_BLOOM_BITS = _BLOOM_WORDS * 64

#: Domain-separation constants for the two Bloom probes (arbitrary odd
#: 64-bit values, distinct from the SplitMix64 mixers).
_PROBE_C1 = 0xA24BAED4963EE407
_PROBE_C2 = 0x9FB21C651E98DF25

#: Domain-separation constant for the MTP masked-depth fallback seeds
#: (a per-(depth, row) remix of the rank-agreed step seed). Must match
#: ``_wm_mtp_seed_kernel``.
_BASE_REMIX = 0xC2B2AE3D27D4EB4F
#: Domain separation for a row's unkeyed salt (derived from its request id).
_SALT_REMIX = 0xD6E8FEB86659FD93


def row_salt(key: int, request_id: int) -> int:
    """Unsigned 64-bit per-request salt for the unkeyed fallback draws.

    The server's watermark key is folded in. Without it the salt would be a
    function of the request id and a published constant alone, so anyone
    could reproduce the fallback noise for a position, compare it against
    the emitted token, and learn which positions were drawn UNKEYED — a
    map of the gaps in the watermark, which is what stripping or forging
    one needs. The key makes the fallback unpredictable to everyone who
    does not already hold it, and the drafter and the verify read the same
    cache row, so their coupling is unaffected.
    """
    return _splitmix64((int(key) ^ _splitmix64((int(request_id) ^ _SALT_REMIX) & _U64)) & _U64)


def unkeyed_fallback_seed(salt: int, position: int) -> int:
    """Positive 63-bit seed for an UNKEYED draw at absolute token ``position``.

    Used wherever a draw must not be keyed on its context: a Bloom-masked
    depth (context window already keyed once) and every depth of an
    opted-out row. It depends only on the row's salt and the position of
    the token being drawn, both of which the drafter that proposes the
    token and the verify that judges it read from the same cache state, so
    the two draw with the same noise and their argmaxes agree whenever
    their distributions do. It never repeats within a request (positions
    are unique) and never keys on the context.
    """
    return _splitmix64((salt ^ _splitmix64((position + _BASE_REMIX) & _U64)) & _U64) & _S63


def _signed64(v: int) -> int:
    """Reinterpret an unsigned 64-bit literal as the same-bits int64."""
    v &= _U64
    return v - (1 << 64) if v >= (1 << 63) else v


_GAMMA_S = _signed64(_GOLDEN_GAMMA)
_MIX_A_S = _signed64(0xBF58476D1CE4E5B9)
_MIX_B_S = _signed64(0x94D049BB133111EB)


def watermark_key_configured(raw: str | None) -> bool:
    """True iff ``raw`` is a watermark key an operator actually set.

    ``ARBI_WATERMARK_KEY=`` (empty) is how compose spells "leave this off",
    but the generic ``str | None`` parser deliberately PRESERVES the
    unset-vs-empty distinction — ``ARBI_FOO=`` is a real way to override an
    earlier export back to empty — so the flag lands as ``""``, not ``None``.
    Every ``is not None`` test on it then answers "configured" for a server
    that has no key, and the report lies in the direction of MORE configured
    than it is: the boot line masks a nonexistent secret as ``<set, masked>``
    and per-request traces mark unwatermarked requests as watermarked.

    One predicate, so the two readers cannot disagree about what "set" means.
    """
    return bool(raw and raw.strip())


def parse_watermark_key(raw: str) -> int:
    """Parse ``ARBI_WATERMARK_KEY`` (decimal or ``0x…`` hex) → 64-bit int."""
    try:
        return int(raw, 0) & _U64
    except ValueError:
        raise ValueError(
            f"ARBI_WATERMARK_KEY: cannot parse {raw!r} as an integer key "
            "(use decimal or 0x-prefixed hex)"
        ) from None


#: The key published on arbicity.com's interactive watermark demo. It is a
#: teaching device with zero secrecy — a boot configured with it must be a
#: copy-paste mistake, so the boot guard refuses it.
PUBLIC_DEMO_KEY = 0x5EED0FA11


def watermark_key_is_public_demo(raw: str | None) -> bool:
    """True iff the configured key is the publicly disclosed demo key.

    Both write-doors already refuse it — the boot guard
    (``engine.build_phases_load``) and the live override coercion
    (``config_overrides._as_watermark_key``) — so a running server should
    never answer True. That is precisely why a status surface ASKS rather
    than assumes: a key that reached the flag by any other route would
    otherwise be presented as a private mark, and a mark anyone can
    reproduce or strip proves nothing about who wrote the text.
    """
    if not watermark_key_configured(raw):
        return False
    try:
        return parse_watermark_key(str(raw)) == PUBLIC_DEMO_KEY
    except ValueError:
        return False


#: How the key in force reached this process. Also the refusal reason on
#: :data:`_KEY_FROM_ENV_COUNTER`, so a flag-truth scrape names the source
#: without a second surface to keep in step.
KEY_SOURCE_ENVIRONMENT = "environment"
KEY_SOURCE_OFF = "watermarking_off"

#: Context-window width: how many trailing tokens are hashed into each draw's
#: seed. It is a parameter of the MARK, not of the deployment — the detector
#: hashes the same window, so a server that used a different H produces text
#: no detector can score. Changing it is changing the scheme, which means
#: changing both sides together.
WATERMARK_H = 4


def effective_watermark_key_from_flags(flags: object) -> tuple[str | None, str]:
    """The key in force and where it came from.

    Returns ``(key_string_or_None, source)``; ``source`` is
    :data:`KEY_SOURCE_ENVIRONMENT` or :data:`KEY_SOURCE_OFF`. Every reader
    that decides behaviour off "is there a key" goes through here rather than
    reading the flag, so there is ONE answer to "is this server
    watermarking": an operator handing over a secret is also a request to use
    it, and no key means off. There is no third state.
    """
    key = getattr(flags, "watermark_key", None)
    if watermark_key_configured(key):
        return key, KEY_SOURCE_ENVIRONMENT
    return None, KEY_SOURCE_OFF


def watermark_state(key: str | None) -> tuple[bool, str | None]:
    """Whether keyed watermarking is ACTUALLY applied, and why not when it is not.

    The two conditions :func:`get_watermark_cache` gates on, answered off the
    flags alone so a status reader needs no device and no engine.

    Returns ``(active, inactive_reason)`` — the reason is a plain sentence
    naming what to change, and is ``None`` exactly when ``active``. It never
    contains the key.
    """
    if not watermark_key_configured(key):
        return False, "no watermark key is configured on this server"
    return True, None


def watermark_state_from_flags(flags: object) -> tuple[bool, str | None]:
    """:func:`watermark_state` against the key actually in force."""
    in_force, _source = effective_watermark_key_from_flags(flags)
    return watermark_state(in_force)


def report_watermark_resolution(flags: object, log) -> tuple[str | None, str]:
    """Resolve the key ONCE at boot, name its source, and count it.

    Fires ``watermark_key_from_environment`` when the operator supplied the
    secret and refuses it — with the source as the reason — when the server is
    not watermarking at all. A resolver that never ran reads as fired 0,
    refused 0, which is a different and earlier failure than either.

    Returns ``(key, source)``. The key is never logged: the status line
    carries :func:`mask_watermark_key`'s two-hex-digit form, which is what
    every other watermark status surface in the tree already prints.
    """
    from arbi_serve.flag_truth import FiringWindow, path_counter  # noqa: PLC0415

    counter = path_counter("watermark_key_from_environment", FiringWindow.BOOT)
    key, source = effective_watermark_key_from_flags(flags)
    if source == KEY_SOURCE_ENVIRONMENT:
        counter.fired = 1
        log.debug(
            "watermark: ENABLED (key %s from the environment, H=%d)",
            mask_watermark_key(parse_watermark_key(str(key))),
            WATERMARK_H,
        )
    else:
        counter.refuse(KEY_SOURCE_OFF)
        log.debug("watermark: disabled (no ARBI_WATERMARK_KEY)")
    return key, source


def mask_watermark_key(key: int) -> str:
    """Loggable form of a key: first and last hex byte only."""
    hx = f"{key & _U64:016x}"
    return f"0x{hx[:2]}…{hx[-2:]}"


# ── Host reference hash (detector + GPU parity tests) ─────────────────


def derive_watermark_hash(key: int, ctx: Sequence[int]) -> int:
    """Unsigned 64-bit context hash — the pre-mask value seeds AND Bloom
    probes derive from. Pure-Python ints; the single source of truth the
    torch implementation is parity-tested against."""
    h = key & _U64
    for j, t in enumerate(ctx):
        h = _splitmix64(h ^ _splitmix64((int(t) + j * _GOLDEN_GAMMA) & _U64))
    return h


def derive_watermark_seed(key: int, ctx: Sequence[int]) -> int:
    """Positive 63-bit Philox seed for the draw keyed on ``(key, ctx)`` —
    the same masking contract as ``rank_symmetric.derive_row_seed``."""
    return derive_watermark_hash(key, ctx) & _S63


# ── Torch (device) hash — bit-identical to the host reference ─────────


def _lshr(x: torch.Tensor, k: int) -> torch.Tensor:
    """Logical (zero-fill) right shift on int64 (torch ``>>`` is arithmetic)."""
    return (x >> k) & ((1 << (64 - k)) - 1)


def _splitmix64_t(x: torch.Tensor) -> torch.Tensor:
    """SplitMix64 step on int64 tensors (two's-complement wraparound ==
    the unsigned reference's low 64 bits)."""
    x = x + _GAMMA_S
    x = (x ^ _lshr(x, 30)) * _MIX_A_S
    x = (x ^ _lshr(x, 27)) * _MIX_B_S
    return x ^ _lshr(x, 31)


def watermark_hash_rows(key: int, ctx: torch.Tensor) -> torch.Tensor:
    """Batched :func:`derive_watermark_hash` → ``(B,)`` int64 (same bits,
    signed view). ``ctx`` is ``(B, H)`` int64; the loop is over ``H``
    (small constant), vectorized over rows."""
    B, H = ctx.shape
    h = torch.full((B,), _signed64(key), dtype=torch.int64, device=ctx.device)
    for j in range(H):
        h = _splitmix64_t(h ^ _splitmix64_t(ctx[:, j] + _signed64(j * _GOLDEN_GAMMA)))
    return h


# ── Per-request device context ring + Bloom filter ────────────────────

#: An allocator for a cache's DEVICE pools: ``(shape, dtype, device) -> tensor``.
#:
#: These pools are cross-step state with FROZEN addresses — a captured graph
#: bakes them — so they are exactly the class that must not be minted by the
#: first step that needs them, in whatever pool is ambient there. Ambient
#: during a served forward is ``scratch.forward_arena``, and a tensor that
#: survives the step boundary there makes ``release_idle_forward_arena``
#: refuse WHOLE-POOL: 0.05 MiB of watermark state holds the pool's entire idle
#: tail out of KV for the life of the process, because the release cannot be
#: partial. The same argument and the same remedy as the sampler's mask
#: buffers (:func:`~arbi_serve.sampler.topk_topp_triton.
#: install_sampler_scratch_pool`). The member's build installs one on its
#: sampler's :class:`WatermarkStore`.
PoolAllocate = Callable[[tuple[int, ...], torch.dtype, torch.device], torch.Tensor]


class WatermarkContextCache:
    """Pooled device state: ``(rows, H)`` context ring + per-row Bloom.

    One instance per device (see :func:`get_watermark_cache`). Row
    lifecycle mirrors :class:`~arbi_serve.sampler.penalty_history.
    PenaltyHistoryCache`: keyed by ``request_id``, LRU eviction of rows
    not in the batch being built, owned by one member's
    :class:`WatermarkStore` on its ``Sampler`` (request ids are unique only
    within one engine build).
    """

    def __init__(
        self, device: torch.device, key: int, h: int, allocate: PoolAllocate | None = None
    ) -> None:
        if h < 1:
            raise ValueError(f"watermark: context width H must be >= 1, got {h}")
        self.device = device
        self.key = int(key) & _U64
        self.h = int(h)
        #: The owning store's pool hook; ``None`` allocates ambient (tests, CPU).
        self._allocate = allocate
        # Device pools, allocated at a CAPACITY and thereafter written in
        # place. Every tensor a captured graph reads by address lives here;
        # see :meth:`reserve_rows` for why widening one is a checked event.
        self._ring: torch.Tensor | None = None  # (capacity, H) int64
        self._bloom: torch.Tensor | None = None  # (capacity, _BLOOM_WORDS) int64
        self._pos: torch.Tensor | None = None  # (capacity,) int64 — committed length
        self._salt: torch.Tensor | None = None  # (capacity,) int64 — per-request salt
        # (1,) int64 device copy of the key for the fused CUDA kernel
        # (read in-kernel; avoids re-uploading a scalar every step).
        self._key_dev: torch.Tensor | None = None
        self._capacity = 0
        self._rows = 0
        #: Capacity the pools are frozen at, or 0 while growth is allowed.
        self._reserved = 0
        #: Bumped by every reallocation — the addresses moved at each bump.
        self.pool_epoch = 0
        self._owner: list[int] = []  # request_id, or -1 when free
        self._plen: list[int] = []  # prompt len at (re)build — rewrite detector
        self._touch: list[int] = []  # tick of last use, for LRU eviction
        self._by_request: dict[int, int] = {}
        self._tick = 0
        # Slate → row-index tensor cache: rebuilt only when the slate's
        # request-id tuple changes (same invalidation idea as the
        # sampler's metadata cache). ``advance`` reuses the tensor the
        # same step's ``row_seeds`` built.
        self._slate_ids: tuple[int, ...] | None = None
        #: ``(B,)`` prefix VIEW of ``_slate_rows_pool`` — a fresh view object
        #: per slate width, always at the pool's base address.
        self._slate_rows: torch.Tensor | None = None
        self._slate_rows_pool: torch.Tensor | None = None  # (capacity,) int64
        self._slate_rows_host: torch.Tensor | None = None  # pinned staging
        #: Per-row watermark opt-out mask consumed by :meth:`_apply_row_keep`.
        self._keep_pool: torch.Tensor | None = None  # (capacity,) bool
        self._keep_host: torch.Tensor | None = None  # pinned staging

    # -- pool growth / row claim (penalty_history pattern) ---------------

    def _pool_empty(self, shape: tuple[int, ...], dtype: torch.dtype) -> torch.Tensor:
        """Allocate a context pool through the store's hook when one is installed."""
        if self._allocate is not None:
            return self._allocate(shape, dtype, self.device)
        return torch.empty(shape, dtype=dtype, device=self.device)

    def reserve_rows(self, rows: int) -> None:
        """Size the device pools for ``rows`` concurrent requests, then FREEZE
        their addresses.

        Call this with the engine's ``cfg.batch.max_batch`` — the scheduler's
        admission width, and so the widest slate the pools can ever be asked
        for — before recording a cudagraph over any keyed path. Afterwards
        ``_ring``, ``_bloom``, ``_slate_rows`` and the keep mask keep the
        addresses the graph records, and a slate that would need more rows
        raises instead of quietly reallocating underneath it.

        The refusal is the point. A reallocation under a live graph does not
        fail — the graph replays against freed storage and the draw is keyed
        on whatever now occupies it, so the watermark is WRONG rather than
        slow and nothing raises to say so.
        """
        if rows < 1:
            raise ValueError(f"watermark: reserve_rows needs rows >= 1, got {rows}")
        if rows > self._capacity:
            self._grow_pool(rows)
        self._reserved = self._capacity

    def _grow_pool(self, capacity: int) -> None:
        """Reallocate every device pool at ``capacity`` rows — the ONLY event
        that moves their ``data_ptr``s, and refused once reserved.

        ``torch.inference_mode(False)`` is load-bearing for the same reason
        as the xgrammar bitmask buffers: these pools are cross-step state
        written from BOTH the K=1 sampler (outside the forward's
        ``inference_mode``) and the MTP seed/verify helpers (inside it).
        Allocated under ``inference_mode`` they become inference tensors and
        the next outside-the-window in-place write raises.
        """
        if self._reserved:
            raise RuntimeError(
                f"watermark: a slate needs {capacity} pooled rows but the "
                f"context pools are reserved at {self._reserved}. Growing them "
                "would move _ring/_bloom/_slate_rows to new addresses, and any "
                "cudagraph recorded against the old ones would then key its "
                "draws on freed storage — a mis-keyed draft, not a slow one. "
                "Reserve the engine's cfg.batch.max_batch, which bounds the "
                "slate, before capture."
            )
        pin = self.device.type == "cuda"
        with torch.inference_mode(False):
            # THROUGH THE ENGINE'S POOL HOOK, never the ambient allocator.
            # Every tensor below outlives the step that first needs one, and
            # ambient during a served forward is the per-step forward arena,
            # where a survivor makes the whole-pool release refuse. See
            # :data:`PoolAllocate`.
            new_ring = self._pool_empty((capacity, self.h), torch.int64)
            new_ring.fill_(_CTX_SENTINEL)
            new_bloom = self._pool_empty((capacity, _BLOOM_WORDS), torch.int64)
            new_bloom.zero_()
            new_pos = self._pool_empty((capacity,), torch.int64)
            new_pos.zero_()
            new_salt = self._pool_empty((capacity,), torch.int64)
            new_salt.zero_()
            if self._ring is not None and self._capacity:
                new_ring[: self._capacity] = self._ring
                new_bloom[: self._capacity] = self._bloom
                new_pos[: self._capacity] = self._pos
                new_salt[: self._capacity] = self._salt
            self._slate_rows_pool = self._pool_empty((capacity,), torch.int64)
            self._slate_rows_pool.zero_()
            self._keep_pool = self._pool_empty((capacity,), torch.bool)
            self._keep_pool.fill_(True)
            self._slate_rows_host = torch.zeros((capacity,), dtype=torch.int64, pin_memory=pin)
            self._keep_host = torch.ones((capacity,), dtype=torch.bool, pin_memory=pin)
        self._ring = new_ring
        self._bloom = new_bloom
        self._pos = new_pos
        self._salt = new_salt
        self._capacity = capacity
        self.pool_epoch += 1
        # The old slate view addressed storage this call just dropped.
        self._slate_ids = None
        self._slate_rows = None

    def _ensure_key_dev(self) -> None:
        """The device-side key, in the pool the context ring lives in.

        One int64, and it survives the step boundary like the rings do — which
        is all it takes to make the whole-pool arena release refuse.
        """
        if self._key_dev is not None and self._key_dev.device == self.device:
            return
        with torch.inference_mode(False):
            self._key_dev = self._pool_empty((1,), torch.int64)
            self._key_dev.fill_(_signed64(self.key))

    def _ensure(self, rows: int) -> None:
        """Make ``rows`` pool rows claimable.

        Widening the pools' CAPACITY is a separate, checked event
        (:meth:`_grow_pool`); claiming more rows inside an existing capacity
        only extends the host-side ownership bookkeeping, so the device
        addresses a graph recorded stay put.
        """
        if rows <= self._rows:
            return
        if rows > self._capacity:
            self._grow_pool(rows)
        for _ in range(rows - self._rows):
            self._owner.append(-1)
            self._plen.append(-1)
            self._touch.append(-1)
        self._rows = rows

    def _claim_row(self, request_id: int) -> int:
        for row in range(self._rows):
            if self._owner[row] == -1:
                break
        else:
            row = -1
            oldest = self._tick
            for r in range(self._rows):
                if self._touch[r] < oldest:
                    oldest = self._touch[r]
                    row = r
            if row < 0:
                self._ensure(self._rows + 1)
                row = self._rows - 1
        prev = self._owner[row]
        if prev != -1:
            self._by_request.pop(prev, None)
        self._owner[row] = request_id
        self._by_request[request_id] = row
        self._plen[row] = -1
        return row

    # -- public API ------------------------------------------------------

    def row_seeds(self, requests: Sequence[object], base_seeds: torch.Tensor) -> torch.Tensor:
        """Watermark seeds for the slate → ``(B,)`` int64 on device.

        ``base_seeds`` is the ``(B,)`` seed tensor the sampler would have
        used without the watermark (the SPMD rank-agreed seeds, or the
        private-generator draw); a row falls back to it when its context
        window has already keyed a draw (repeated-context masking).
        Everything after the host bookkeeping is device tensor ops — no
        host sync.
        """
        B = len(requests)
        self._prepare_slate(requests)
        assert self._ring is not None and self._bloom is not None
        rows_t = self._slate_rows
        assert rows_t is not None

        if self.device.type == "cuda":
            # Fused path: ONE launch for ring-gather + hash + Bloom
            # check/insert + seed select (vs ~15 tiny eager launches whose
            # overhead is measurable against a small model's decode step).
            # Bit-identical to the eager path below.
            from arbi_serve.sampler._watermark_kernel import _wm_seed_kernel

            self._ensure_key_dev()
            out = torch.empty(B, dtype=torch.int64, device=self.device)
            _wm_seed_kernel[(B,)](
                self._ring,
                self._bloom,
                rows_t,
                base_seeds,
                out,
                self._key_dev,
                H=self.h,
                W=_BLOOM_WORDS,
            )
            return out

        ctx = self._ring.index_select(0, rows_t)  # (B, H)
        h = watermark_hash_rows(self.key, ctx)  # (B,) int64 (signed bits)
        seeds = h & _S63

        # Bloom check-then-insert on the CURRENT context hash. Probes are
        # domain-separated remixes of ``h``; bit ops on int64 ignore sign.
        flat = self._bloom.view(-1)
        seen = None
        for c in (_PROBE_C1, _PROBE_C2):
            g = _splitmix64_t(h ^ _signed64(c))
            bit = g & (_BLOOM_BITS - 1)
            word_idx = rows_t * _BLOOM_WORDS + (bit >> 6)
            m = torch.bitwise_left_shift(torch.ones_like(bit), bit & 63)
            cur = flat.gather(0, word_idx)
            hit = (cur & m) != 0
            seen = hit if seen is None else (seen & hit)
            flat.scatter_(0, word_idx, cur | m)

        return torch.where(seen, base_seeds, seeds)

    def advance(self, requests: Sequence[object], sampled: torch.Tensor) -> None:
        """Shift each slate row's ring left and append this step's token.

        ``sampled`` is the sampler's merged ``(B,)`` int64 output tensor —
        a pure D2D update, valid under async output where the host has not
        yet materialized the token.
        """
        ids = tuple(int(req.request_id) for req in requests)  # type: ignore[attr-defined]
        if self._slate_ids != ids or self._slate_rows is None:
            # ``advance`` always follows a same-step ``row_seeds`` for the
            # same slate; a mismatch means a caller skipped it.
            raise RuntimeError("watermark: advance() without a matching row_seeds()")
        rows_t = self._slate_rows
        assert self._ring is not None
        if self.device.type == "cuda":
            from arbi_serve.sampler._watermark_kernel import _wm_advance_kernel

            sampled = sampled.to(dtype=torch.int64)
            assert self._pos is not None
            _wm_advance_kernel[(len(requests),)](self._ring, rows_t, sampled, self._pos, H=self.h)
            return
        cur = self._ring.index_select(0, rows_t)  # (B, H)
        new = torch.cat([cur[:, 1:], sampled.view(-1, 1)], dim=1)
        self._ring.index_copy_(0, rows_t, new)
        assert self._pos is not None
        self._pos.index_add_(0, rows_t, torch.ones(len(requests), dtype=torch.int64))

    # -- MTP (K>1 spec-decode) API ---------------------------------------

    def mtp_seed_grid(
        self,
        requests: Sequence[object],
        draft_tokens: torch.Tensor,  # (K, B) int on device
        step_seed: torch.Tensor,  # (1,) int64 on device — accepted for the shared call shape
        kp1: int,
        keep: Sequence[bool] | None = None,  # (B,) — False rows sampled UNKEYED
    ) -> torch.Tensor:
        """Per-(depth, row) watermark seeds for one MTP verify step.

        Returns ``(kp1 * B,)`` int64 (flat row ``d * B + b`` — the verify
        kernel's row layout). Depth ``d``'s context is the last ``H`` of
        (committed ring ++ ``draft_tokens[:d]``): the residual draw at the
        first rejected depth sees exactly this context because the
        accepted prefix IS the drafted prefix, and the bonus draw sees all
        drafted tokens. Bloom is CHECK-ONLY (a masked depth falls back to
        the row's unkeyed seed at that absolute position,
        :func:`unkeyed_fallback_seed`); inserts happen in
        :meth:`mtp_advance` for the depths actually consumed.

        ``keep`` is the per-row opt-out mask (``keep[b] is False`` ⇒ request
        ``b`` opted out of the watermark). An opted-out row gets the UNKEYED
        per-(depth, row) fallback at EVERY depth — the same
        fallback a Bloom-masked depth uses — so its verify draws the target
        distribution from the rank-agreed engine seed (a valid unkeyed
        sample) and, coupled with the identical draft seeds
        (:meth:`mtp_draft_seed_row` receives the same ``keep``), its
        draft↔verify accept behaviour is preserved. ``None`` keeps every
        row watermarked (the historical behaviour).
        """
        return self._mtp_seeds(requests, draft_tokens, step_seed, 0, kp1, keep)

    def _mtp_seeds(
        self,
        requests: Sequence[object],
        draft_tokens: torch.Tensor,  # (d_end - 1, B) int on device
        step_seed: torch.Tensor,  # (1,) int64 on device
        d_start: int,
        d_end: int,
        keep: Sequence[bool] | None,
    ) -> torch.Tensor:
        """Seeds for depths ``d_start..d_end-1``, flat row ``(d - d_start) * B + b``.

        The one definition of the MTP keyed-seed computation, sliced two
        ways: the verify tail asks for every depth, a drafter asks for the
        single depth it is about to draw. A depth's hash is a function of
        the context TOKENS alone — ring ++ ``draft_tokens[:d]``, never
        another depth's hash — and the Bloom probe here is check-only, so
        a sliced range is bit-identical to the same rows of a full sweep.
        """
        # Same slate bookkeeping as row_seeds (row claim / prompt-rewrite
        # rebuild / LRU touch), without the K=1 seed computation.
        self._prepare_slate(requests)
        rows_t = self._slate_rows
        assert rows_t is not None and self._ring is not None and self._bloom is not None
        B = len(requests)
        K = d_end - 1
        n_depths = d_end - d_start
        draft = draft_tokens.to(dtype=torch.int64)
        if K > 0:
            assert draft.shape == (K, B), f"draft_tokens {tuple(draft.shape)} != ({K}, {B})"
        if self.device.type == "cuda":
            return self._launch_mtp_seeds(B, draft, d_start, d_end, self._keep_device(keep, B))

        # Eager reference (CPU / parity tests) — mirrors the kernel exactly.
        # Only the context span the requested depths read is materialised:
        # absolute positions ``d_start .. d_end - 2 + H`` of (ring ++ draft),
        # which is ``H`` tokens for a single depth however deep it sits.
        ring = self._ring.index_select(0, rows_t).tolist()  # (B, H)
        d_lo = max(d_start - self.h, 0)
        draft_host = draft[d_lo:K].cpu().tolist() if d_lo < K else []
        del step_seed  # the fallback keys on the row's salt and position
        out_host = torch.empty(n_depths * B, dtype=torch.int64)
        for b in range(B):
            seq = ring[b][d_start:] + [row[b] for row in draft_host]
            for d in range(d_start, d_end):
                window = seq[d - d_start : d - d_start + self.h]
                hsh = derive_watermark_hash(self.key, window)
                seed = hsh & _S63
                seen = self._bloom_seen_host(int(rows_t[b]), hsh)
                base = self.unkeyed_seed(int(rows_t[b]), d)
                out_host[(d - d_start) * B + b] = _signed64(base if seen else seed)
        return self._apply_row_keep(out_host.to(self.device), keep, d_start, n_depths, B)

    def _keep_device(self, keep: Sequence[bool] | None, B: int) -> torch.Tensor | None:
        """``keep`` staged into the persistent device mask, or ``None`` when every row is keyed."""
        if keep is None or all(keep):
            return None
        assert self._keep_pool is not None and self._keep_host is not None
        self._keep_host[:B].copy_(torch.as_tensor([bool(k) for k in keep], dtype=torch.bool))
        self._keep_pool[:B].copy_(self._keep_host[:B], non_blocking=True)
        return self._keep_pool[:B]

    def _launch_mtp_seeds(self, B, draft, d_start, d_end, keep_t):
        """One seed-kernel launch for depths ``d_start..d_end-1`` of the PREPARED slate."""
        from arbi_serve.sampler._watermark_kernel import _wm_mtp_seed_kernel

        self._ensure_key_dev()
        K, n_depths = d_end - 1, d_end - d_start
        out = torch.empty(n_depths * B, dtype=torch.int64, device=self.device)
        _wm_mtp_seed_kernel[(B,)](
            self._ring, self._bloom, self._slate_rows,
            draft if K > 0 else out,  # dummy ptr at K==0 (never read)
            self._pos, self._salt, out, self._key_dev,
            keep_t if keep_t is not None else out,  # dummy ptr without a mask (never read)
            B, draft.stride(0) if K > 0 else 0, draft.stride(1) if K > 0 else 0,
            H=self.h, W=_BLOOM_WORDS, D_START=d_start, D_COUNT=n_depths, HAS_KEEP=keep_t is not None,
        )  # fmt: skip
        return out

    def mtp_draft_seed_walk(self, requests: Sequence[object], keep: Sequence[bool] | None = None):
        """``seeds(draft_prefix, step)`` for a drafter walk: slate and mask prepared once, one launch per step."""
        if self.device.type != "cuda":
            return lambda prefix, step: self.mtp_draft_seed_row(requests, prefix, None, step, keep)
        self._prepare_slate(requests)
        B, keep_t = len(requests), self._keep_device(keep, len(requests))
        return lambda prefix, step: self._launch_mtp_seeds(
            B, prefix.to(dtype=torch.int64), step, step + 1, keep_t
        )

    def masked_depths_host(
        self, requests: Sequence[object], draft_tokens: torch.Tensor, kp1: int
    ) -> list[list[bool]]:
        """DIAGNOSTIC: per row, whether each depth ``0..kp1-1`` is Bloom-masked.

        Host-side re-derivation of the seed kernel's Bloom probe over the same
        (ring ++ drafts) windows; a per-probe device read, so never on a perf
        path. Rows must already be prepared for the slate.
        """
        rows_t = self._slate_rows
        assert rows_t is not None and self._ring is not None
        B = len(requests)
        ring = self._ring.index_select(0, rows_t).tolist()
        draft_host = draft_tokens.cpu().tolist() if kp1 > 1 else []
        out: list[list[bool]] = []
        for b in range(B):
            seq = ring[b] + [row[b] for row in draft_host]
            flags = []
            for d in range(kp1):
                hsh = derive_watermark_hash(self.key, seq[d : d + self.h])
                flags.append(bool(self._bloom_seen_host(int(rows_t[b]), hsh)))
            out.append(flags)
        return out

    def unkeyed_seed(self, row: int, depth: int) -> int:
        """Host reference of the unkeyed fallback for cache ``row`` at ``depth``."""
        assert self._pos is not None and self._salt is not None
        salt = int(self._salt[row].item()) & _U64
        position = (int(self._pos[row].item()) + int(depth)) & _U64
        return unkeyed_fallback_seed(salt, position)

    def _apply_row_keep(
        self,
        out: torch.Tensor,  # (n_depths * B,) int64 keyed seeds
        keep: Sequence[bool] | None,
        d_start: int,
        n_depths: int,
        B: int,
    ) -> torch.Tensor:
        """Overwrite opted-out rows' seeds with the UNKEYED per-(depth, row)
        fallback (:func:`unkeyed_fallback_seed`) — the SAME fallback a
        Bloom-masked depth uses, so an opted-out row is unkeyed at every
        depth. The fallback keys on the ABSOLUTE depth ``d_start + i``, so a
        sliced range reproduces the full sweep's rows — the seeds differ at
        every depth by construction and are NOT hoistable across a walk.
        ``keep is None`` (or all True) is the no-op keyed path — it allocates
        and launches nothing.

        The mask lands in the persistent ``_keep_pool`` rather than a fresh
        upload per call: a pageable host-list H2D cannot be captured at all,
        and a re-uploaded one would move under a graph that had recorded it."""
        if keep is None or all(keep):
            return out
        device = self.device
        assert self._keep_pool is not None and self._keep_host is not None
        host = self._keep_host[:B]
        host.copy_(torch.as_tensor([bool(k) for k in keep], dtype=torch.bool))
        keep_t = self._keep_pool[:B]  # (B,); broadcast over depth below
        keep_t.copy_(host, non_blocking=True)
        assert self._pos is not None and self._salt is not None and self._slate_rows is not None
        rows_t = self._slate_rows
        pos_t = self._pos.index_select(0, rows_t).view(1, B)
        salt_t = self._salt.index_select(0, rows_t).view(1, B)
        depths = torch.arange(d_start, d_start + n_depths, dtype=torch.int64, device=device)
        inner = _splitmix64_t(pos_t + depths.view(n_depths, 1) + _signed64(_BASE_REMIX))
        fallback = (_splitmix64_t(salt_t ^ inner) & _S63).reshape(-1)
        # (1, B) against (n_depths, B): flat index i*B+b selects on keep[b],
        # the same choice ``keep_t.repeat(n_depths)`` made, without the repeat.
        return torch.where(
            keep_t.view(1, B), out.view(n_depths, B), fallback.view(n_depths, B)
        ).view(-1)

    def mtp_draft_seed_row(
        self,
        requests: Sequence[object],
        draft_prefix: torch.Tensor,  # (step, B) int on device — drafts committed so far
        step_seed: torch.Tensor,  # (1,) int64 on device — accepted for the shared call shape
        step: int,
        keep: Sequence[bool] | None = None,  # (B,) — False rows drafted UNKEYED
    ) -> torch.Tensor:
        """Per-row keyed seeds for draft slot ``step`` — depth ``step`` of
        :meth:`mtp_seed_grid` (context = last ``H`` of ring ++
        ``draft_prefix``). A stochastic drafter drawing its slot-``step``
        token with these seeds (zero-lane Philox layout) shares its Gumbel
        noise with the verify pass's keyed choice at the same depth, so the
        draft argmax and the target's keyed argmax agree whenever their
        distributions do — the accept-restoring coupling for
        ``ARBI_TRUE_STOCHASTIC_DRAFT`` under the watermark.

        ``keep`` (same per-row opt-out mask :meth:`mtp_seed_grid` takes) makes
        an opted-out row draw from the UNKEYED per-position fallback, matching
        the seed its verify pass uses so accept behaviour is preserved.

        Returns ``(B,)`` int64.
        """
        return self._mtp_seeds(requests, draft_prefix, step_seed, step, step + 1, keep)

    def mtp_advance(
        self,
        requests: Sequence[object],
        committed: torch.Tensor,  # (KP1, B) int64 — drafted prefix then recovery/bonus
        n_accepted: torch.Tensor,  # (B,) int — accepted drafted count per row
        *,
        insert_blooms: bool = True,
    ) -> None:
        """Commit one MTP verify step: Bloom-insert the consumed contexts
        (depths ``0..n``) and advance each row's ring by its ``n+1``
        committed tokens. Pure D2D on CUDA — host-sync-free under async
        output. ``insert_blooms=False`` is the ring-only variant for
        slates that committed WITHOUT keyed draws (greedy-routed steps):
        the ring must track the context, but no keyed context was
        consumed, so nothing is marked seen."""
        ids = tuple(int(req.request_id) for req in requests)  # type: ignore[attr-defined]
        if self._slate_ids != ids or self._slate_rows is None:
            # A ring-only advance may arrive without a same-step seed call
            # (greedy-routed slate); prepare the slate bookkeeping here.
            self._prepare_slate(requests)
        rows_t = self._slate_rows
        assert rows_t is not None
        assert self._ring is not None and self._bloom is not None
        kp1, B = committed.shape
        committed = committed.to(dtype=torch.int64)
        nacc = n_accepted.to(dtype=torch.int64)

        if self.device.type == "cuda":
            from arbi_serve.sampler._watermark_kernel import _wm_mtp_advance_kernel

            if self._key_dev is None or self._key_dev.device != self.device:
                self._key_dev = torch.tensor(
                    [_signed64(self.key)], dtype=torch.int64, device=self.device
                )
            assert self._pos is not None
            _wm_mtp_advance_kernel[(B,)](
                self._ring,
                self._bloom,
                rows_t,
                committed,
                nacc,
                self._pos,
                self._key_dev,
                B,
                committed.stride(0),
                committed.stride(1),
                H=self.h,
                W=_BLOOM_WORDS,
                KP1=kp1,
                INSERT_BLOOMS=insert_blooms,
            )
            return

        ring = self._ring
        committed_host = committed.cpu()
        nacc_host = nacc.cpu()
        for b in range(B):
            row = int(rows_t[b])
            n = int(nacc_host[b])
            seq = [int(t) for t in ring[row]] + [int(committed_host[k, b]) for k in range(n + 1)]
            if insert_blooms:
                for d in range(n + 1):
                    hsh = derive_watermark_hash(self.key, seq[d : d + self.h])
                    self._bloom_insert_host(row, hsh)
            tail = seq[-self.h :]
            ring[row] = torch.tensor(tail, dtype=torch.int64)
        assert self._pos is not None
        self._pos.index_add_(0, rows_t, (nacc + 1).to(self._pos.device))

    def _prepare_slate(self, requests: Sequence[object]) -> None:
        """Row claim / prompt-rewrite rebuild / LRU touch for a slate —
        the bookkeeping prefix of :meth:`row_seeds`, shared with the MTP
        path (which computes its seeds in its own kernel).

        The slate's row indices are WRITTEN INTO the persistent pool rather
        than uploaded as a fresh tensor: ``_slate_rows`` is always a prefix
        view at the pool's base address, so a graph that recorded it keeps
        reading the current slate. The ``_slate_ids`` comparison only skips the
        upload when the slate has not changed; it does not decide whether the
        tensor exists.
        """
        self._tick += 1
        tick = self._tick
        B = len(requests)
        if self._rows < B:
            self._ensure(B)
        rows: list[int] = []
        builds: list[tuple[int, list[int]]] = []
        for req in requests:
            rid = int(req.request_id)  # type: ignore[attr-defined]
            plen = len(req.prompt_token_ids)  # type: ignore[attr-defined]
            row = self._by_request.get(rid, -1)
            if row < 0:
                row = self._claim_row(rid)
            if self._plen[row] != plen:
                full = list(req.prompt_token_ids) + list(req.output_token_ids)  # type: ignore[attr-defined]
                tail = full[-self.h :]
                if len(tail) < self.h:
                    tail = [_CTX_SENTINEL] * (self.h - len(tail)) + tail
                builds.append((row, tail, len(full), _signed64(row_salt(self.key, rid))))
                self._plen[row] = plen
            self._touch[row] = tick
            rows.append(row)
        assert self._ring is not None and self._bloom is not None
        if builds:
            assert self._pos is not None and self._salt is not None
            idx = torch.as_tensor([b[0] for b in builds], dtype=torch.int64)
            vals = torch.as_tensor([b[1] for b in builds], dtype=torch.int64)
            pos = torch.as_tensor([b[2] for b in builds], dtype=torch.int64)
            salt = torch.as_tensor([b[3] for b in builds], dtype=torch.int64)
            idx = idx.to(self.device, non_blocking=True)
            self._ring.index_copy_(0, idx, vals.to(self.device, non_blocking=True))
            self._bloom.index_fill_(0, idx, 0)
            self._pos.index_copy_(0, idx, pos.to(self.device, non_blocking=True))
            self._salt.index_copy_(0, idx, salt.to(self.device, non_blocking=True))
        ids = tuple(int(req.request_id) for req in requests)  # type: ignore[attr-defined]
        if self._slate_ids != ids or self._slate_rows is None:
            assert self._slate_rows_pool is not None and self._slate_rows_host is not None
            host = self._slate_rows_host[:B]
            host.copy_(torch.as_tensor(rows, dtype=torch.int64))
            self._slate_rows_pool[:B].copy_(host, non_blocking=True)
            self._slate_ids = ids
            self._slate_rows = self._slate_rows_pool[:B]

    def _bloom_seen_host(self, row: int, hsh: int) -> bool:
        """Check-only host Bloom probe (eager/CPU reference path)."""
        assert self._bloom is not None
        seen = True
        for c in (_PROBE_C1, _PROBE_C2):
            g = _splitmix64((hsh ^ c) & _U64)
            bit = g & (_BLOOM_BITS - 1)
            word = int(self._bloom[row, bit >> 6].item()) & _U64
            seen = seen and bool(word & (1 << (bit & 63)))
        return seen

    def _bloom_insert_host(self, row: int, hsh: int) -> None:
        assert self._bloom is not None
        for c in (_PROBE_C1, _PROBE_C2):
            g = _splitmix64((hsh ^ c) & _U64)
            bit = g & (_BLOOM_BITS - 1)
            word = int(self._bloom[row, bit >> 6].item()) & _U64
            self._bloom[row, bit >> 6] = _signed64(word | (1 << (bit & 63)))

    def drop(self, request_id: int) -> None:
        """Release the row held by ``request_id`` (no-op when absent)."""
        row = self._by_request.pop(int(request_id), -1)
        if row >= 0:
            self._owner[row] = -1
            self._plen[row] = -1
            self._touch[row] = -1
            self._slate_ids = None
            self._slate_rows = None

    def reset(self) -> None:
        """Return every row to the free pool and clear its context.

        The device pools are re-filled in place, not dropped: their addresses
        outlive the reset, so a graph recorded against them stays valid. The
        reservation is released — a rebuild may serve a different
        ``max_batch``, and re-reserving is how the next capture states it.
        """
        if self._ring is not None:
            assert self._bloom is not None
            with torch.inference_mode(False):
                self._ring.fill_(_CTX_SENTINEL)
                self._bloom.zero_()
        self._rows = 0
        self._reserved = 0
        self._owner.clear()
        self._plen.clear()
        self._touch.clear()
        self._by_request.clear()
        self._slate_ids = None
        self._slate_rows = None


class WatermarkStore:
    """One member's watermark caches by device, and the pool hook they allocate through."""

    __slots__ = ("allocate", "caches")

    def __init__(self) -> None:
        self.allocate: PoolAllocate | None = None
        self.caches: dict[str, WatermarkContextCache] = {}

    def install_pool(self, allocate: PoolAllocate | None) -> None:
        """Route this store's context pools through ``allocate`` (``None`` uninstalls); drops its caches."""
        self.allocate = allocate
        self.reset()

    def reset(self) -> None:
        """Drop every cache (key flip / test isolation); the next claim rebuilds through the hook."""
        for cache in self.caches.values():
            cache.reset()
        self.caches.clear()


def get_watermark_cache(
    device: torch.device, store: WatermarkStore
) -> WatermarkContextCache | None:
    """``store``'s cache for ``device``, or ``None`` when no key is configured."""
    from arbi_serve.runtime_flags import runtime_flags

    # A configured key IS the enable: clearing it (live, through
    # /v1/admin/config_override) is how a standing server stops marking.
    # Every consumer (K=1 sampler, MTP verify + draft) goes through this
    # function, so this one check covers them all.
    raw, _source = effective_watermark_key_from_flags(runtime_flags())
    if not watermark_key_configured(raw):
        return None
    dev_key = str(device)
    cache = store.caches.get(dev_key)
    if cache is None:
        cache = WatermarkContextCache(device, parse_watermark_key(raw), WATERMARK_H, store.allocate)
        store.caches[dev_key] = cache
    return cache


# ── Detection (host-side, model-free) ─────────────────────────────────


def philox_uniform_host(seed: int, index: int) -> float:
    """The sampling kernel's Philox4x32-10 uniform at ``(seed, index)``.

    Bit-for-bit mirror of ``_gumbel_argmax_kernel._philox_uniform``:
    counter lane 0 = ``index`` (uint32 wrap), lanes 1-3 zero, key = the
    64-bit seed split lo/hi, ten rounds, lane-0 mapped to (0, 1) as
    ``((x >> 9) + 0.5) * 2^-23`` (exact in fp32 and fp64 alike).
    """
    mask32 = 0xFFFFFFFF
    c0, c1, c2, c3 = index & mask32, 0, 0, 0
    k0 = seed & mask32
    k1 = (seed >> 32) & mask32
    for _ in range(10):
        lo0 = (0xD2511F53 * c0) & mask32
        hi0 = (0xD2511F53 * c0) >> 32
        lo1 = (0xCD9E8D57 * c2) & mask32
        hi1 = (0xCD9E8D57 * c2) >> 32
        c0, c1, c2, c3 = (hi1 ^ c1 ^ k0) & mask32, lo1, (hi0 ^ c3 ^ k1) & mask32, lo0
        k0 = (k0 + 0x9E3779B9) & mask32
        k1 = (k1 + 0xBB67AE85) & mask32
    return ((c0 >> 9) + 0.5) * 1.1920928955078125e-07


def detect_tokens(
    token_ids: Sequence[int],
    key: int,
    *,
    h: int = 4,
    prompt_len: int = 0,
    collect_per_token: bool = False,
) -> dict[str, float]:
    """Score a token sequence for the ``key`` watermark. Model-free.

    ``token_ids`` is the full available sequence (prompt + completion when
    the prompt is known — pass ``prompt_len`` so prompt tokens provide
    context but are not themselves scored). Positions whose ``h``-window
    context repeats an earlier scored context are skipped, mirroring the
    sampler's repeated-context masking (the sampler's Bloom false
    positives are not mirrored — those tokens score as null noise and
    only dilute the statistic).

    Returns ``n`` (scored tokens), ``mean_u`` (null: 0.5), ``stat``
    (``Σ -log(1-u)``; null: ``Gamma(n, 1)``), ``p_value`` (survival
    probability of the null — small ⇒ watermarked), and ``z`` (normal
    approximation of the same test).
    """
    ids = [int(t) for t in token_ids]
    n = 0
    stat = 0.0
    mean_acc = 0.0
    seen: set[tuple[int, ...]] = set()
    per: list[dict[str, float | int | bool]] = [] if collect_per_token else []
    start = max(int(prompt_len), 1 if len(ids) > 0 else 0)
    for t in range(start, len(ids)):
        window = ids[max(0, t - h) : t]
        if len(window) < h:
            window = [_CTX_SENTINEL] * (h - len(window)) + window
        wkey = tuple(window)
        if wkey in seen:
            if collect_per_token:
                per.append({"pos": t, "u": None, "masked": True})
            continue
        seen.add(wkey)
        seed = derive_watermark_seed(key, window)
        u = philox_uniform_host(seed, ids[t])
        n += 1
        mean_acc += u
        stat += -math.log1p(-u)
        if collect_per_token:
            per.append({"pos": t, "u": u, "masked": False})
    if n == 0:
        out0 = {"n": 0, "mean_u": 0.5, "stat": 0.0, "p_value": 1.0, "z": 0.0}
        if collect_per_token:
            out0["per"] = per
        return out0
    # Null: stat ~ Gamma(n, 1). Regularized upper incomplete gamma is the
    # exact survival function; torch provides it without a scipy dep.
    p = float(torch.special.gammaincc(torch.tensor(float(n)), torch.tensor(stat)).item())
    z = (stat - n) / math.sqrt(n)
    out = {"n": n, "mean_u": mean_acc / n, "stat": stat, "p_value": p, "z": z}
    if collect_per_token:
        out["per"] = per
    return out
# ---- watermark_request.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Which requests carry the keyed watermark, and what each response reports."""

from __future__ import annotations

from collections.abc import Sequence


def watermark_default_on(flags: object) -> bool:
    """Whether a request that leaves ``watermark`` unset is keyed (``ARBI_WATERMARK_DEFAULT``)."""
    return bool(getattr(flags, "watermark_default", False))


def row_keyed(watermark: bool | None, default_on: bool) -> bool:
    """A row is keyed when it asks (``True``), or leaves it unset under a default-on server."""
    return watermark is True or (watermark is None and default_on)


def watermark_keep_mask(requests: Sequence[object]) -> list[bool]:
    """Per-row keyed mask; ``False`` rows draw unkeyed. Valid only when a key is loaded."""
    from arbi_serve.runtime_flags import runtime_flags

    default_on = watermark_default_on(runtime_flags())
    return [
        row_keyed(getattr(getattr(req, "sampling", None), "watermark", None), default_on)
        for req in requests
    ]


def step_watermark_cache(device, requests: Sequence[object], store):
    """``store``'s cache when a key is loaded AND some row of ``requests`` is keyed, else ``None``."""
    from arbi_serve.sampler.watermark import get_watermark_cache

    cache = get_watermark_cache(device, store)
    if cache is None or not any(watermark_keep_mask(requests)):
        return None
    return cache


def watermark_server_state(flags: object) -> dict:
    """``{"key_loaded", "default"[, "reason"]}`` for status surfaces; never the key."""
    from arbi_serve.sampler.watermark import watermark_state_from_flags

    loaded, reason = watermark_state_from_flags(flags)
    state: dict = {"key_loaded": loaded, "default": "on" if watermark_default_on(flags) else "off"}
    if not loaded:
        state["reason"] = reason
    return state


def request_watermark_state(sampling: object, flags: object) -> tuple[bool, str | None]:
    """Whether a request's output is watermarked, and why not when it is not."""
    from arbi_serve.sampler.watermark import watermark_state_from_flags

    loaded, reason = watermark_state_from_flags(flags)
    if not loaded:
        return False, reason
    wm = getattr(sampling, "watermark", None)
    if wm is False:
        return False, "the request opted out (watermark: false)"
    if not row_keyed(wm, watermark_default_on(flags)):
        return False, "watermarking is off by default on this server; send watermark: true"
    if float(getattr(sampling, "temperature", 1.0)) <= 0.0:
        return False, "greedy decoding (temperature 0) has no random draw to key"
    return True, None


def refuse_unhonoured_watermark(sampling: object, flags: object) -> None:
    """Raise ``ValueError`` when ``watermark: true`` was asked for and cannot be applied."""
    if getattr(sampling, "watermark", None) is not True:
        return
    marked, reason = request_watermark_state(sampling, flags)
    if not marked:
        raise ValueError(
            f"watermark: true was requested but this output cannot be watermarked: {reason}. "
            "The server marks output only when ARBI_WATERMARK_KEY is loaded; omit the field to "
            "accept the server default (usage.watermark reports what was applied)."
        )
# ---- watermark_warmup.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Boot-time pre-compile of the watermark ring/Bloom STATE kernels.

Split out of :mod:`arbi_serve.sampler.kernel_warmup` (file-size ceiling), which
re-exports both names; the keyed watermark DRAWS stay warmed there, beside the
verify sampler they ride.
"""

from __future__ import annotations

import torch


def _wm_state_slates(k_plus_1: int, max_batch: int) -> list[tuple[int, int]]:
    """One ``(K+1, B)`` slate per distinct watermark-state specialization.

    A different ladder from :func:`~arbi_serve.sampler.kernel_warmup._verify_slates`: the state kernels are
    keyed on ``KP1`` and on the integer class of the slate width ``B``
    (which is also the committed/draft tensor's leading stride), not on
    the residual draw's row-count and split axes.
    """
    from arbi_serve.sampler.kernel_warmup import _spec_class

    seen: set[tuple[int, str]] = set()
    slates: list[tuple[int, int]] = []
    for kp1 in range(2, int(k_plus_1) + 1):
        for b in range(1, max(1, int(max_batch)) + 1):
            key = (kp1, _spec_class(b))
            if key not in seen:
                seen.add(key)
                slates.append((kp1, b))
    return slates


def warm_watermark_state_kernels(
    device: torch.device, *, h: int, k_plus_1: int, max_batch: int
) -> int:
    """Pre-compile the watermark ring/Bloom state kernels.

    The keyed DRAWS are warmed alongside the verify sampler; the state
    kernels that COMMIT them are reached by no sampler launch, so without
    this they compile under the first live request.

    ``_wm_mtp_advance_kernel`` specializes on ``KP1``, so a boot whose
    served draft length changes needs its own warm; it additionally
    specializes on ``INSERT_BLOOMS``, the ring-only variant a
    greedy-routed slate takes. ``_wm_mtp_seed_kernel`` specializes on its
    depth range: the verify tail launches ``(0, KP1)``, and a stochastic
    drafter launches ``(s, 1)`` once per slot ``s``. Every one of those is
    servable, so every one is warmed. Warms against private scratch ring
    and Bloom buffers, never the live cache.
    """
    if not torch.cuda.is_available():
        return 0
    from arbi_serve.sampler._watermark_kernel import (
        _wm_advance_kernel,
        _wm_mtp_advance_kernel,
        _wm_mtp_seed_kernel,
        _wm_seed_kernel,
    )
    from arbi_serve.sampler.watermark import _BLOOM_WORDS

    hh, w = int(h), int(_BLOOM_WORDS)
    mb = max(1, int(max_batch))
    ring = torch.zeros(mb, hh, dtype=torch.int64, device=device)
    bloom = torch.zeros(mb, w, dtype=torch.int64, device=device)
    key = torch.zeros(1, dtype=torch.int64, device=device)
    rows = torch.zeros(mb, dtype=torch.int64, device=device)
    base = torch.zeros(mb, dtype=torch.int64, device=device)
    out = torch.zeros(mb, dtype=torch.int64, device=device)
    n = 0

    # Plain decode: one specialization each, on ``H`` (and ``W``) alone.
    _wm_seed_kernel[(mb,)](ring, bloom, rows, base, out, key, H=hh, W=w)
    # Four tensors, because the serving call passes four: RING, ROWS,
    # SAMPLED, POS. The three-argument form here never compiled — it raised
    # ``TypeError: dynamic_func() missing 1 required positional argument:
    # 'POS'`` — and nothing noticed, because this whole block was unreachable
    # on every shipped recipe until the key stopped being the feature gate.
    pos = torch.zeros(mb, dtype=torch.int64, device=device)
    # Per-row committed length and unkeyed salt: both MTP kernels take them
    # and neither three-argument call here ever compiled, so the shapes come
    # from the kernel signatures rather than from what this block used to pass.
    salt = torch.zeros(mb, dtype=torch.int64, device=device)
    _wm_advance_kernel[(mb,)](ring, rows, base, pos, H=hh)
    n += 2

    for kp1, b in _wm_state_slates(k_plus_1, mb):
        rows_b = rows[:b]
        draft = torch.zeros(kp1 - 1, b, dtype=torch.int64, device=device)
        # The drafter walk reads its prefix as ``toks[:, :j].t()``: the same
        # shape transposed in memory, a distinct stride specialization.
        draft_t = torch.zeros(b, kp1 - 1, dtype=torch.int64, device=device).t()
        seeds = torch.zeros(kp1 * b, dtype=torch.int64, device=device)
        keep = torch.ones(b, dtype=torch.bool, device=device)
        # (0, kp1): the verify tail's full grid. (s, 1): the drafter's slot-``s`` row.
        launches = [(0, kp1, draft)] + [(s, 1, d) for s in range(kp1 - 1) for d in (draft, draft_t)]
        for d_start, d_count, dr in launches:
            for has_keep in (False, True):
                _wm_mtp_seed_kernel[(b,)](
                    ring, bloom, rows_b, dr, pos, salt, seeds, key, keep, b,
                    dr.stride(0), dr.stride(1),
                    H=hh, W=w, D_START=d_start, D_COUNT=d_count, HAS_KEEP=has_keep,
                )  # fmt: skip
                n += 1
        committed = torch.zeros(kp1, b, dtype=torch.int64, device=device)
        nacc = torch.zeros(b, dtype=torch.int64, device=device)
        for insert_blooms in (True, False):
            _wm_mtp_advance_kernel[(b,)](
                ring,
                bloom,
                rows_b,
                committed,
                nacc,
                pos,
                key,
                b,
                committed.stride(0),
                committed.stride(1),
                H=hh,
                W=w,
                KP1=kp1,
                INSERT_BLOOMS=insert_blooms,
            )
        n += 2
    ring.zero_()
    bloom.zero_()
    return n
# ---- xgrammar_bounded_table.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Device-resident state tables for BOUNDED grammars — the capture-safe
target :class:`~arbi_serve.sampler.xgrammar_processor.DraftGrammarWalk` is
the fallback for.

Every xgrammar call (``fill_next_token_bitmask``, ``accept_token``, ``fork``)
is CPU automaton work, so masking a captured graph's per-step draft
proposal by calling into it needs a host sync every step — real, even in
the eager path (see ``xgrammar_processor.py``'s "Grammar-aware DRAFTING"
section). A captured replay cannot make that call at all: no CPU code runs
during replay.

For a BOUNDED grammar (a flat enum, a boolean, a tool-name alternation —
finite reachable states, no unbounded recursion), the state -> legal-token
bitmask and (state, token) -> next-state relations can be walked ONCE, at
grammar-compile time (not per request, not per step), and handed to the
caller as plain tensors a captured graph can `index_select`/`gather` with
zero CPU involvement. Building that table is CPU work like everything else
here — the win is WHEN it's paid (once per distinct grammar) and WHERE
(compile time, off the per-step hot path), not that it avoids xgrammar's
CPU-only API.

Built entirely from xgrammar's public, documented, stable surface —
``GrammarMatcher.fork()``, ``.accept_token()``, ``.fill_next_token_bitmask()``,
``.is_terminated()`` — deliberately NOT xgrammar's internal serialization
format (``CompiledGrammar.serialize_json()`` does expose an internal
``adaptive_token_mask_cache`` with comparable information, but it is
undocumented and version-tagged; reverse-engineering it risks breaking
silently across xgrammar releases).

:func:`upload_bounded_grammar_table` turns one :class:`BoundedGrammarTable`
into the device tensors a captured step can read with zero CPU
involvement (:func:`gather_bitmasks` for the mask, :func:`gather_next_states`
for the next state). Still NOT
DONE HERE: splicing a captured graph's replay to actually read them, or the
per-row state-index buffer a replay would gather with — those need a live
GPU boot to verify and belong beside the capture machinery they extend.
"""

from __future__ import annotations

from dataclasses import dataclass, field

import torch
import xgrammar as xg

#: Reject a grammar whose BFS exceeds this many states — the boundedness
#: test. A flat enum/bool/tool-name alternation reaches its full state set
#: in the tens; anything open-ended (recursive JSON, free-text spans) blows
#: this immediately. Deliberately NOT a minimized-DFA state count (no state
#: merging is attempted — see the module docstring's TREE, not DFA, note
#: below): a real minimal automaton would need fewer states for the same
#: grammar, so this cap is conservative (some grammars that COULD be
#: bounded with minimization fall back to the live-chain path instead) but
#: never unsafe.
DEFAULT_MAX_STATES = 512

#: Reject a grammar where any single reachable state has more than this
#: many legal next tokens — the per-state branching test. Without this, a
#: state with a huge legal set (e.g. "anything but the closing quote" in an
#: open JSON string) would fork + accept once per legal token before the
#: total-state cap ever has a chance to bite, which is slow AND pointless
#: (that state was never going to be part of a bounded grammar).
DEFAULT_MAX_BRANCHING = 64


@dataclass
class BoundedGrammarTable:
    """A fully-enumerated state table for one compiled, bounded grammar.

    Built as a TREE by BFS from the initial state, not a minimized DFA: two
    reachable states with identical future behavior are never merged (doing
    so needs a state-equality test xgrammar's public API does not expose
    cheaply). This costs some avoidable state count — bounded by
    ``DEFAULT_MAX_STATES`` regardless, so it costs *coverage* (some
    grammars that a minimized DFA would keep bounded exceed the cap here
    and fall back to the live-chain path instead), never correctness.

    ``bitmasks[s]`` is state ``s``'s legal-token bitmask, packed
    ``(ceil(V/32),)`` int32 — CPU tensors here; uploading to device is the
    caller's job, once per table.

    ``transitions[(s, token)] = next_s`` for every LEGAL ``token`` at state
    ``s`` (illegal tokens have no entry — they are masked out by
    ``bitmasks[s]`` before a lookup could ever ask for them).

    ``terminal_states`` are states reached by accepting a stop token — the
    chain is over; nothing masks further (mirrors
    ``DraftGrammarWalk``/``draft_step_bitmask``'s terminated-walk
    all-legal degrade, at the table level: a caller should stop advancing,
    not look up a transition that doesn't exist).
    """

    bitmasks: list[torch.Tensor] = field(default_factory=list)
    transitions: dict[tuple[int, int], int] = field(default_factory=dict)
    terminal_states: set[int] = field(default_factory=set)
    vocab_size: int = 0

    @property
    def num_states(self) -> int:
        return len(self.bitmasks)


def _legal_token_ids(bitmask: torch.Tensor, vocab_size: int) -> list[int]:
    """Unpack a packed ``(words,)`` int32 bitmask into legal token ids.

    Vectorized (no Python loop over ``vocab_size``): unpack all 32 bits of
    every word at once via a shift/mask against a bit-index tensor, then
    read off the nonzero flat positions and clip the padding tail (the last
    word may cover indices >= vocab_size when V is not a multiple of 32).
    """
    words = bitmask.to(torch.int64)  # widen: bit 31 would be negative in int32
    bits = torch.arange(32, dtype=torch.int64)
    set_bits = (words.unsqueeze(-1) >> bits) & 1  # (num_words, 32)
    flat = set_bits.reshape(-1)[:vocab_size]
    return flat.nonzero(as_tuple=True)[0].tolist()


def build_bounded_grammar_table(
    compiled: xg.CompiledGrammar,
    vocab_size: int,
    *,
    max_states: int = DEFAULT_MAX_STATES,
    max_branching: int = DEFAULT_MAX_BRANCHING,
) -> BoundedGrammarTable | None:
    """BFS the grammar's reachable states from a fresh matcher; ``None`` if
    it isn't bounded within ``max_states`` / ``max_branching``.

    Pure CPU work over xgrammar's public API — no device tensor, no model,
    no request. Callers cache the result the same way
    :class:`~arbi_serve.sampler.xgrammar_processor.XGrammarLogitsProcessor`
    caches a ``CompiledGrammar``: once per distinct grammar, not per
    request. ``None`` is the expected, common outcome for anything beyond a
    flat enum/bool/tool-name alternation — callers fall back to
    :class:`~arbi_serve.sampler.xgrammar_processor.DraftGrammarWalk`, not an
    error.
    """
    words = (vocab_size + 31) // 32
    root = xg.GrammarMatcher(compiled)
    table = BoundedGrammarTable(vocab_size=vocab_size)
    # state id -> live matcher instance for states not yet expanded. State 0
    # is always the root (pre-any-token) state.
    frontier: list[tuple[int, xg.GrammarMatcher]] = [(0, root)]
    table.bitmasks.append(torch.empty((words,), dtype=torch.int32))  # placeholder, filled below

    while frontier:
        next_frontier: list[tuple[int, xg.GrammarMatcher]] = []
        for state_id, matcher in frontier:
            if matcher.is_terminated():
                table.terminal_states.add(state_id)
                # A terminal state has no further legal-token bitmask to
                # fill or transitions to expand — leave its bitmask row as
                # the all-legal placeholder (matches DraftGrammarWalk's own
                # terminated-walk convention: nothing further is
                # constrained).
                table.bitmasks[state_id] = torch.full((words,), -1, dtype=torch.int32)
                continue
            bm = torch.empty((words,), dtype=torch.int32)
            matcher.fill_next_token_bitmask(bm.unsqueeze(0), 0)
            table.bitmasks[state_id] = bm
            legal = _legal_token_ids(bm, vocab_size)
            if len(legal) > max_branching:
                return None
            for token in legal:
                if table.num_states >= max_states:
                    return None
                child = matcher.fork()
                if not child.accept_token(token):
                    # Should not happen — `token` came from this state's OWN
                    # bitmask — but a matcher that refuses its own legal
                    # token is not one this table can trust; bail rather
                    # than record a transition to a state that may not
                    # reflect reality.
                    return None
                child_id = table.num_states
                table.bitmasks.append(torch.empty((words,), dtype=torch.int32))  # placeholder
                table.transitions[(state_id, token)] = child_id
                next_frontier.append((child_id, child))
        frontier = next_frontier

    return table


#: Sentinel written into ``next_state_dev`` for a ``(state, token)`` pair
#: with no transition: an illegal token (never read — the bitmask gather
#: masks it out first) or a legal token accepted FROM a terminal state
#: (the table stops expanding at ``is_terminated()``, so there is no child
#: to point to). A caller that gathers this back is the table's own
#: contract for "stop trusting this row's state index" — degrade to
#: unconstrained for the rest of the chain, the same way a terminated
#: :class:`~arbi_serve.sampler.xgrammar_draft_walk.DraftGrammarWalk`
#: degrades (its own module's terminated-walk convention).
NO_TRANSITION = -1


#: Width of a device table's per-state transition row. A bounded table never
#: holds a state with more legal tokens than ``DEFAULT_MAX_BRANCHING`` (the
#: build refuses it), and every legal token of a non-terminal state has a
#: transition, so this many ``(token, next_state)`` slots hold every state's
#: whole transition set. Fixed rather than per-table so a captured graph's
#: persistent rows fit any table a later request brings.
TRANSITION_WIDTH = DEFAULT_MAX_BRANCHING


@dataclass
class DeviceBoundedGrammarTable:
    """The device-resident mirror of one :class:`BoundedGrammarTable`.

    Uploaded ONCE per compiled grammar (like the CPU table it mirrors) —
    never per request, never per step.

    ``next_token_dev[s]`` / ``next_state_dev[s]`` are state ``s``'s
    transitions as ``TRANSITION_WIDTH`` parallel slots, padded with
    :data:`NO_TRANSITION`. That is the whole relation, because a bounded
    state has at most ``DEFAULT_MAX_BRANCHING`` legal tokens and each has a
    transition — so the legal-token mask is derivable from the same rows
    (:func:`gather_bitmasks`) and the next state is a compare against them
    (:func:`gather_next_states`), both pure device ops a captured step can
    run. A dense ``(num_states, vocab_size)`` next-state table would cost
    ``vocab_size / TRANSITION_WIDTH`` times more for the same information,
    and a captured chain holds one per ``(B, K)`` bucket.

    ``bitmasks_dev`` is the eager tier's per-state mask
    (:func:`~arbi_serve.spec_decode.mtp_grammar_draft.grammar_step_bitmask`),
    sized by this table's own state count.
    """

    bitmasks_dev: torch.Tensor  # (num_states, ceil(V/32)) int32
    next_token_dev: torch.Tensor  # (num_states, TRANSITION_WIDTH) int32, NO_TRANSITION pad
    next_state_dev: torch.Tensor  # (num_states, TRANSITION_WIDTH) int32, NO_TRANSITION pad
    num_states: int
    vocab_size: int


def device_bounded_table_bytes(num_states: int, vocab_size: int) -> int:
    """Bytes :func:`upload_bounded_grammar_table` reserves for one table."""
    words = (vocab_size + 31) // 32
    return num_states * words * 4 + 2 * num_states * TRANSITION_WIDTH * 4


def upload_bounded_grammar_table(
    table: BoundedGrammarTable, device: torch.device
) -> DeviceBoundedGrammarTable:
    """Build the device tensors a step gathers from (see the class docstring)."""
    n = table.num_states
    next_token = torch.full((n, TRANSITION_WIDTH), NO_TRANSITION, dtype=torch.int32)
    next_state = torch.full((n, TRANSITION_WIDTH), NO_TRANSITION, dtype=torch.int32)
    fill = [0] * n
    for (state, token), child in sorted(table.transitions.items()):
        slot = fill[state]
        if slot >= TRANSITION_WIDTH:
            raise ValueError(
                f"bounded grammar state {state} has more than {TRANSITION_WIDTH} "
                f"transitions; the table was built past DEFAULT_MAX_BRANCHING."
            )
        next_token[state, slot] = int(token)
        next_state[state, slot] = int(child)
        fill[state] = slot + 1
    return DeviceBoundedGrammarTable(
        bitmasks_dev=torch.stack(table.bitmasks).to(device),
        next_token_dev=next_token.to(device),
        next_state_dev=next_state.to(device),
        num_states=n,
        vocab_size=table.vocab_size,
    )


def gather_bitmasks(
    next_token: torch.Tensor, state_idx: torch.Tensor, *, vocab_size: int
) -> torch.Tensor:
    """``(B, ceil(vocab_size/32))`` packed int32 legal-token masks for each
    row's state — capture-safe, no host sync.

    A row whose state holds no transition inside ``[0, vocab_size)`` (a
    terminal state, the always-legal sentinel, or a state whose legal set
    lies wholly past a narrower drafter row) is all-legal: the table's
    "stop constraining" convention. Tokens within one state are distinct,
    so summing their bits into a word is their OR.
    """
    words = (int(vocab_size) + 31) // 32
    toks = next_token.index_select(0, state_idx).to(torch.int64)
    valid = (toks >= 0) & (toks < int(vocab_size))
    safe = torch.where(valid, toks, torch.zeros_like(toks))
    bits = torch.where(valid, torch.bitwise_left_shift(torch.ones_like(safe), safe % 32), 0)
    packed = torch.zeros((toks.shape[0], words), dtype=torch.int64, device=toks.device)
    packed.scatter_add_(1, safe // 32, bits)
    packed = torch.where(valid.any(dim=1, keepdim=True), packed, -1)
    return torch.where(packed >= 2**31, packed - 2**32, packed).to(torch.int32)


def gather_next_states(
    next_token: torch.Tensor,
    next_state: torch.Tensor,
    state_idx: torch.Tensor,
    tokens: torch.Tensor,
) -> torch.Tensor:
    """Each row's state after ``tokens`` — capture-safe, no host sync.

    A token with no transition from the row's state sends the row to the
    last row, the reserved always-legal self-loop sentinel of a padded
    capture buffer, so the index stays in range for the next gather.
    """
    sentinel = next_token.shape[0] - 1
    toks = next_token.index_select(0, state_idx)
    hit = toks == tokens.reshape(-1, 1).to(toks.dtype)
    found = torch.where(hit, next_state.index_select(0, state_idx), NO_TRANSITION).amax(dim=1)
    return torch.where(found >= 0, found, sentinel).to(torch.int64)


@dataclass
class BoundedGrammarBinding:
    """One request's live position inside a device-uploaded table.

    Lives beside (not instead of) the request's real
    :class:`~arbi_serve.sampler.xgrammar_processor._PerRequestGrammar` —
    ``state`` tracks the SAME committed-token history the real matcher's
    ``accept_token`` advances, via the CPU table's ``transitions`` dict
    (a host-side dict lookup, same cost class as the real matcher's own
    ``accept_token`` call it rides alongside). ``table``/``device_table``
    are the compiled grammar's cached, shared objects — never rebuilt or
    re-uploaded per request.

    ``state == NO_TRANSITION`` once a commit has taken this request off
    the table's coverage (a terminal state's stop token, or — should not
    happen, since the real matcher and this table were built from the
    SAME compiled grammar, but a mismatch is a bug we degrade rather than
    crash on — a token neither table's ``transitions`` nor its bitmask
    recognises). A caller sees this the same way it reads any
    :data:`NO_TRANSITION` gather: stop masking with the table for the
    rest of this request's life, fall back to the request's other paths
    (the real matcher via :class:`XGrammarLogitsProcessor.__call__`,
    unaffected either way, remains the correctness backstop).
    """

    table: BoundedGrammarTable
    device_table: DeviceBoundedGrammarTable
    state: int = 0


def advance_bounded_binding(binding: BoundedGrammarBinding, token: int) -> None:
    """Advance ``binding.state`` by the SAME committed token the request's
    real matcher just accepted. A no-op once ``state`` is
    :data:`NO_TRANSITION` — nothing to advance off a table this request
    has already left."""
    if binding.state == NO_TRANSITION:
        return
    binding.state = binding.table.transitions.get((binding.state, token), NO_TRANSITION)


def bounded_table_for(
    cache: dict[str, tuple[BoundedGrammarTable, DeviceBoundedGrammarTable] | None],
    key: str,
    compiled: xg.CompiledGrammar,
    vocab_size: int,
    device: torch.device | None,
) -> tuple[BoundedGrammarTable, DeviceBoundedGrammarTable] | None:
    """Build + device-upload one grammar's bounded table ONCE, cached in
    the CALLER's ``cache`` dict by the same content-hash key its compiled-
    grammar cache uses (a plain function taking the dict rather than a
    method owning it — :class:`~arbi_serve.sampler.xgrammar_processor.XGrammarLogitsProcessor`
    is the one owner either way, this just keeps the BFS + upload beside
    the table types they build instead of duplicated onto the processor).

    Skips (returns ``None`` without caching) while ``device`` is still
    unknown — the very first grammar-carrying request of a boot, before
    any forward has resolved one. Every later request on the SAME key
    finds either the built pair or the cached "tried, not bounded"
    negative — this only ever leaves a gap on requests that predate the
    boot's first masked step, and ``None`` is always correct (just not
    accelerated), never wrong.
    """
    if key in cache:
        return cache[key]
    if device is None:
        return None
    table = build_bounded_grammar_table(compiled, vocab_size)
    pair = None
    if table is not None:
        pair = (table, upload_bounded_grammar_table(table, device))
    cache[key] = pair
    return pair
# ---- xgrammar_capability.py ----
# SPDX-License-Identifier: Apache-2.0
"""Check compiler semantics when a request actually needs constrained decoding."""

from functools import lru_cache


class UnsupportedXGrammarCompiler(RuntimeError):
    """The installed compiler cannot enforce the requested schema safely."""


@lru_cache(maxsize=1)
def require_correct_optional_groups() -> None:
    import xgrammar as xg

    # A tiny CPU-only grammar. A looping child end must not be the optional
    # bypass target: that accepts a digit without the mandatory 'b' prefix.
    vocab = [chr(i) for i in range(32, 127)] + ["<stop>"]
    info = xg.TokenizerInfo(vocab, xg.VocabType.RAW, stop_token_ids=[len(vocab) - 1])
    compiler = xg.GrammarCompiler(info, cache_enabled=False)
    grammar = compiler.compile_json_schema({"type": "string", "pattern": "^a(b[0-9]+)?$"})
    for text, expected in (('"a"', True), ('"ab1"', True), ('"a1"', False)):
        matcher = xg.GrammarMatcher(grammar)
        accepted = all(matcher.accept_token(vocab.index(ch)) for ch in text)
        if (accepted and matcher.is_completed()) != expected:
            raise UnsupportedXGrammarCompiler(
                "Installed xgrammar incorrectly bypasses required prefixes in optional regex groups. "
                "Use `arbi-serve run` (it builds a corrected xgrammar once into the per-user "
                "cache), the official arbi-serve image, or run "
                "`python -m _arbi_serve_launcher.xgrammar_fix --install` in this environment. "
                "Unpatched PyPI xgrammar 0.2.8/0.2.9 does not enforce these schemas correctly."
            )


if __name__ == "__main__":
    require_correct_optional_groups()
# ---- xgrammar_draft_walk.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""``DraftGrammarWalk`` — a forked per-chain matcher a drafter's own
per-step loop uses to propose grammar-legal tokens. Split out of
:mod:`arbi_serve.sampler.xgrammar_processor` (which grew past the
file-size ceiling); re-exported there as
``XGrammarLogitsProcessor.start_draft_walk`` /
``.draft_step_bitmask`` / ``.advance_draft_walk`` — thin delegations to the
functions here, so the public surface does not move.

WHY THIS EXISTS. Today only the VERIFY pass
(``XGrammarLogitsProcessor.mask_verify_logits``) is grammar-aware: the
drafter proposes unconstrained, and an illegal draft is simply rejected at
verify time. Under a tight grammar (a bool/enum field, a tool-name
selection — the common case for structured agentic output) that wastes
most of speculation's value: an unconstrained drafter rarely lands inside
a legal set of 2-3 tokens, so the accept rate collapses toward "one
recovery token per step," the same as K=1, while still paying to draft.

DraftGrammarWalk lets a drafter mask its OWN proposals, so a legal draft
is the common case instead of the rare one. It is built around
``GrammarMatcher.fork()`` (documented, stable xgrammar API — a deep copy
of parsing state, independent of the original) rather than the request's
REAL matcher, because a draft is speculative: it may be rejected, and the
real per-request matcher must only ever reflect tokens actually committed
(advanced by ``XGrammarLogitsProcessor.accept_token``, at commit time —
nothing here ever touches that matcher). The walk caches each position's
filled bitmask as it goes; a future integration of ``mask_verify_logits``
can consume those instead of re-deriving the same masks via its own
advance-then-rollback walk on the real matcher — the two are computing
identical bitmasks (same prefix, same grammar) today, just twice.

SCOPE OF WHAT THIS MODULE DOES: matcher lifecycle (fork once, advance per
step, drop at chain end — no rollback) and CPU bitmask fills only — no GPU
masking kernel call, no captured-graph gating. A drafter's eager per-step
loop applies the returned bitmask itself (the same
``xg.apply_token_bitmask_inplace`` call
``XGrammarLogitsProcessor.__call__`` already uses), and a drafter with a
captured fast path must gate on ``any(start_draft_walk(...) is not None
...)`` before entering it — same as the existing "no external processors"
gate the K=1 Sampler already applies for its own argmax fast path. Neither
integration is done here; this is the shared primitive they both need,
built once rather than per drafter.

THIS IS NOT THE CAPTURE-SAFE END STATE, and it is not free even in the
eager path — say so plainly rather than leave it implied. Every xgrammar
call (``fill_next_token_bitmask``, ``accept_token``, ``fork``) is CPU
automaton work, not a GPU op, so :func:`advance_draft_walk` needs the
step's sampled token as a Python int — a real host sync BEFORE the next
step's mask can be computed, on every constrained drafting step. That is
unavoidable calling into xgrammar's matcher at all, per step, in an eager
loop — this primitive does not remove it, it only makes the PROPOSAL
legal instead of the mask arriving too late (at verify) to help
acceptance. Removing the sync entirely needs the grammar's
state -> bitmask / (state, token) -> next-state transitions baked into
DEVICE tensors ahead of time — see
:mod:`arbi_serve.sampler.xgrammar_bounded_table`, which does exactly that
for BOUNDED grammars (enums, booleans, tool-name alternation) via a BFS
over states using these same fork/accept/bitmask primitives, once at
grammar-compile time rather than per request, so a captured replay can
`gather` the next mask with zero CPU involvement. That device-resident
path builds the table only; splicing it into an actual captured graph's
replay is not done anywhere in this codebase yet.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import TYPE_CHECKING

import torch
import xgrammar as xg

if TYPE_CHECKING:
    from arbi_serve.engine.request import Request
    from arbi_serve.sampler.xgrammar_processor import _PerRequestGrammar


@dataclass
class DraftGrammarWalk:
    """One speculative draft chain's grammar state.

    ``matcher`` is a FORK, never the request's real
    ``Request.grammar_state.matcher`` — a draft is speculative and may be
    rejected, so nothing here may advance state the real matcher would
    later need to reflect only the actually-committed prefix. Dropped
    (garbage-collected) at the end of the draft chain; nothing rolls it
    back, because nothing outside this walk ever reads it again.

    ``bitmasks`` accumulates one packed CPU tensor per position filled via
    :func:`draft_step_bitmask`, in step order — the reuse hook a future
    ``mask_verify_logits`` integration would read instead of recomputing
    the same masks.
    """

    matcher: xg.GrammarMatcher
    cache_key: str
    bitmasks: list[torch.Tensor] = field(default_factory=list)


def start_draft_walk(request: Request) -> DraftGrammarWalk | None:
    """Begin a grammar-aware draft chain for ``request``, or ``None``.

    ``None`` when the request carries no live grammar (the overwhelming
    majority of requests) — one attribute check, no fork, no allocation.
    Call once per draft chain (one call to a drafter's ``draft()``), not
    per step; :func:`draft_step_bitmask` / :func:`advance_draft_walk`
    drive the same walk forward across the chain's K positions.
    """
    gs: _PerRequestGrammar | None = request.grammar_state
    if gs is None or gs.matcher.is_terminated():
        return None
    return DraftGrammarWalk(matcher=gs.matcher.fork(), cache_key=gs.cache_key)


def draft_step_bitmask(walk: DraftGrammarWalk, vocab_size: int) -> torch.Tensor:
    """The legal-token bitmask for THIS walk's current (forked) state.

    A packed ``(ceil(V/32),)`` int32 CPU tensor — the same row shape
    ``XGrammarLogitsProcessor.__call__`` fills into its persistent host
    buffer, but standalone here since a draft step masks one row at a time
    (a drafter's own per-step loop calls this once per in-flight
    constrained row per step, not batched across a whole slate the way
    decode-time sampling is). Cached on the walk (``walk.bitmasks``) so a
    later verify re-mask can reuse it instead of recomputing — wiring that
    reuse into ``mask_verify_logits`` is the follow-up this function exists
    to enable, not something it does itself.

    Terminated mid-chain (the grammar's language is already complete —
    e.g. the fork accepted a stop token) returns an ALL-ONES bitmask
    (nothing further is constrained), matching how
    ``XGrammarLogitsProcessor.__call__`` already treats a terminated
    matcher: skip masking, let the model emit anything (typically EOS).
    """
    words = (vocab_size + 31) // 32
    if walk.matcher.is_terminated():
        bm = torch.full((words,), -1, dtype=torch.int32)
    else:
        bm = torch.empty((words,), dtype=torch.int32)
        walk.matcher.fill_next_token_bitmask(bm.unsqueeze(0), 0)
    walk.bitmasks.append(bm)
    return bm


def advance_draft_walk(walk: DraftGrammarWalk, token: int) -> None:
    """Advance THIS WALK's fork by the token the drafter chose.

    Never touches the request's real matcher — see :class:`DraftGrammarWalk`.
    UNLIKE ``XGrammarLogitsProcessor.accept_token`` (which skips a stop
    token, because the real per-request matcher's lifecycle is handled by
    request-finish elsewhere), a stop token here MUST be accepted: it is
    how a walk's own :attr:`~DraftGrammarWalk.matcher` learns it is
    ``is_terminated()`` at all — there is no other signal driving this
    scratch object. Once accepted, :func:`draft_step_bitmask` already
    degrades a terminated walk to all-ones for any further step. A no-op
    only once already terminated (a drafter's loop may call this one step
    past the end).
    """
    if walk.matcher.is_terminated():
        return
    walk.matcher.accept_token(token)
# ---- xgrammar_grammar_source.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Grammar-SOURCE resolution + disk-payload shape — split out of
:mod:`arbi_serve.sampler.xgrammar_processor` (which grew past the
file-size ceiling) along a real seam: everything here turns a request's
sampling params or a ``ResponseFormat`` into a serializable payload, none
of it touches a live matcher or the compiled-grammar cache. Re-exported
from ``xgrammar_processor`` so no import site changes.
"""

from __future__ import annotations

import logging
import pathlib
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any

from arbi_serve.engine.request import ResponseFormat

if TYPE_CHECKING:
    from arbi_serve.engine.tool_parsers.base import ToolParser

logger = logging.getLogger("arbi_serve.sampler.xgrammar")

#: This cache's slug under the one boot cache (:mod:`arbi_serve.cache_paths`).
GRAMMAR_CACHE_SUBDIR = "xgrammar"


@dataclass(frozen=True)
class ModelGrammar:
    """One model's grammar facts: its tool-call wire format and its reasoning-close marker."""

    tool_parser: ToolParser | None = None
    think_end: str | None = None


def resolve_grammar_cache_dir() -> pathlib.Path | None:
    """Return the on-disk grammar cache root, or None when it is unusable.

    ``<boot cache>/xgrammar`` (:mod:`arbi_serve.cache_paths`). A root that
    cannot be created leaves the in-memory cache as the only tier.
    """
    from arbi_serve.cache_paths import boot_cache_subdir

    p = boot_cache_subdir(GRAMMAR_CACHE_SUBDIR)
    try:
        p.mkdir(parents=True, exist_ok=True)
    except OSError as e:
        logger.warning(
            "xgrammar disk cache dir %s unusable (%s); falling back to in-memory cache only.", p, e
        )
        return None
    return p


def disk_payload_for(rf: ResponseFormat) -> dict:
    """The on-disk serializable shape of a ResponseFormat."""
    return {
        "type": rf.type,
        "schema": rf.schema,
        "regex": rf.regex,
        "grammar": rf.grammar,
        "structural_tag": rf.structural_tag,
    }


def disk_payload_to_rf(d: dict) -> ResponseFormat:
    return ResponseFormat(
        type=d.get("type", "text"),
        schema=d.get("schema"),
        regex=d.get("regex"),
        grammar=d.get("grammar"),
        structural_tag=d.get("structural_tag"),
    )


#: response_format types this wraps, and how to build the inner xgrammar
#: Format element for each. All three share the same "constrains the ENTIRE
#: output from token 0" foreclosure (confirmed live for json_schema; regex
#: and grammar go through the identical unwrapped-grammar compile path in
#: xgrammar_processor.attach, so nothing distinguishes them at this layer).
def _json_schema_element(st: Any, rf: ResponseFormat) -> Any:
    import json

    # JSONSchemaFormat.json_schema is a dict/bool field (pydantic-validated),
    # unlike compile_json_schema's own str-only contract (_compile_sync's
    # comment) -- the two xgrammar entry points do not share a convention.
    schema = json.loads(rf.schema) if isinstance(rf.schema, str) else rf.schema
    return st.JSONSchemaFormat(json_schema=schema, style="json")


def _regex_element(st: Any, rf: ResponseFormat) -> Any:
    return st.RegexFormat(pattern=rf.regex)


def _grammar_element(st: Any, rf: ResponseFormat) -> Any:
    return st.GrammarFormat(grammar=rf.grammar)


_BOUNDARY_ELEMENT_BUILDERS = {
    "json_schema": _json_schema_element,
    "regex": _regex_element,
    "grammar": _grammar_element,
}


def apply_thinking_boundary(
    rf: ResponseFormat, sampling: Any, grammar: ModelGrammar | None = None
) -> ResponseFormat:
    """Gate an explicit ``json_schema``/``regex``/``grammar`` behind the
    model's reasoning close.

    Unwrapped, any of these three grammars constrains the ENTIRE output from
    token 0 — a reasoning model can never open its own ``<think>`` content,
    since nothing but the grammar is legal from the first token (confirmed
    live for ``json_schema``: a thinking-mode request with a schema returned
    schema-valid JSON with zero preceding reasoning text; ``regex`` and
    ``grammar`` compile through the same unwrapped path in
    ``xgrammar_processor.attach`` with nothing layer-side distinguishing
    them, so the foreclosure is the same mechanism, not a separate bug).
    ``<think>`` itself is prompt-side (the chat template opens it before
    generation starts on every checkpoint this parser covers), so the model
    only ever needs to write free-form content and then close it — the
    boundary this wraps is exactly that close marker, never an opening one.

    Wrapped as a sequence — free text up to (excluding) the trigger, the
    literal trigger, then the grammar — via ``xgrammar.structural_tag``'s
    ``SequenceFormat``, not ``TriggeredTagsFormat``: a triggered tag's body
    is OPTIONAL (right for a tool call, which may never fire), but a
    ``response_format`` is a contract the client asked for and must still be
    produced, so it stays MANDATORY once the trigger closes reasoning — a
    sequence element, not an optional tag.

    A no-op (returns ``rf`` unchanged) for every other case: a type with no
    registered element builder (``text``/``json_object``/``structural_tag``
    itself), no reasoning close in ``grammar`` (no reasoning parser on this checkpoint),
    or ``SamplingParams.opens_in_reasoning`` is false. That field, not
    ``ChatCompletionRequest.resolved_enable_thinking()``, is the gate: it is
    the MODEL-TRUTH signal set from the actual rendered prompt (did the
    template leave generation inside an unclosed ``<think>``), already
    resolved by the time a request reaches this sampler-level function,
    where ``resolved_enable_thinking`` — an API-schema-layer method — is not
    even reachable (``SamplingParams`` carries no such method; reading it
    via ``getattr`` would silently return ``None`` and wrap every request
    regardless of thinking mode, which is why this uses the field that is
    actually on the object this function receives).
    """
    build_element = _BOUNDARY_ELEMENT_BUILDERS.get(rf.type)
    if build_element is None:
        return rf
    wrapped = _gate_behind_think_end(lambda st: build_element(st, rf), sampling, grammar)
    return rf if wrapped is None else wrapped


def _gate_behind_think_end(
    build_element: Any, sampling: Any, grammar: ModelGrammar | None
) -> ResponseFormat | None:
    """The one thinking-boundary wrap: free text up to the reasoning close,
    the close itself, then ``build_element(st)`` as a MANDATORY element.

    Returns ``None`` (caller keeps its unwrapped grammar) when the model has no
    reasoning close or the request's rendered prompt did not open inside a
    reasoning block (``SamplingParams.opens_in_reasoning``) — see
    :func:`apply_thinking_boundary` for why that field is the gate.
    """
    think_end = grammar.think_end if grammar is not None else None
    if think_end is None:
        return None
    if not getattr(sampling, "opens_in_reasoning", False):
        return None

    import xgrammar.structural_tag as st

    tag = st.StructuralTag(
        format=st.SequenceFormat(
            elements=[
                st.AnyTextFormat(excludes=[think_end]),
                st.ConstStringFormat(value=think_end),
                build_element(st),
            ]
        )
    )
    return ResponseFormat(type="structural_tag", structural_tag=tag.model_dump_json())


def _tool_grammar_rf(sampling: Any, grammar: ModelGrammar | None) -> ResponseFormat | None:
    """The tool-call grammar for ``(tools, tool_choice)``, gated behind the
    reasoning close when the choice ENFORCES a call and the request opens in
    reasoning.

    Unwrapped, ``"required"`` / a named choice forces the call surface from
    token 0 — while the model is still inside ``<think>`` — so the forced call
    lands in ``reasoning_content``, the model then closes the block and writes
    prose, and the response carries no ``tool_calls`` (seen live on
    Qwen3.8-27B with thinking on). Gated, reasoning is free text and, after
    the close, only optional whitespace (the template's own ``</think>`` + blank line
    separator) and then the call(s) are legal, which the reasoning split +
    tool extractor read back as ``tool_calls``.

    ``"auto"`` stays unwrapped: it forces nothing, so there is nothing to
    gate, and wrapping would only make every thinking-mode tool request pay
    a live mask on every reasoning token and forbid EOS before the close.
    """
    from arbi_serve.sampler.tool_grammar import _resolve_choice, build_tool_structural_tag

    parser = grammar.tool_parser if grammar is not None else None
    tag = build_tool_structural_tag(sampling.tools, sampling.tool_choice, parser)
    if tag is None:
        return None
    mode, _ = _resolve_choice(sampling.tool_choice)
    if mode != "auto":
        wrapped = _gate_behind_think_end(
            lambda st: st.SequenceFormat(elements=[st.RegexFormat(pattern=r"\s*"), tag.format]),
            sampling,
            grammar,
        )
        if wrapped is not None:
            return wrapped
    return ResponseFormat(type="structural_tag", structural_tag=tag.model_dump_json())


def effective_response_format(
    sampling: Any, grammar: ModelGrammar | None = None
) -> ResponseFormat | None:
    """The single grammar source for a request — used by BOTH the single-rank
    attach path and the SPMD admit path so every rank agrees.

    Precedence: an explicit non-text ``response_format`` wins (see
    :func:`apply_thinking_boundary` for the one transform applied to it);
    otherwise tools + an enforcing ``tool_choice`` synthesize a
    structural-tag grammar, gated behind the same reasoning close
    (:func:`_tool_grammar_rf`). Returns ``None`` when nothing constrains
    decoding. ``grammar`` is the serving model's :class:`ModelGrammar`
    (``None``: the Hermes-JSON default and no reasoning gate).
    """
    if getattr(grammar.tool_parser if grammar is not None else None, "harmony", False):
        from arbi_serve.sampler.harmony_grammar import harmony_response_format

        return harmony_response_format(sampling)
    rf = getattr(sampling, "response_format", None)
    if rf is not None and getattr(rf, "type", "text") != "text":
        return apply_thinking_boundary(rf, sampling, grammar)
    if not getattr(sampling, "tools", None) or getattr(sampling, "tool_choice", None) == "none":
        return None
    return _tool_grammar_rf(sampling, grammar)


def grammar_payload_for(sampling: Any, grammar: ModelGrammar | None = None) -> dict | None:
    """Pickle-friendly grammar spec for a request, or ``None``.

    Carried once in the SPMD ``AdmitRow`` so every rank reconstructs the
    identical grammar (and thus an identical matcher) locally. Reuses the
    on-disk ResponseFormat payload shape.
    """
    rf = effective_response_format(sampling, grammar)
    return disk_payload_for(rf) if rf is not None else None
# ---- xgrammar_processor.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Constrained decoding via :pypi:`xgrammar`.

Surface
-------

The processor is constructed once per engine and shared across every
request. Each request owns its own :class:`xgrammar.GrammarMatcher`
(per-request automaton state); the *compiled* grammar
(:class:`xgrammar.CompiledGrammar`) is shared across requests via a
content-hash-keyed in-process cache, since compilation costs seconds
for large JSON Schemas while matcher construction is microseconds.

Per-step contract
-----------------

For each ``(k, request)`` row whose request carries a
``response_format``:

  1. Look up the request's matcher (``request.grammar_state``); if
     missing, lazily build it from the cached
     :class:`CompiledGrammar`.
  2. Fill that row's slot in a *shared* pinned host bitmask via
     ``matcher.fill_next_token_bitmask(host_bitmask, row_index)`` —
     all CPU work, no device traffic.
  3. After every constrained row is filled, perform ONE H2D copy
     of the populated host bitmask region into a persistent device
     bitmask, then ONE fused
     ``xgrammar.apply_token_bitmask_inplace(logits_2d, device_bitmask,
     indices=constrained_row_idx)`` kernel launch — disallowed tokens
     are set to ``-inf`` for every constrained row in a single pass.

After sampling, the engine calls :meth:`accept_token` so the matcher
advances its per-request automaton state.

Batching rationale
------------------

xgrammar's kernel takes an ``indices=`` argument so a single dense
bitmask covering every row in the flat ``(K*B, V)`` logits view can be
filled CPU-side, copied once, and applied to every constrained row in
one launch, instead of one per-request bitmask copy + kernel launch
per ``(k, request)``.

Cache safety / thread safety
----------------------------

The cache is a plain dict guarded by an :class:`asyncio.Lock`; entries
build via ``asyncio.to_thread`` (compilation is CPU-bound).
``GrammarMatcher.fork()`` is the documented way to spawn an
independent matcher for the same grammar; matchers do not share
mutable state with the ``CompiledGrammar``.

The shared host / device bitmask buffers are written to at *distinct
row indices* per request per step (the row index is the request's
flat (k, i) coordinate in the current logits batch), so concurrent
``fill_next_token_bitmask`` calls touch non-overlapping memory. The
processor's :meth:`__call__` runs synchronously in a single thread
(the engine's run loop), so no lock is needed around buffer access.
"""

from __future__ import annotations

import asyncio
import hashlib
import json
import logging
import os
import pathlib
from collections import OrderedDict
from collections.abc import Sequence
from contextlib import nullcontext
from dataclasses import dataclass

import torch
import xgrammar as xg

from arbi_serve.engine.request import Request, ResponseFormat
from arbi_serve.sampler.tool_grammar_fallback import compile_tool_grammar
from arbi_serve.sampler.vocab_window import BITMASK_WORD, VocabWindow
from arbi_serve.sampler.xgrammar_bounded_table import (
    BoundedGrammarBinding,
    BoundedGrammarTable,
    DeviceBoundedGrammarTable,
)
from arbi_serve.sampler.xgrammar_bounded_table import (
    advance_bounded_binding as _advance_bounded_binding,
)
from arbi_serve.sampler.xgrammar_bounded_table import (
    bounded_table_for as _bounded_table_for,
)
from arbi_serve.sampler.xgrammar_draft_walk import DraftGrammarWalk  # noqa: F401 — re-exported
from arbi_serve.sampler.xgrammar_draft_walk import (
    advance_draft_walk as _advance_draft_walk,
)
from arbi_serve.sampler.xgrammar_draft_walk import (
    draft_step_bitmask as _draft_step_bitmask,
)
from arbi_serve.sampler.xgrammar_draft_walk import (
    start_draft_walk as _start_draft_walk,
)
from arbi_serve.sampler.xgrammar_grammar_source import (
    apply_thinking_boundary as _apply_thinking_boundary,
)
from arbi_serve.sampler.xgrammar_grammar_source import (
    disk_payload_for as _disk_payload_for,
)
from arbi_serve.sampler.xgrammar_grammar_source import (
    disk_payload_to_rf as _disk_payload_to_rf,
)
from arbi_serve.sampler.xgrammar_grammar_source import (
    effective_response_format,  # noqa: F401 — re-exported
    grammar_payload_for,  # noqa: F401 — re-exported
)
from arbi_serve.sampler.xgrammar_grammar_source import (
    resolve_grammar_cache_dir as _resolve_grammar_cache_dir,
)
from arbi_serve.sampler.xgrammar_processor_spmd import _XGrammarSpmdSyncMixin

logger = logging.getLogger("arbi_serve.sampler.xgrammar")


# B4: default LRU cap for the in-process compiled-grammar cache.
# Sized bigger than typical workloads' distinct-schema count; evict
# oldest on overflow so unbounded growth never eats RSS.
_DEFAULT_COMPILED_CACHE_SIZE = 256


# Persistent on-disk grammar cache.
#
# xgrammar 0.1.x does not expose a stable serialized form for
# ``CompiledGrammar``, so we persist the *source* — the original
# :class:`ResponseFormat` payload — keyed by sha256, and recompile on
# warm restart. Recompile is still far cheaper than cold engine boot
# because tokenizer-info construction + vocab encoding happen once at
# boot, not per grammar. When xgrammar exposes
# ``CompiledGrammar.serialize / deserialize`` this can upgrade to
# byte-level persistence with the same put/get key.


# Standalone allocation hint. Engine builds pass their configured batch size
# and reserve the actual (draft depth + 1) * max_batch before capture instead.
# Buffers grow on demand for standalone callers; this hint is not a cap.
_DEFAULT_INITIAL_BATCH_ROWS = 64 * 8


@dataclass
class _PerRequestGrammar:
    """One in-flight request's structured-decoding state.

    Lives on ``Request.grammar_state`` so concurrent requests share no
    mutable matcher state at the processor level. Bitmask buffers are
    shared engine-wide and addressed by row index per step (see the
    processor docstring); this struct only carries the per-request
    matcher + diagnostics.
    """

    matcher: xg.GrammarMatcher
    vocab_size: int
    cache_key: str  # for diagnostics / cache stats
    #: This request's live position in the grammar's device-uploaded
    #: bounded-state table, or ``None`` when the grammar is not bounded
    #: (most grammars) or the processor's device was not yet known when
    #: this matcher was installed (a one-time cold-start gap, self-heals
    #: on the request after it — see ``_bounded_table_for``). Purely an
    #: optimization: every request is ALSO correct through ``matcher``
    #: regardless of whether this is set.
    bounded: BoundedGrammarBinding | None = None


@dataclass
class _CacheStats:
    """Hit/miss counters for the compiled-grammar cache."""

    hits: int = 0
    misses: int = 0


class XGrammarLogitsProcessor(_XGrammarSpmdSyncMixin):
    """Implements :class:`LogitsProcessor`. Compiles + applies grammars.

    The processor is shared across requests (engine-level singleton);
    per-request state lives on ``Request.grammar_state`` so concurrent
    requests don't share mutable matcher state.
    """

    def __init__(
        self,
        tokenizer_info: xg.TokenizerInfo,
        *,
        max_compile_threads: int = 4,
        disk_cache_dir: pathlib.Path | None = None,
        cache_size: int = _DEFAULT_COMPILED_CACHE_SIZE,
        initial_batch_rows: int = _DEFAULT_INITIAL_BATCH_ROWS,
    ) -> None:
        self._tok_info = tokenizer_info
        self._compiler = xg.GrammarCompiler(
            tokenizer_info,
            max_threads=max_compile_threads,
            # The bounded Python LRU owns compiled grammars. A second,
            # unbounded compiler cache would retain its evicted entries.
            cache_enabled=False,
        )
        # B4: content-hash → CompiledGrammar — LRU bounded so
        # unbounded workloads don't grow the in-process cache for
        # the lifetime of the process. ``OrderedDict`` lets
        # ``move_to_end`` refresh an entry on hit and
        # ``popitem(last=False)`` drop the LRU tail on overflow,
        # both O(1).
        self._cache_size: int = max(1, int(cache_size))
        self._compiled_cache: OrderedDict[str, xg.CompiledGrammar] = OrderedDict()
        # content-hash → asyncio.Future for an in-flight compile, so
        # concurrent requests with the same grammar key share one compile
        # job rather than each spawning their own.
        self._pending: dict[str, asyncio.Future[xg.CompiledGrammar]] = {}
        self._cache_lock = asyncio.Lock()
        self._stats = _CacheStats()
        # grammar key -> (BoundedGrammarTable, DeviceBoundedGrammarTable) |
        # None, built once per distinct grammar — see ``bounded_table_for``.
        # Missing key: not tried yet. Present ``None``: tried, not bounded
        # (a negative cache; an unbounded grammar's BFS is a real cost).
        self._bounded_table_cache: dict[
            str, tuple[BoundedGrammarTable, DeviceBoundedGrammarTable] | None
        ] = {}
        # Disk persistence. Default to env-var resolution; tests pass
        # an explicit path.
        self._disk_cache_dir: pathlib.Path | None = (
            disk_cache_dir if disk_cache_dir is not None else _resolve_grammar_cache_dir()
        )

        # Persistent batched bitmask buffers — see :meth:`__call__`.
        # Sized at first call to (max(initial_batch_rows, current K*B),
        # ceil(V / 32)) and reallocated only when a larger step lands.
        self._bitmask_words = (self.vocab_size + 31) // 32
        self._max_rows: int = max(1, int(initial_batch_rows))
        self._host_bitmask: torch.Tensor = self._alloc_host_bitmask(self._max_rows)
        # Persistent pinned host buffer for the constrained-row index
        # tensor. Reused per step to avoid pageable-to-device copies
        # of a fresh tensor every call. Sized to one int32 per
        # potential logits row.
        self._host_indices: torch.Tensor = self._alloc_host_indices(self._max_rows)
        # Device bitmask + indices are allocated lazily on first call
        # with a CUDA tensor — at processor-init time the device is
        # unknown (CPU-only tests, mixed-device deployments, hot-swap
        # gates).
        self._device_bitmask: torch.Tensor | None = None
        self._device_indices: torch.Tensor | None = None
        self._device: torch.device | None = None
        self._buffer_pool = None

    @classmethod
    def from_tokenizer(
        cls,
        tokenizer,
        *,
        vocab_size: int | None = None,
        stop_token_ids: list[int] | None = None,
        disk_cache_dir: pathlib.Path | None = None,
        cache_size: int = _DEFAULT_COMPILED_CACHE_SIZE,
        initial_batch_rows: int = _DEFAULT_INITIAL_BATCH_ROWS,
    ) -> XGrammarLogitsProcessor:
        """Build from our :class:`arbi_serve.tokenizer.Tokenizer`.

        Constructs an :class:`xg.TokenizerInfo` directly from the
        decoded vocab list and known stop tokens (no HF
        ``PreTrainedTokenizerBase`` is required).

        ``vocab_size`` should match the model's lm_head width (often
        larger than the tokenizer's vocab — Qwen3-4B for example has a
        tokenizer of 151,669 tokens but a 151,936-wide lm_head with
        padding for fast matmul). When the bitmask is sized to the
        narrower tokenizer vocab the model can sample logits at the
        padding indices, which xgrammar then rejects with an
        out-of-range warning.
        """
        # Vocab strings retain their backend encoding: byte-level BPE and
        # SentencePiece byte-fallback spell spaces/bytes differently. Use
        # xgrammar's own HF-backend detector, without importing transformers.
        metadata = xg.TokenizerInfo._detect_metadata_from_hf(tokenizer.tokenizer.to_str())
        vocab = tokenizer.tokenizer.get_vocab()
        v_size = vocab_size if vocab_size is not None else tokenizer.vocab_size
        encoded = [""] * v_size
        for tok_str, tok_id in vocab.items():
            if 0 <= tok_id < v_size:
                encoded[tok_id] = tok_str
        # xgrammar renamed the prefix-space kwarg around 0.1.30:
        # older builds use ``add_prefix_space``; newer use
        # ``prepend_space_in_tokenization``. Probe the constructor
        # signature once instead of pinning the SDK version.
        import inspect

        ti_params = set(inspect.signature(xg.TokenizerInfo.__init__).parameters)
        prefix_kw = (
            "prepend_space_in_tokenization"
            if "prepend_space_in_tokenization" in ti_params
            else "add_prefix_space"
        )
        info = xg.TokenizerInfo(
            encoded_vocab=encoded,
            vocab_type=metadata["vocab_type"],
            vocab_size=v_size,
            stop_token_ids=stop_token_ids or [],
            **{prefix_kw: metadata["add_prefix_space"]},
        )
        return cls(
            info,
            disk_cache_dir=disk_cache_dir,
            cache_size=cache_size,
            initial_batch_rows=initial_batch_rows,
        )

    @property
    def vocab_size(self) -> int:
        """Vocabulary size reported by the tokenizer info."""
        return self._tok_info.vocab_size

    # ── batched bitmask buffer helpers ──────────────────────────────

    def reserve_buffers(self, rows: int, device: torch.device, *, pool=None) -> None:
        """Preallocate the serving slate in its owning pool before first use."""
        if self._device_bitmask is not None:
            raise RuntimeError("Grammar buffers must be reserved before their first use")
        self._buffer_pool = pool
        self._ensure_buffers(rows, device)

    def _alloc_host_bitmask(self, rows: int) -> torch.Tensor:
        """Allocate a pinned (rows, ceil(V/32)) int32 host bitmask.

        ``pin_memory=True`` is best-effort: on CPU-only hosts (CI test
        runners with no CUDA) it raises ``RuntimeError``; we fall back
        to an unpinned tensor so the CPU code path still works.
        ``inference_mode(False)`` per :meth:`_ensure_buffers`.
        """
        with torch.inference_mode(False):
            try:
                return torch.empty(
                    (rows, self._bitmask_words),
                    dtype=torch.int32,
                    pin_memory=torch.cuda.is_available(),
                )
            except RuntimeError:
                return torch.empty((rows, self._bitmask_words), dtype=torch.int32)

    def _alloc_host_indices(self, rows: int) -> torch.Tensor:
        """Allocate a pinned (rows,) int32 host indices buffer.

        ``inference_mode(False)`` per :meth:`_ensure_buffers`.
        """
        with torch.inference_mode(False):
            try:
                return torch.empty(
                    (rows,),
                    dtype=torch.int32,
                    pin_memory=torch.cuda.is_available(),
                )
            except RuntimeError:
                return torch.empty((rows,), dtype=torch.int32)

    def _ensure_buffers(self, rows: int, device: torch.device) -> None:
        """Grow / re-home the persistent bitmask + indices buffers.

        Buffers grow if ``rows`` exceeds the current cap; they are
        also reallocated when the device changes (hot-swap). Steady
        state never reallocates — the common path is a no-op except
        on the first call where the device buffer must be created.

        ``torch.inference_mode(False)`` is LOAD-BEARING, not defensive.
        These buffers are persistent cross-step scratch, but the two
        writers reach them from opposite autograd contexts: the main
        sampler chain (:meth:`__call__`) runs OUTSIDE the forward's
        ``inference_mode`` window, while the speculative verify masker
        (:meth:`mask_verify_logits`) runs INSIDE it. A tensor allocated
        under ``inference_mode`` is an inference tensor and can never be
        updated in place again once execution leaves that region, so
        letting the verify path win the lazy-allocation race would make
        every later ``__call__`` raise "Inplace update to inference
        tensor outside InferenceMode" — killing the whole co-batched
        step, not just the constrained row. Allocating with inference
        mode explicitly OFF yields normal tensors, which both writers may
        update in place from either context.
        """
        if rows > self._max_rows:
            new_cap = max(rows, self._max_rows * 2)
            self._host_bitmask = self._alloc_host_bitmask(new_cap)
            self._host_indices = self._alloc_host_indices(new_cap)
            self._device_bitmask = None  # force device realloc below
            self._device_indices = None
            self._max_rows = new_cap
        if (
            self._device_bitmask is None
            or self._device_indices is None
            or self._device is None
            or self._device != device
            or self._device_bitmask.shape[0] != self._max_rows
        ):
            with (
                self._buffer_pool.use() if self._buffer_pool is not None else nullcontext(),
                torch.inference_mode(False),
            ):
                self._device_bitmask = torch.empty(
                    (self._max_rows, self._bitmask_words),
                    dtype=torch.int32,
                    device=device,
                )
                self._device_indices = torch.empty(
                    (self._max_rows,),
                    dtype=torch.int32,
                    device=device,
                )
            self._device = device

    # ── cache + per-request state ────────────────────────────────────

    @staticmethod
    def _cache_key(rf: ResponseFormat) -> str:
        """Stable content hash for a :class:`ResponseFormat`.

        A ``json_schema`` is hashed in its DECLARED key order, never
        ``sort_keys``: xgrammar emits an object's ``properties`` in the order
        the schema lists them, so two schemas that differ only in property
        order compile to different grammars and must not share a cache entry.
        """
        if rf.type == "json_object":
            payload = "json_object"
        elif rf.type == "json_schema":
            payload = "json_schema:" + json.dumps(rf.schema, separators=(",", ":"))
        elif rf.type == "regex":
            payload = "regex:" + (rf.regex or "")
        elif rf.type == "grammar":
            payload = "grammar:" + (rf.grammar or "")
        elif rf.type == "structural_tag":
            payload = "structural_tag:" + (rf.structural_tag or "")
        else:
            raise ValueError(f"unsupported response_format type {rf.type!r}")
        return hashlib.sha256(payload.encode("utf-8")).hexdigest()

    def _cache_get(self, key: str) -> xg.CompiledGrammar | None:
        """LRU-refreshing read. The ONE reader of ``_compiled_cache``."""
        cached = self._compiled_cache.get(key)
        if cached is not None:
            # LRU refresh: bump to the most-recently-used end so a
            # subsequent eviction picks a colder entry.
            self._compiled_cache.move_to_end(key, last=True)
        return cached

    def _cache_put(self, key: str, compiled: xg.CompiledGrammar) -> None:
        """LRU insert + evict down to the cap. The ONE writer of
        ``_compiled_cache``.

        Idempotent by key: the compile is a deterministic function of the
        grammar source and the key is its content hash, so a re-insert (async
        attach and the SPMD sync build racing on the same key) replaces an
        entry with an equivalent automaton. Callers hold a strong ref to the
        object they got, so an eviction under them is safe.
        """
        self._compiled_cache[key] = compiled
        self._compiled_cache.move_to_end(key, last=True)
        # LRU overflow: CPU bytes only, not VRAM, but unbounded growth eats
        # RSS under workloads with high schema diversity.
        while len(self._compiled_cache) > self._cache_size:
            evicted_key, _ = self._compiled_cache.popitem(last=False)
            self._bounded_table_cache.pop(evicted_key, None)
            logger.debug(
                "xgrammar LRU: evicting cache_key=%s to keep size at %d",
                evicted_key,
                self._cache_size,
            )

    async def get_or_compile(self, rf: ResponseFormat) -> xg.CompiledGrammar:
        """Return a cached :class:`CompiledGrammar`, compiling on miss.

        Compilation is CPU-bound and runs in a worker thread.
        Concurrent calls for the same grammar key share one compile
        job via a per-key future, so N identical-schema requests
        spawn one ``to_thread`` worker rather than racing on
        xgrammar's internal compile lock.

        On in-memory miss the on-disk cache is probed: a hit still
        recompiles (the binary form isn't stable across xgrammar
        versions) but skips the network / file fetch.
        """
        key = self._cache_key(rf)
        # Fast path under the cache lock.
        loop = asyncio.get_running_loop()
        async with self._cache_lock:
            cached = self._cache_get(key)
            if cached is not None:
                self._stats.hits += 1
                return cached
            pending = self._pending.get(key)
            if pending is not None:
                # Another caller is already compiling this exact
                # grammar — wait on its Future. Counts as a hit since
                # we won't spawn a duplicate job.
                self._stats.hits += 1
            else:
                self._stats.misses += 1
                pending = loop.create_future()
                self._pending[key] = pending
                # Schedule the actual compile on a worker thread; the
                # body of this branch is the producer for `pending`.
                asyncio.create_task(self._compile_and_publish(key, rf, pending))
        # One disconnected request must not cancel compilation shared by
        # other admissions or prevent the result from entering the cache.
        return await asyncio.shield(pending)

    def _disk_path_for(self, key: str) -> pathlib.Path | None:
        if self._disk_cache_dir is None:
            return None
        return self._disk_cache_dir / f"{key}.json"

    def _disk_load_source(self, key: str) -> ResponseFormat | None:
        """Read the cached source for ``key`` if present, else None."""
        path = self._disk_path_for(key)
        if path is None or not path.exists():
            return None
        try:
            with open(path) as f:
                payload = json.load(f)
            return _disk_payload_to_rf(payload)
        except (OSError, json.JSONDecodeError) as e:
            logger.warning(
                "xgrammar disk cache: failed to read %s (%s); treating as miss.", path, e
            )
            return None

    def _disk_store_source(self, key: str, rf: ResponseFormat) -> None:
        """Write the grammar source to disk so a future engine restart
        can fast-load it without going back to the request payload.
        Best-effort; disk failures degrade to in-memory-only cache."""
        path = self._disk_path_for(key)
        if path is None:
            return
        try:
            tmp = path.with_suffix(".tmp")
            with open(tmp, "w") as f:
                # No sort_keys: the schema's key order is grammar semantics
                # (see _cache_key), and this file is what a warm restart
                # recompiles from.
                json.dump(_disk_payload_for(rf), f, separators=(",", ":"))
            os.replace(tmp, path)
        except OSError as e:
            logger.warning(
                "xgrammar disk cache: failed to write %s (%s); in-memory cache still populated.",
                path,
                e,
            )

    async def _compile_and_publish(
        self,
        key: str,
        rf: ResponseFormat,
        future: asyncio.Future[xg.CompiledGrammar],
    ) -> None:
        try:
            # Disk fast path — if the source is already on disk we still
            # recompile (xgrammar 0.1.x doesn't expose a stable
            # CompiledGrammar serializer), but we don't *also* fail when
            # the caller-supplied rf differs from what's on disk: the
            # cache key is a content hash so a hit means by-construction
            # the payloads match.
            disk_rf = await asyncio.to_thread(self._disk_load_source, key)
            compile_source = disk_rf if disk_rf is not None else rf
            compiled = await asyncio.to_thread(self._compile_sync, compile_source)
        except BaseException as e:  # noqa: BLE001 — propagate cancel to awaiters
            async with self._cache_lock:
                self._pending.pop(key, None)
            if not future.done():
                future.set_exception(e)
            return
        async with self._cache_lock:
            self._cache_put(key, compiled)
            self._pending.pop(key, None)
        # Persist the source to disk on first successful compile so
        # warm restarts hit the disk fast path. Best-effort — the
        # in-memory cache is already populated.
        if disk_rf is None:
            try:
                await asyncio.to_thread(self._disk_store_source, key, rf)
            except OSError as e:
                logger.warning("xgrammar disk-cache write failed: %s", e)
        if not future.done():
            future.set_result(compiled)

    def _compile_sync(
        self, rf: ResponseFormat, *, check_compiler: bool = True
    ) -> xg.CompiledGrammar:
        """Compile ``rf``. ``check_compiler=False`` is for a grammar the engine itself builds with no regex
        optional group (the boot-time logprobs realization row's boolean schema), where the compiler's
        optional-group defect cannot matter; every caller's schema keeps the check."""
        from arbi_serve.sampler.xgrammar_capability import require_correct_optional_groups

        if check_compiler:
            require_correct_optional_groups()
        if rf.type == "json_object":
            return self._compiler.compile_builtin_json_grammar()
        if rf.type == "json_schema":
            # xgrammar >= 0.1.13 rejects dict schemas — accepts str /
            # Pydantic only. Serialize PRESERVING key order, never
            # ``sort_keys``: xgrammar emits ``properties`` in the order the
            # schema declares them, so a sorted schema is a different
            # grammar — one that masks the model's own key order and can
            # leave ``[]`` as the only completion of an array of objects
            # (tests/test_xgrammar_schema_property_order.py).
            schema = rf.schema if isinstance(rf.schema, str) else json.dumps(rf.schema)
            return self._compiler.compile_json_schema(schema)
        if rf.type == "regex":
            return self._compiler.compile_regex(rf.regex)
        if rf.type == "grammar":
            return self._compiler.compile_grammar(xg.Grammar.from_ebnf(rf.grammar))
        if rf.type == "structural_tag":
            # ``structural_tag`` is the xgrammar StructuralTag serialized to a
            # JSON string; ``compile_structural_tag`` accepts the str form.
            return self._compiler.compile_structural_tag(rf.structural_tag)
        raise ValueError(f"unsupported response_format type {rf.type!r}")

    async def attach(self, request: Request) -> None:
        """Build the per-request matcher. The ONE builder of
        ``Request.grammar_state``.

        Called by the engine before the request is admitted, on every routing.
        Idempotent: a second call is a no-op once ``grammar_state`` is
        populated.

        Every exit either installs a matcher or explicitly clears
        ``grammar_required`` — a request must never leave here requiring a
        grammar it does not have.
        """
        if request.grammar_state is not None:
            return
        rf = request.sampling.response_format
        if rf is not None and rf.type != "text":
            # Explicit response_format: the client asked for this, so a
            # compile failure surfaces (caller turns it into a 400).
            # apply_thinking_boundary gates a json_schema behind the model's
            # reasoning close marker when thinking may be active — see its
            # own docstring; a no-op for every other case (same object back).
            rf = _apply_thinking_boundary(rf, request.sampling, request.model_grammar)
            compiled = await self.get_or_compile(rf)
            self._install_matcher(request, compiled, self._cache_key(rf))
            return
        # Tool-call enforcement: build a structural-tag grammar from the
        # request's tools + tool_choice. Unlike an explicit response_format,
        # a failure here DEGRADES (proceed unconstrained; the output parser
        # still extracts) rather than failing the request. An enforcing
        # tool_choice is gated behind the same reasoning close as above
        # (xgrammar_grammar_source._tool_grammar_rf).
        tool_rf = effective_response_format(request.sampling, request.model_grammar)
        if tool_rf is None:
            request.grammar_required = False
            return
        built = await compile_tool_grammar(self, tool_rf)
        if built is None:  # logged + counted by the degrade ladder
            request.grammar_required = False
            return
        self._install_matcher(request, built[0], self._cache_key(built[1]))

    def _install_matcher(self, request: Request, compiled: xg.CompiledGrammar, key: str) -> None:
        # Another compile can evict this key before its awaiter resumes.
        # Re-establish ownership before caching the associated device table.
        if key not in self._compiled_cache:
            self._cache_put(key, compiled)
        pair = _bounded_table_for(
            self._bounded_table_cache, key, compiled, self.vocab_size, self._device
        )
        request.grammar_state = _PerRequestGrammar(
            matcher=xg.GrammarMatcher(compiled),
            vocab_size=self.vocab_size,
            cache_key=key,
            bounded=(
                BoundedGrammarBinding(table=pair[0], device_table=pair[1])
                if pair is not None
                else None
            ),
        )

    # ── SPMD: synchronous per-rank matcher build ─────────────────────
    #
    # get_or_compile_sync / build_grammar_state live in
    # xgrammar_processor_spmd._XGrammarSpmdSyncMixin (file-size split; see
    # that module's docstring), mixed into this class below.

    # ── LogitsProcessor surface ──────────────────────────────────────

    def __call__(
        self,
        logits: torch.Tensor,  # (K, num_seqs, V) fp32
        requests: Sequence[Request],
    ) -> torch.Tensor:
        K, B, V = logits.shape
        if len(requests) != B:
            raise RuntimeError(
                f"XGrammarLogitsProcessor: logits B={B} but {len(requests)} requests."
            )

        # First pass: discover which (k, request) rows actually need
        # masking. Skip terminated matchers (no further constraint
        # applies — model can emit EOS / arbitrary). The flat row
        # index uses the same convention as ``logits.view(K*B, V)``:
        # row = k*B + i.
        constrained_indices: list[int] = []
        constrained_grammars: list[_PerRequestGrammar] = []
        for i, req in enumerate(requests):
            gs: _PerRequestGrammar | None = req.grammar_state
            if gs is None:
                # Invariant: a request requiring constrained decoding reached
                # sampling with no matcher. Sampling it here would silently
                # emit unconstrained (schema-violating) output. One attribute
                # load on the unconstrained hot path.
                if req.grammar_required:
                    raise RuntimeError(
                        f"XGrammarLogitsProcessor: request {req.request_id} requires "
                        "constrained decoding but reached sampling with no grammar "
                        "matcher — it would sample UNCONSTRAINED. No routing may skip "
                        "the matcher build (Request.grammar_state is built by "
                        "XGrammarLogitsProcessor.attach; the SPMD mirror's by "
                        "build_grammar_state)."
                    )
                continue
            if gs.matcher.is_terminated():
                continue
            for k in range(K):
                constrained_indices.append(k * B + i)
                constrained_grammars.append(gs)

        if not constrained_indices:
            return logits

        # Clone once — the rest of the sampler chain expects a tensor
        # we own (the caller passed us the engine's logits buffer).
        out = logits.clone()
        flat_rows = K * B
        device = out.device
        self._ensure_buffers(flat_rows, device)

        # CPU fill: one per constrained row. Each
        # ``fill_next_token_bitmask`` call writes a single row of the
        # shared host pinned tensor at the row's flat logits index.
        # xgrammar's Matcher.fill is CPU-only and does not advance
        # matcher state, so calling it K times for the same matcher
        # (one per draft position) is safe AND correct: every K row
        # for a given request observes the same allowed-token set
        # (the matcher hasn't accepted any of the K-step draft tokens
        # yet — that happens after sampling, in :meth:`accept_token`).
        host = self._host_bitmask
        for row_idx, gs in zip(constrained_indices, constrained_grammars, strict=False):
            gs.matcher.fill_next_token_bitmask(host, row_idx)

        # Single H2D copy of the populated bitmask region. We copy
        # the full ``[:flat_rows]`` slice rather than scatter just
        # the ``constrained_indices`` rows for two reasons: (1) one
        # contiguous DMA beats N strided index_copy_ launches when N
        # > a handful, (2) xgrammar's kernel only touches
        # ``bitmask[batch_id]`` for batch_id in ``indices`` so stale
        # rows in non-constrained slots are harmless. ``flat_rows``
        # is bounded by ``max_batch * max_K`` so this is cheap (~1 MB
        # at B=64 K=1 V=151936).
        assert self._device_bitmask is not None  # _ensure_buffers
        assert self._device_indices is not None
        device_bm = self._device_bitmask
        device_bm[:flat_rows].copy_(host[:flat_rows], non_blocking=True)

        # Stage the constrained-row index list into the persistent
        # pinned host buffer and DMA it to the persistent device
        # buffer. Passing the device tensor directly to xgrammar
        # avoids the pageable-host → device copy xgrammar would
        # otherwise issue (it accepts both ``list[int]`` and
        # ``torch.Tensor``; on tensor input the Triton kernel uses it
        # as-is once on-device).
        n = len(constrained_indices)
        host_idx = self._host_indices[:n]
        host_idx.copy_(torch.tensor(constrained_indices, dtype=torch.int32, device="cpu"))
        device_idx = self._device_indices[:n]
        device_idx.copy_(host_idx, non_blocking=True)

        # Single fused kernel launch. ``logits.view(K*B, V)`` shares
        # storage with ``out``, so the in-place mask propagates back
        # — the kernel writes ``-inf`` at every disallowed token in
        # every constrained row in one pass.
        logits_2d = out.view(flat_rows, V)
        xg.apply_token_bitmask_inplace(
            logits_2d,
            device_bm[:flat_rows],
            indices=device_idx,
        )
        return out

    async def accept_token(self, request: Request, token: int) -> None:
        """Advance the per-request matcher after a token is committed."""
        gs: _PerRequestGrammar | None = request.grammar_state
        if gs is None:
            return
        if gs.matcher.is_terminated():
            return
        # Returns False if the token violates the grammar — should not
        # happen since we masked, but defend against EOS / stop tokens
        # the model can still emit.
        if token in gs.matcher.stop_token_ids:
            return
        accepted = gs.matcher.accept_token(token)
        if not accepted:
            logger.warning(
                "xgrammar: matcher rejected sampled token %d for request %d (cache_key=%s)",
                token,
                request.request_id,
                gs.cache_key,
            )
            return
        # Lockstep with the REAL matcher's advance, not a separate
        # decision: a stop token never reaches here (returned above,
        # matching the real matcher's own skip), so ``bounded`` only ever
        # advances on committed CONTENT tokens. Its state after the last
        # content token is the pre-terminal state, whose bitmask already
        # permits only stop tokens (see ``build_bounded_grammar_table``'s
        # BFS) — exactly right for masking a draft step that would only
        # ever propose a stop from there, so there is nothing to gain by
        # chasing the table into ``terminal_states`` through this path.
        if gs.bounded is not None:
            _advance_bounded_binding(gs.bounded, token)

    # ── Grammar-aware DRAFTING — see xgrammar_draft_walk's module docstring
    # for the full rationale (why, scope, and "not capture-safe yet") before
    # calling any of the three thin delegations below.

    def start_draft_walk(self, request: Request) -> DraftGrammarWalk | None:
        return _start_draft_walk(request)

    def draft_step_bitmask(self, walk: DraftGrammarWalk) -> torch.Tensor:
        return _draft_step_bitmask(walk, self.vocab_size)

    def advance_draft_walk(self, walk: DraftGrammarWalk, token: int) -> None:
        _advance_draft_walk(walk, token)

    # ── MTP verify-pass masking (grammar-aware speculation) ──────────
    #
    # The verify pass samples the (K+1, B, V) per-position logits OUTSIDE the
    # captured forward (see mtp_verify.run_verify_step), so the grammar mask is
    # applied here, before verify_and_accept. Position p of a constrained row is
    # masked by the matcher state advanced through that row's drafts[0:p]
    # (exactly the context the model conditioned on at that position); after
    # filling all positions the matcher is rolled back to its base state — the
    # post-verify per-committed-token ``accept_token`` loop re-advances by the
    # ACTUALLY accepted prefix. This makes greedy/stochastic accept grammar-
    # correct AND keeps speculation: any draft the (unconstrained) drafter
    # proposed that is grammar-valid is accepted; an invalid one is rejected
    # down to the masked correction token.
    #
    # NOTE: this remains the ONLY grammar-aware step today for a drafter that
    # has not yet been integrated with DraftGrammarWalk above (all three
    # shipped drafters, as of this comment) — an unconstrained proposal is
    # rejected here rather than never made. DraftGrammarWalk makes the
    # proposal itself constrained; it does not change this function's own
    # correctness, only (once a drafter is wired to it) how often this
    # function's rejection path fires.

    def mask_verify_logits(
        self,
        bucket_logits: torch.Tensor,  # (K+1, B, W) fp32/bf16, masked in place
        bucket_reqs: Sequence[Request],  # one per column, with .grammar_state
        drafts_per_row: Sequence[Sequence[int]],  # per-column draft token ids
        *,
        window: VocabWindow | None = None,
    ) -> torch.Tensor:
        if bucket_logits.dim() != 3:
            raise RuntimeError(
                f"mask_verify_logits: expected (K+1, B, W); got {tuple(bucket_logits.shape)}"
            )
        kp1, b, v = bucket_logits.shape
        # The matcher fills a PACKED int32 bitmask over the whole vocabulary,
        # BITMASK_WORD tokens per word. A vocab-parallel window is a slice of
        # that bitmask, and it is a slice only on a word boundary — otherwise
        # a word straddles two ranks and neither can address its own bits.
        # Refuse LOUD rather than mask the wrong tokens; the sharded gate
        # screens for this so the raise is unreachable in service.
        if window is not None and not window.is_bitmask_aligned:
            raise RuntimeError(
                f"mask_verify_logits: vocab window [{window.start}, {window.stop}) "
                f"is not {BITMASK_WORD}-token aligned, so the packed bitmask does "
                f"not slice on a word boundary and this rank cannot mask its own shard."
            )
        word_lo = 0 if window is None else window.bitmask_word_start
        flat_rows = kp1 * b
        device = bucket_logits.device
        host_idx_list: list[int] = []
        # First pass: per constrained row, advance the matcher through its
        # drafts position-by-position, filling each position's bitmask row, then
        # roll the matcher back to base. Flat row index matches the
        # ``view(K+1*B, V)`` convention: row = p * B + col.
        any_constrained = any(getattr(r, "grammar_state", None) is not None for r in bucket_reqs)
        if not any_constrained:
            return bucket_logits
        self._ensure_buffers(flat_rows, device)
        host = self._host_bitmask
        for col, req in enumerate(bucket_reqs):
            gs = getattr(req, "grammar_state", None)
            if gs is None or gs.matcher.is_terminated():
                continue
            matcher = gs.matcher
            drafts = drafts_per_row[col] if col < len(drafts_per_row) else ()
            advanced = 0
            for p in range(kp1):
                row = p * b + col
                matcher.fill_next_token_bitmask(host, row)
                host_idx_list.append(row)
                if p == kp1 - 1 or p >= len(drafts):
                    break
                d = int(drafts[p])
                # Advance to condition the next position on this draft. A draft
                # the unconstrained drafter proposed may be grammar-invalid;
                # then we cannot advance further — the verify will reject it at
                # this position anyway (its token is masked out), so stop.
                if matcher.is_terminated() or d in matcher.stop_token_ids:
                    break
                if not matcher.accept_token(d):
                    break
                advanced += 1
            if advanced:
                matcher.rollback(advanced)
        if not host_idx_list:
            return bucket_logits
        assert self._device_bitmask is not None and self._device_indices is not None
        device_bm = self._device_bitmask
        device_bm[:flat_rows].copy_(host[:flat_rows], non_blocking=True)
        # The window's words, made contiguous: the masking kernel reads the
        # bitmask row-major, and a column slice of the full-vocab buffer
        # keeps the full row stride. Word-scale, not vocab-scale.
        shard_bm = (
            device_bm[:flat_rows]
            if window is None
            else device_bm[:flat_rows, word_lo : word_lo + v // BITMASK_WORD].contiguous()
        )
        n = len(host_idx_list)
        host_idx = self._host_indices[:n]
        host_idx.copy_(torch.tensor(host_idx_list, dtype=torch.int32, device="cpu"))
        device_idx = self._device_indices[:n]
        device_idx.copy_(host_idx, non_blocking=True)
        # ``reshape``, not ``view``: a vocab-parallel caller hands this a
        # SLICE of its shard (a short final shard trimmed of its padding
        # columns), which is a strided view rather than a contiguous tensor.
        flat = bucket_logits.reshape(flat_rows, v)
        xg.apply_token_bitmask_inplace(flat, shard_bm, indices=device_idx)
        if flat.data_ptr() != bucket_logits.data_ptr():
            # ``reshape`` fell back to a COPY for this layout. The kernel
            # writes IN PLACE, so without this the mask lands on a temporary
            # and the row is drawn unconstrained — a constraint dropped with
            # nothing to notice, which is the one outcome this path may not
            # have.
            bucket_logits.copy_(flat.view(kp1, b, v))
        return bucket_logits

    def constrains_verify_slate(self, requests: Sequence[Request]) -> bool:
        """Whether any row carries a live matcher.

        The SAME condition :meth:`mask_verify_logits` short-circuits on, so
        the answer cannot disagree with what the mask would do. A row that
        merely REQUIRES a grammar whose matcher is not built yet writes
        nothing this step.
        """
        return any(getattr(r, "grammar_state", None) is not None for r in requests)

    def verify_slate_reads_drafts(self, requests: Sequence[Request]) -> bool:
        """True iff a row carries a grammar: its matcher advances through
        the drafts."""
        return any(getattr(r, "grammar_state", None) is not None for r in requests)

    def apply_to_verify_slate(
        self,
        logits: torch.Tensor,  # (K+1, B, W) — masked in place
        requests: Sequence[Request],
        drafts_per_row: Sequence[Sequence[int]],
        *,
        window: VocabWindow | None = None,
    ) -> None:
        """The chain's verify-slate form of the grammar mask.

        Per-position by construction: :meth:`mask_verify_logits` advances
        each constrained row's matcher through its own drafts, so position
        ``p`` is masked by the state the model actually conditioned on. The
        matcher walk is CPU work every rank already does identically, so a
        ``window`` narrows only the device-side mask application.
        """
        self.mask_verify_logits(logits, requests, drafts_per_row, window=window)

    def cache_stats(self) -> dict:
        """Return cache hit/miss counts and bitmask buffer dimensions as a dict."""
        return {
            "hits": self._stats.hits,
            "misses": self._stats.misses,
            "size": len(self._compiled_cache),
            "max_size": self._cache_size,
            "disk_cache_dir": (str(self._disk_cache_dir) if self._disk_cache_dir else None),
            "bitmask_max_rows": self._max_rows,
            "bitmask_words_per_row": self._bitmask_words,
            "bitmask_device": (str(self._device) if self._device else None),
        }
# ---- xgrammar_processor_spmd.py ----
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""``XGrammarLogitsProcessor``'s SPMD synchronous-compile mixin.

Under SPMD every rank samples off its own ``_MirroredRequest``, a
rank-local object distinct from the engine ``Request`` (which exists only
on rank 0). Each mirror therefore needs its OWN matcher, built from the
grammar spec carried once in the AdmitRow.

This is ADDITIVE to ``XGrammarLogitsProcessor.attach``, never an
alternative to it: the two build matchers for two different objects, and
neither is gated on a routing flag. The per-step SPMD loop is synchronous,
so compilation must be too -- ``get_or_compile_sync`` shares the in-memory
LRU with the async path (identical grammar -> byte-identical automaton on
every rank, so masks + samples stay rank-symmetric).

Split out of ``xgrammar_processor.py`` along this real seam (the SPMD
sync-compile surface is self-contained and only reaches ``self`` state the
main class already owns) to stay under the file-size ceiling; re-exported
from there so imports don't churn.
"""

from __future__ import annotations

import logging

import xgrammar as xg

from arbi_serve.engine.request import ResponseFormat
from arbi_serve.sampler.tool_grammar_fallback import compile_tool_grammar_sync
from arbi_serve.sampler.xgrammar_bounded_table import BoundedGrammarBinding
from arbi_serve.sampler.xgrammar_bounded_table import bounded_table_for as _bounded_table_for
from arbi_serve.sampler.xgrammar_grammar_source import disk_payload_to_rf as _disk_payload_to_rf

logger = logging.getLogger("arbi_serve.sampler.xgrammar")


class _XGrammarSpmdSyncMixin:
    """Synchronous, rank-local grammar compile + bounded-table build."""

    def get_or_compile_sync(
        self, rf: ResponseFormat, *, check_compiler: bool = True
    ) -> xg.CompiledGrammar:
        """Synchronous cached compile (no event loop, no disk). For SPMD."""
        key = self._cache_key(rf)
        cached = self._cache_get(key)
        if cached is not None:
            self._stats.hits += 1
            return cached
        self._stats.misses += 1
        compiled = (
            self._compile_sync(rf)
            if check_compiler
            else self._compile_sync(rf, check_compiler=False)
        )
        self._cache_put(key, compiled)
        return compiled

    def build_grammar_state(self, payload: dict):
        """Build a mirror's per-rank matcher from a broadcast grammar payload.
        The ONE builder of ``_MirroredRequest.grammar_state``.

        Returns ``None`` on a compile failure rather than diverging — every
        rank degrades identically since the payload is the same everywhere.
        The caller must then clear the mirror's ``grammar_required``.

        Builds ``bounded`` too, like ``_install_matcher`` does for a real
        ``Request``: the shared cache is keyed by content hash, so every rank
        resolves the same table. Without this a mirror's ``bounded`` is
        always ``None`` and captured grammar-masked drafting degrades to the
        plain stochastic pool on every rank -- safe, just not accelerated.
        """
        from arbi_serve.sampler.xgrammar_processor import _PerRequestGrammar

        # A failure degrades by the same pure ladder on every rank
        # (tool_grammar_fallback), so all ranks agree on the grammar.
        built = compile_tool_grammar_sync(self, _disk_payload_to_rf(payload))
        if built is None:
            return None
        compiled, rf = built
        key = self._cache_key(rf)
        pair = _bounded_table_for(
            self._bounded_table_cache, key, compiled, self.vocab_size, self._device
        )
        return _PerRequestGrammar(
            matcher=xg.GrammarMatcher(compiled),
            vocab_size=self.vocab_size,
            cache_key=key,
            bounded=(
                BoundedGrammarBinding(table=pair[0], device_table=pair[1])
                if pair is not None
                else None
            ),
        )
