Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

416 KB
Raw Blame
//! Per-batch dispatcher: decode NATS JetStream messages into WorkItems,
//! fan out to the backend over IPC, publish results, and
//! ACK/NAK each message.
//!
//!   fetch -> decode + validate (subject, reply_subject, model_id)
//!         -> group by model_id
//!         -> per model (concurrent):
//!              EnsureModelReady (still loading -> park the group in its own task)
//!              then, capped by batch_semaphore:
//!              apply per-model batch_budget (overflow -> NAK fast)
//!              fan out encode/score/extract concurrently:
//!                 resolve payload -> IPC ProcessXxxBatch -> publish + ACK
//!                 on IPC failure -> NAK group with transient delay

use std::collections::{BTreeMap, HashMap, HashSet};
use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::sync::OnceLock;
use std::time::{Duration, Instant};

use async_nats::jetstream::Message;
use futures_util::future::join_all;
use rmpv::Value as MsgValue;
use thiserror::Error;
use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore};
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};

use crate::backend::{AdapterWorkerPool, BackendError, SharedBackend};
use crate::batch_cancel::{BatchCancelState, RequestCancelState};
use crate::config_subscriber::ConfigApplyState;
use crate::delivery::Delivery;
use crate::ipc_client::IpcError;
use crate::ipc_types::{
    BatchOutcome, BatchedF16MultivectorOutput, Disposition, EncodeBatchItem, ExtractBatchItem,
    GenerateEvent, ItemOutcome, ModelDescriptor, PreparedAudioPcm16, PreparedTokens,
    ProcessEncodeBatchRequest, ProcessExtractBatchRequest, ProcessGenerateRequest,
    ProcessScoreBatchRequest, ReadinessState, RunBatchRequest, ScoreBatchItem,
};
use crate::latency::LatencyTracker;
use crate::log_util::ErrChain;
use crate::observability::metrics::SchedulerRequestBatchObservation;
use crate::payload_store::{PayloadError, PayloadStore};
use crate::pool_admission::PoolAdmissionGate;
use crate::prep::media::{validate_item_media, MediaValidationError};
use crate::publisher::{
    shape_and_build_work_result, shape_batched_f16_multivector_outcome, should_publish,
    PublishResultContext, Timings, WorkPublisher,
};
use crate::runtime_state::{RuntimeGauge, RuntimeState};
use crate::scheduler::{
    lora_from_options, HasCost, LoraKey, Op as SchedOp, ProductionScheduler,
    ProductionSchedulerRegistry, SchedulerItem, SchedulerMeta,
};
use crate::shutdown::Shutdown;
use crate::subject::{
    execution_authority_model_matches, extract_model_id, is_worker_direct_work_subject,
    requires_execution_authority_v1, requires_numerical_admission_v1,
};
use crate::tokenize::TokenizerRegistry;
use crate::work_deadline::{
    apparent_age_ms, unix_now_s, ClockSkewSignal, DeadlineStatus, WorkDeadlinePolicy,
    CLOCK_SKEW_WARNINGS, EXPIRED_DROP_WARNINGS, EXPIRED_EXECUTE_WARNINGS,
    REJECTED_DEADLINE_WARNINGS,
};
use crate::work_types::WorkItem;
use half::f16;

const MODEL_LOADING_ERROR_CODE: &str = "MODEL_LOADING";
/// Terminal, non-retryable model-load failure. Emitted on the `WorkResult`
/// (encode/score/extract) or the generation terminal chunk when the Python
/// executor reports [`ReadinessState::Failed`] (registry holds a PERMANENT
/// `LoadFailure`). The gateway maps this code to a typed HTTP 502 via
/// `build_model_load_failed_response` (unary/batch path) — the fast-path twin
/// of the `run_batch` mapping. Kept byte-identical to the gateway
/// constant `sie_gateway::handlers::proxy::MODEL_LOAD_FAILED_ERROR_CODE` and
/// the Python `ErrorCode.MODEL_LOAD_FAILED`.
const MODEL_LOAD_FAILED_ERROR_CODE: &str = "MODEL_LOAD_FAILED";
const INVALID_INPUT_ERROR_CODE: &str = "INVALID_INPUT";
/// A remote profile's upstream cannot serve now; retryable, like the single
/// server's `QUEUE_FULL` for a busy or unreachable upstream.
const QUEUE_FULL_ERROR_CODE: &str = "QUEUE_FULL";
/// The code of a numerical admission refusal, as the backend's fence and the
/// single server's bridge refusal report it.
const INFERENCE_ERROR_CODE: &str = "INFERENCE_ERROR";
const NUMERICAL_ADMISSION_RETRY_AFTER_S: u32 = 1;
const FALLBACK_REFUSAL_MESSAGE: &str = "The remote profile cannot serve this request now";
/// Operation of a work item that only asks the worker to load its model.
const LOAD_OPERATION: &str = "load";
const PAYLOAD_TOO_LARGE_ERROR_CODE: &str = "PAYLOAD_TOO_LARGE";
const PAYLOAD_ERROR_CODE: &str = "payload_error";
const PAYLOAD_RESOLVE_ERROR_MESSAGE: &str = "failed to resolve item";
const PAYLOAD_TOO_LARGE_MESSAGE: &str = "referenced payload exceeds the worker size limit";

#[derive(Debug, Error)]
#[error("{code}: {message}")]
pub struct GenerateDispatchError {
    pub code: String,
    pub message: String,
}

impl GenerateDispatchError {
    fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
        }
    }
}

#[derive(Debug, Clone, Default)]
enum LocalGeneratePhase {
    #[default]
    Streaming,
    AwaitingChunkAck,
    AwaitingRetryAck {
        reason: String,
    },
    Complete,
    Retry {
        reason: String,
    },
}

#[derive(Default)]
struct LocalGenerateState {
    attempt_id: Option<String>,
    next_seq: u32,
    phase: LocalGeneratePhase,
}

impl LocalGenerateState {
    fn observe_ack(&mut self) -> Result<(), String> {
        self.phase = match &self.phase {
            LocalGeneratePhase::AwaitingChunkAck => LocalGeneratePhase::Complete,
            LocalGeneratePhase::AwaitingRetryAck { reason } => LocalGeneratePhase::Retry {
                reason: reason.clone(),
            },
            phase => {
                return Err(format!(
                    "generation ACK violated publication/settlement ordering in phase {phase:?}"
                ));
            }
        };
        Ok(())
    }

    fn observe_transport_nak(&mut self) -> Result<(), String> {
        if !matches!(self.phase, LocalGeneratePhase::Streaming) || self.next_seq != 0 {
            return Err(format!(
                "generation NAK violated publication/settlement ordering in phase {:?}",
                self.phase
            ));
        }
        self.phase = LocalGeneratePhase::Retry {
            reason: "backend_redelivery".to_string(),
        };
        Ok(())
    }

    fn observe_progress(&self) -> Result<(), String> {
        if matches!(self.phase, LocalGeneratePhase::Streaming) {
            Ok(())
        } else {
            Err(format!(
                "generation progress violated terminal/settlement ordering in phase {:?}",
                self.phase
            ))
        }
    }
}

#[derive(Debug)]
enum LocalGeneratePublication {
    Chunk(Vec<u8>),
    Retry,
}

struct InflightBatchGuard {
    runtime_state: Arc<RuntimeState>,
}

impl InflightBatchGuard {
    fn enter(runtime_state: Arc<RuntimeState>) -> Self {
        runtime_state.inflight_batches.inc();
        Self { runtime_state }
    }
}

impl Drop for InflightBatchGuard {
    fn drop(&mut self) {
        decrement_gauge(&self.runtime_state.inflight_batches, 1);
    }
}

fn payload_error_contract(error: &PayloadError) -> (&'static str, &'static str) {
    match error {
        PayloadError::TooLarge { .. } => (PAYLOAD_TOO_LARGE_ERROR_CODE, PAYLOAD_TOO_LARGE_MESSAGE),
        _ => (PAYLOAD_ERROR_CODE, PAYLOAD_RESOLVE_ERROR_MESSAGE),
    }
}

type ResolvedWorkItem = (WorkItem, Delivery, f64, Option<String>);

#[derive(Debug, Clone, Copy)]
struct BatchedF16MultivectorSlice<'a> {
    values_f16: &'a [f16],
    num_tokens: u32,
    token_dims: u32,
}

#[derive(serde::Serialize)]
struct GenerateTerminalErrorChunk<'a> {
    kind: &'static str,
    request_id: &'a str,
    attempt_id: String,
    seq: u32,
    text_delta: &'static str,
    done: bool,
    finish_reason: &'static str,
    error: GenerateTerminalError<'a>,
}

#[derive(serde::Serialize)]
struct GenerateTerminalError<'a> {
    code: &'a str,
    message: &'a str,
}

#[derive(Debug, Clone)]
struct DeliveryContext {
    subject: String,
    stream: String,
    consumer: String,
    stream_sequence: u64,
    consumer_sequence: u64,
    delivered: i64,
    pending: u64,
    has_metadata: bool,
}

impl DeliveryContext {
    fn from_message(msg: &Message) -> Self {
        match msg.info() {
            Ok(info) => Self {
                subject: msg.subject.to_string(),
                stream: info.stream.to_string(),
                consumer: info.consumer.to_string(),
                stream_sequence: info.stream_sequence,
                consumer_sequence: info.consumer_sequence,
                delivered: info.delivered,
                pending: info.pending,
                has_metadata: true,
            },
            Err(_) => Self {
                subject: msg.subject.to_string(),
                stream: String::new(),
                consumer: String::new(),
                stream_sequence: 0,
                consumer_sequence: 0,
                delivered: 0,
                pending: 0,
                has_metadata: false,
            },
        }
    }
}

#[derive(Debug, Clone)]
struct GenerateDeliveryLogContext {
    work_item_id: String,
    request_id: String,
    model_id: String,
    reply_subject: String,
    delivery: DeliveryContext,
}

/// Base retry delay in milliseconds. Mirrors Python's `_NAK_DELAY_S`
/// (default 5 000 ms, overridable via `SIE_NAK_DELAY_S`). Used for:
///
/// * `retry_later` readiness (unknown error path)
/// * generic transient IPC / executor failures
///
/// Local model-loading waits use JetStream progress ACKs instead of NAKs.
pub(crate) fn base_nak_delay_ms() -> u64 {
    std::env::var("SIE_NAK_DELAY_S")
        .ok()
        .and_then(|s| s.parse::<f64>().ok())
        .filter(|v| *v > 0.0)
        .map(|s| (s * 1000.0) as u64)
        .unwrap_or(5_000)
}

/// NAK delay on fair-dispatch overflow — we want fast redelivery because
/// the item is otherwise ready, we're just flow-controlling. Matches
/// Python's hardcoded 0.1 s overflow NAK.
const NAK_DELAY_OVERFLOW_MS: u64 = 100;

/// NAK delay used when the backend reports `BackendError::Draining`. The
/// local backend is going away — another worker should pick the message
/// up promptly, so we use a short delay (100ms) instead of the generic
/// `base_nak_delay_ms` (~5s) that is intended for transient retryable
/// errors. Holding the message back longer just starves redelivery.
const NAK_DELAY_DRAINING_MS: u64 = 100;
const READINESS_PROGRESS_ACK_WAIT_FRACTION: u64 = 2;
const MODEL_READINESS_POLL_INTERVAL: Duration = Duration::from_secs(1);
const MODEL_READINESS_PROGRESS_INTERVAL: Duration =
    Duration::from_secs(crate::nats_consumer::ACK_WAIT_SECS / 3);

fn duration_millis(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

fn phase_elapsed_ms(started: Instant, finished: Instant) -> u64 {
    duration_millis(finished.saturating_duration_since(started))
}

struct ModelReadinessWait {
    deadline: tokio::time::Instant,
    next_progress: tokio::time::Instant,
}

impl ModelReadinessWait {
    fn new(deadline: tokio::time::Instant) -> Self {
        Self {
            deadline,
            next_progress: tokio::time::Instant::now(),
        }
    }
}

/// Pick the right NAK delay for a given backend error — `Draining` is
/// fast because we want redelivery to another worker, everything else
/// uses the shared base delay.
pub(crate) fn nak_delay_for_backend_error(err: &BackendError) -> u64 {
    match err {
        BackendError::Draining => NAK_DELAY_DRAINING_MS,
        _ => base_nak_delay_ms(),
    }
}

fn readiness_progress_delay_ms(state: &ReadinessState, base_delay_ms: u64) -> Option<u64> {
    let max_delay_ms = crate::nats_consumer::ACK_WAIT_SECS
        .saturating_mul(1000)
        .checked_div(READINESS_PROGRESS_ACK_WAIT_FRACTION)
        .unwrap_or(1)
        .max(1);
    match state {
        ReadinessState::LoadingStarted => Some(base_delay_ms.min(max_delay_ms)),
        ReadinessState::LoadingInProgress => {
            Some(base_delay_ms.saturating_mul(2).min(max_delay_ms))
        }
        // `Failed` is terminal: no progress delay — the caller dead-letters
        // the group instead of re-driving `EnsureModelReady`.
        ReadinessState::Ready | ReadinessState::RetryLater | ReadinessState::Failed => None,
    }
}

/// Reply subjects must live under `_INBOX.` (NATS conventions). Non-empty
/// subjects outside this prefix are rejected as a crude anti-injection
/// check — a malicious producer could otherwise aim results at an
/// arbitrary subject. Empty reply_subjects are allowed (fire-and-forget).
const INBOX_PREFIX: &str = "_INBOX.";

fn msg_value_key_eq(key: &MsgValue, expected: &str) -> bool {
    match key {
        MsgValue::String(s) => s.as_str() == Some(expected),
        MsgValue::Binary(b) => std::str::from_utf8(b).ok() == Some(expected),
        _ => false,
    }
}

fn msg_map_get<'a>(value: &'a MsgValue, key: &str) -> Option<&'a MsgValue> {
    let MsgValue::Map(entries) = value else {
        return None;
    };
    entries
        .iter()
        .find(|(k, _)| msg_value_key_eq(k, key))
        .map(|(_, v)| v)
}

fn msg_as_str(value: &MsgValue) -> Option<&str> {
    match value {
        MsgValue::String(s) => s.as_str(),
        MsgValue::Binary(b) => std::str::from_utf8(b).ok(),
        _ => None,
    }
}

/// Extract the optional caller id from a resolved encode item. This runs after
/// payload-store fetch, so inline and offloaded inputs preserve the same echo
/// contract without retaining or cloning the full resolved payload.
fn caller_item_id_from_value(value: &MsgValue) -> Option<String> {
    msg_map_get(value, "id")
        .and_then(msg_as_str)
        .map(str::to_string)
}

/// True if `reply_subject` is acceptable for use on a `WorkItem`.
/// Empty is allowed (fire-and-forget). Non-empty subjects must start
/// with `_INBOX.` so malicious producers can't redirect results.
/// The first `Nats-` header on a work delivery other than `Nats-Msg-Id`.
///
/// The gateway publishes work with at most `Nats-Msg-Id`. The NATS server adds
/// other `Nats-` headers when it copies stored messages into a work stream on
/// a user's behalf, past that user's publish permissions: a stream republish
/// adds `Nats-Stream`, and a stream source adds `Nats-Stream-Source`.
pub fn unexpected_work_header(headers: Option<&async_nats::HeaderMap>) -> Option<String> {
    headers?.iter().find_map(|(name, _)| {
        let name: &str = name.as_ref();
        let nats_header = name
            .get(..5)
            .is_some_and(|prefix| prefix.eq_ignore_ascii_case("nats-"));
        (nats_header && !name.eq_ignore_ascii_case("Nats-Msg-Id")).then(|| name.to_string())
    })
}

pub(crate) fn reply_subject_is_safe(reply_subject: &str) -> bool {
    reply_subject.is_empty() || reply_subject.starts_with(INBOX_PREFIX)
}

/// Bind each outcome (in order) to a `resolved` index by `work_item_id`,
/// consuming duplicate ids in FIFO arrival order. Returns a vector the
/// same length as `outcomes`, where `Some(idx)` means "outcome[i]
/// handles resolved[idx]" and `None` means "ghost outcome — no matching
/// work item remaining to consume".
///
/// Factored out of [`Dispatcher::apply_outcomes`] so the bookkeeping is
/// unit-testable without mocking JetStream `Message`s.
pub(crate) fn resolve_outcome_indices<'a, I>(
    resolved_wiids: &[&'a str],
    outcomes_wiids: I,
) -> Vec<Option<usize>>
where
    I: IntoIterator<Item = &'a str>,
{
    use std::collections::HashMap;

    let mut by_wiid: HashMap<&str, Vec<usize>> = HashMap::with_capacity(resolved_wiids.len());
    for (idx, wiid) in resolved_wiids.iter().enumerate() {
        by_wiid.entry(*wiid).or_default().push(idx);
    }
    // Reverse so `pop()` yields earliest-inserted index first.
    for v in by_wiid.values_mut() {
        v.reverse();
    }
    outcomes_wiids
        .into_iter()
        .map(|wiid| by_wiid.get_mut(wiid).and_then(|v| v.pop()))
        .collect()
}

fn index_batched_f16_multivectors<'a>(
    batches: &'a [BatchedF16MultivectorOutput],
) -> HashMap<&'a str, Result<BatchedF16MultivectorSlice<'a>, String>> {
    let item_count = batches.iter().map(|batch| batch.items.len()).sum();
    let mut indexed = HashMap::with_capacity(item_count);
    for batch in batches {
        for item in &batch.items {
            let entry = batched_f16_multivector_slice(batch, item);
            if indexed.insert(item.work_item_id.as_str(), entry).is_some() {
                indexed.insert(
                    item.work_item_id.as_str(),
                    Err("duplicate batched f16 multivector work_item_id".to_string()),
                );
            }
        }
    }
    indexed
}

fn batched_f16_multivector_slice<'a>(
    batch: &'a BatchedF16MultivectorOutput,
    item: &'a crate::ipc_types::BatchedF16MultivectorItem,
) -> Result<BatchedF16MultivectorSlice<'a>, String> {
    let byte_offset = usize::try_from(item.byte_offset)
        .map_err(|_| "batched f16 multivector offset exceeds platform range".to_string())?;
    let byte_len = usize::try_from(item.byte_len)
        .map_err(|_| "batched f16 multivector length exceeds platform range".to_string())?;
    if !byte_offset.is_multiple_of(std::mem::size_of::<f16>())
        || !byte_len.is_multiple_of(std::mem::size_of::<f16>())
    {
        return Err("batched f16 multivector range is not f16-aligned".to_string());
    }
    let end = byte_offset
        .checked_add(byte_len)
        .ok_or_else(|| "batched f16 multivector byte range overflow".to_string())?;
    let value_offset = byte_offset / std::mem::size_of::<f16>();
    let value_end = end / std::mem::size_of::<f16>();
    let values_f16 = batch
        .values_f16
        .0
        .get(value_offset..value_end)
        .ok_or_else(|| "batched f16 multivector byte range exceeds buffer".to_string())?;
    Ok(BatchedF16MultivectorSlice {
        values_f16,
        num_tokens: item.num_tokens,
        token_dims: item.token_dims,
    })
}

fn batched_f16_multivector_error_outcome(outcome: &ItemOutcome, message: &str) -> ItemOutcome {
    ItemOutcome {
        disposition: Disposition::PublishErrorAndAck,
        result_msgpack: Vec::new(),
        error: Some(format!("batched f16 multivector: {message}")),
        error_code: Some("raw_output_shape_error".to_string()),
        raw_output: None,
        ..outcome.clone()
    }
}

/// Fallback per-model batch budget when the Python side doesn't report
/// one on EnsureModelReady (for example, while the model is not loaded).
/// Reads `SIE_NATS_FETCH_BUDGET` (default
/// 64), the same env var that the pull loop uses for its per-fetch
/// credit — so operators have one knob that means "how many messages a
/// worker should grab at a time" across both layers (matches Python's
/// historical `_DEFAULT_BATCH_BUDGET`).
fn default_batch_budget() -> u32 {
    std::env::var("SIE_NATS_FETCH_BUDGET")
        .ok()
        .and_then(|s| s.parse::<u32>().ok())
        .unwrap_or(64)
}

/// Cap on concurrent model-group processing per worker. Matches Python's
/// `_MAX_CONCURRENT_BATCHES = 4` — enough to keep the IPC pipeline full
/// without risking ACK-timeout storms under backpressure. Override with
/// `SIE_MAX_CONCURRENT_BATCHES`.
///
/// Exposed publicly so `main.rs` can use the same value as the fallback
/// for `SIE_IPC_POOL_SIZE` when it's unset — the IPC pool should never
/// be smaller than the dispatcher's concurrency cap or it becomes the
/// binding constraint.
pub fn default_max_concurrent_batches() -> usize {
    std::env::var("SIE_MAX_CONCURRENT_BATCHES")
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
        .filter(|&n| n > 0)
        .unwrap_or(4)
}

/// Process-wide cap on concurrent CPU audio decodes. One worst-case decode
/// can transiently hold about 230 MiB, so the conservative default is one.
fn default_audio_prep_permits() -> usize {
    std::env::var("SIE_AUDIO_PREP_PERMITS")
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
        .filter(|&n| n > 0)
        .unwrap_or(1)
}

#[derive(Debug, Error)]
pub enum DispatchError {
    /// Backend-layer error — IPC transport, native inference failure,
    /// or backend-level drain. Wraps [`BackendError`].
    #[error("backend: {0}")]
    Backend(#[from] BackendError),
    #[error("payload: {0}")]
    Payload(#[from] PayloadError),
    #[error("publish: {0}")]
    Publish(#[from] crate::publisher::PublishError),
    #[error("ipc: {0}")]
    Ipc(#[from] IpcError),
    #[error("nats ack: {0}")]
    Ack(String),
}

/// A JetStream message plus an optional pull-loop admission permit — the
/// pull-loop intake type consumed by [`Dispatcher::handle_batch`].
///
/// The permit is intentionally carried with the message until the request
/// settles. This makes the sidecar's queue intake behave like the Python
/// worker queue: a pulled item occupies capacity until the scheduler/backend
/// path has actually finished with it, not merely until it was enqueued.
/// At decode time `handle_batch` moves the permit into the item's
/// [`Delivery`], which owns it for the rest of the pipeline.
pub(crate) struct QueuedMessage {
    msg: Message,
    admission_permit: Option<OwnedSemaphorePermit>,
}

impl QueuedMessage {
    #[must_use]
    pub(crate) fn new(msg: Message, admission_permit: Option<OwnedSemaphorePermit>) -> Self {
        Self {
            msg,
            admission_permit,
        }
    }

    fn into_parts(self) -> (Message, Option<OwnedSemaphorePermit>) {
        (self.msg, self.admission_permit)
    }
}

impl From<Message> for QueuedMessage {
    fn from(msg: Message) -> Self {
        Self::new(msg, None)
    }
}

impl std::ops::Deref for QueuedMessage {
    type Target = Message;

    fn deref(&self) -> &Self::Target {
        &self.msg
    }
}

/// Pre-bundled handles the dispatcher needs — avoids a giant fn signature.
pub struct Dispatcher {
    /// Inference backend — typically a [`crate::backend::BackendRouter`]
    /// composing a native backend and/or [`crate::backend::PythonIpcBackend`].
    /// Held behind a trait object so the dispatcher doesn't care which
    /// backend runs which model.
    pub backend: SharedBackend,
    /// Adapter worker pool used for streaming generation. The batch backend
    /// trait remains outcome-oriented; generation is event-streaming, so
    /// the dispatcher asks the pool to pick the concrete child socket.
    pub worker_pool: Arc<AdapterWorkerPool>,
    pub payload_store: Arc<dyn PayloadStore>,
    /// NATS result publisher. `None` in local-ingest mode (P2.10, §4.6)
    /// where results ride each [`Delivery::Local`]'s event channel instead
    /// — the invariant "a [`Delivery::Nats`] item implies `Some`" holds by
    /// construction (`run()` wires both NATS and the publisher; `run_local()`
    /// wires neither).
    pub publisher: Option<Arc<WorkPublisher>>,
    /// Stable worker id stamped on locally-delivered `WorkResult`s. Same
    /// value the NATS `WorkPublisher` stamps on its results.
    pub worker_id: String,
    pub runtime_state: Arc<RuntimeState>,
    /// Rolling latency tracker shared with the pull loop. On every
    /// successful publish we record `inference_ms + postprocess_ms`
    /// (default) or `queue_ms + inference_ms + postprocess_ms` when
    /// `SIE_PULL_QUANTUM_INCLUDE_QUEUE_MS=1`. See
    /// `crate::pull_quantum_includes_queue_ms` for the rationale.
    pub latency_tracker: Arc<Mutex<LatencyTracker>>,
    /// Caps concurrent model-group processing. Acquired once per group
    /// after its model is ready, held for the lifetime of the
    /// encode/score/extract fan-out.
    pub batch_semaphore: Arc<Semaphore>,
    /// Caps queue items parked while their model loads, at one fetch
    /// (`SIE_NATS_FETCH_BUDGET`). A parked item gives its pull-loop admission
    /// permit back and holds one of these instead, so a cold model cannot
    /// stop the pull loop admitting work for models that are already loaded.
    parked_item_permits: Arc<Semaphore>,
    /// Groups parked while their model loads, joined at shutdown.
    parked_group_handles: Arc<std::sync::Mutex<Vec<JoinHandle<()>>>>,
    /// Bounds the largest CPU allocation path independently of batch fan-out.
    /// One 12-minute 48 kHz decode can transiently hold about 230 MiB.
    audio_prep_semaphore: Arc<Semaphore>,
    /// Rust-side tokenizer registry. Always present; an empty
    /// registry means "no model has registered a tokeniser yet" and
    /// every `get(model_id)` returns `None`, which collapses the
    /// dispatcher to the Python-tokenise fallback path.
    ///
    /// Tokenisers are ingested lazily on the first
    /// [`crate::backend::InferenceBackend::ensure_model_ready`]
    /// response that carries a populated [`crate::ipc_types::ModelDescriptor`] for the
    /// model — see `Dispatcher::handle_model_group`.
    pub tokenizer_registry: Arc<TokenizerRegistry>,
    /// Optional Rust-side scheduler registry. When `Some`, every model
    /// is routed through the Rust scheduler
    /// (batch formation + adaptive control) with flushed batches
    /// shipped to the backend via `run_batch`. When `None`, the
    /// dispatcher falls back to the op-scoped `process_*_batch`
    /// path for every request — this mode is kept for unit tests
    /// that don't need the scheduler plumbing.
    ///
    /// The [`Shutdown`] signal below is observed by the per-model
    /// drain loops which are spawned lazily on first traffic by
    /// `Dispatcher::resolve_scheduler`.
    pub scheduler_registry: Option<Arc<ProductionSchedulerRegistry>>,
    /// Shutdown signal the per-model scheduler drain loops observe.
    /// `None` when no [`Self::scheduler_registry`] is configured —
    /// keeps the field inert for the Python-only topology.
    pub shutdown: Option<Arc<Shutdown>>,
    /// Current sidecar-applied bundle config state. Shared with the live config
    /// subscriber/reconciler and NATS health publisher.
    pub config_apply_state: Option<Arc<ConfigApplyState>>,
    /// Optional admission gate for both the physical queue and logical
    /// `admission_pool` labels carried on default-backed work items.
    pub pool_admission: Option<Arc<PoolAdmissionGate>>,
    /// Per-model scheduler drain handles, populated lazily when a
    /// new scheduler is materialised on first traffic. The shutdown
    /// path in `lib.rs` drains this map and awaits every handle so
    /// final-drain windows have a chance to complete.
    pub scheduler_drain_handles: Arc<Mutex<HashMap<String, JoinHandle<()>>>>,
    pub generation_handles: Arc<Mutex<Vec<JoinHandle<()>>>>,
    pub batch_cancel_state: BatchCancelState,
    pub request_cancel_state: RequestCancelState,
    /// Gateway-stamped deadline enforcement, read from env at construction.
    pub work_deadline: WorkDeadlinePolicy,
    /// Dispatch width each model's backend reported on its last
    /// `EnsureModelReady` (`ModelDescriptor::max_concurrent_dispatch`).
    /// Only widths above 1 are kept; see [`Dispatcher::dispatch_width`].
    dispatch_widths: Arc<std::sync::RwLock<HashMap<String, usize>>>,
    /// Each model's scheduler pipeline, shared with its drain loop so a
    /// larger width reported after the loop started can widen it.
    pipelines: Arc<std::sync::Mutex<HashMap<String, Arc<ModelPipeline>>>>,
}

/// In-flight batch permits of one model's scheduler drain loop. The depth
/// only grows: a later `EnsureModelReady` that reports a larger dispatch
/// width adds permits to the running loop.
struct ModelPipeline {
    permits: Arc<Semaphore>,
    depth: std::sync::atomic::AtomicUsize,
}

impl ModelPipeline {
    fn new(depth: usize) -> Self {
        Self {
            permits: Arc::new(Semaphore::new(depth)),
            depth: std::sync::atomic::AtomicUsize::new(depth),
        }
    }

    fn depth(&self) -> usize {
        self.depth.load(Ordering::Acquire)
    }

    /// Raise the depth to `depth`; never lowers it.
    fn grow_to(&self, depth: usize) {
        let previous = self.depth.fetch_max(depth, Ordering::AcqRel);
        if depth > previous {
            self.permits.add_permits(depth - previous);
        }
    }
}

impl Dispatcher {
    /// Keep the dispatch width a model's backend reported on
    /// `EnsureModelReady`. A width above 1 means the adapter fronts an
    /// engine that batches continuously (SGLang): Python runs that many
    /// batches through it at once, so the scheduler sends each extract
    /// item alone and keeps up to that many in flight for the model.
    fn record_dispatch_width(&self, model_id: &str, descriptor: Option<&ModelDescriptor>) {
        let width = descriptor
            .and_then(|d| d.max_concurrent_dispatch)
            .map_or(1, |w| {
                (w as usize).clamp(1, MAX_ENGINE_BATCHED_PIPELINE_DEPTH)
            });
        if self.dispatch_width(model_id) == width {
            return;
        }
        let mut widths = self
            .dispatch_widths
            .write()
            .expect("dispatch width lock poisoned");
        if width > 1 {
            widths.insert(model_id.to_owned(), width);
        } else {
            widths.remove(model_id);
        }
        drop(widths);
        // A drain loop that is already running keeps its semaphore; widen it.
        let pipeline = self
            .pipelines
            .lock()
            .expect("pipeline map lock poisoned")
            .get(model_id)
            .cloned();
        if let Some(pipeline) = pipeline {
            pipeline.grow_to(self.pipeline_depth_for(model_id));
        }
        info!(
            model = %model_id,
            dispatch_width = width,
            "rust-scheduler: backend dispatch width recorded",
        );
    }

    /// The pipeline of `model_id`'s drain loop, created at
    /// [`Self::pipeline_depth_for`] on first use.
    fn model_pipeline(&self, model_id: &str) -> Arc<ModelPipeline> {
        let mut pipelines = self.pipelines.lock().expect("pipeline map lock poisoned");
        Arc::clone(
            pipelines
                .entry(model_id.to_owned())
                .or_insert_with(|| Arc::new(ModelPipeline::new(self.pipeline_depth_for(model_id)))),
        )
    }

    /// Batches the backend runs through `model_id`'s adapter at once
    /// (1 unless its last `EnsureModelReady` reported more).
    pub(crate) fn dispatch_width(&self, model_id: &str) -> usize {
        self.dispatch_widths
            .read()
            .expect("dispatch width lock poisoned")
            .get(model_id)
            .copied()
            .unwrap_or(1)
    }

    /// True when `op` items of `model_id` go to the backend one per
    /// `RunBatch`. For an engine that batches continuously, a shared
    /// `RunBatch` only makes every item wait for the slowest one before any
    /// result is published (the Python worker flags the same items
    /// `runs_alone` on its direct path).
    fn dispatches_items_alone(&self, model_id: &str, op: SchedOp) -> bool {
        op == SchedOp::Extract && self.dispatch_width(model_id) > 1
    }

    /// Scheduler pipeline depth for `model_id`: the configured depth, or the
    /// backend's dispatch width when that is larger.
    fn pipeline_depth_for(&self, model_id: &str) -> usize {
        pipeline_depth().max(self.dispatch_width(model_id))
    }

    fn execution_hash_is_current(&self, wi: &WorkItem) -> bool {
        !wi.bundle_config_hash.is_empty()
            && self.config_apply_state.is_some()
            && unknown_bundle_config_hash(std::iter::once(wi), self.config_apply_state.as_deref())
                .is_none()
    }

    fn execution_authority_is_available(&self, wi: &WorkItem, needs_scheduler: bool) -> bool {
        self.execution_hash_is_current(wi)
            && self
                .worker_pool
                .execution_authority_v1()
                .load(Ordering::Acquire)
            && (wi.numerical_admission_sha256.is_none()
                || self
                    .worker_pool
                    .numerical_admission_v1()
                    .load(Ordering::Acquire))
            && (!needs_scheduler || (self.scheduler_registry.is_some() && self.shutdown.is_some()))
    }

    /// Construct with a default-sized concurrency semaphore from env.
    ///
    /// `scheduler_registry` + `shutdown` together gate the scheduler
    /// path: if both are `Some`, every model routes
    /// through `Self::enqueue_encode_into_scheduler` (and the
    /// score / extract twins) with per-model drain loops spawned
    /// lazily on first traffic by `Self::resolve_scheduler`.
    /// Otherwise every model keeps the legacy
    /// `Self::handle_encode` / `Self::handle_score` /
    /// `Self::handle_extract` flow. It's a programming error to
    /// pass exactly one as `Some` — we assert it below rather than
    /// carry a half-wired state through the hot path.
    #[allow(clippy::too_many_arguments)] // each arg is a distinct dependency
    pub fn new(
        backend: SharedBackend,
        worker_pool: Arc<AdapterWorkerPool>,
        payload_store: Arc<dyn PayloadStore>,
        publisher: Option<Arc<WorkPublisher>>,
        worker_id: String,
        runtime_state: Arc<RuntimeState>,
        latency_tracker: Arc<Mutex<LatencyTracker>>,
        tokenizer_registry: Arc<TokenizerRegistry>,
        scheduler_registry: Option<Arc<ProductionSchedulerRegistry>>,
        shutdown: Option<Arc<Shutdown>>,
        config_apply_state: Option<Arc<ConfigApplyState>>,
        pool_admission: Option<Arc<PoolAdmissionGate>>,
        batch_cancel_state: BatchCancelState,
        request_cancel_state: RequestCancelState,
    ) -> Self {
        debug_assert_eq!(
            scheduler_registry.is_some(),
            shutdown.is_some(),
            "scheduler_registry and shutdown must be wired together — one half invalidates the drain-loop lifecycle"
        );
        Self {
            backend,
            worker_pool,
            payload_store,
            publisher,
            worker_id,
            runtime_state,
            latency_tracker,
            batch_semaphore: Arc::new(Semaphore::new(default_max_concurrent_batches())),
            parked_item_permits: Arc::new(Semaphore::new(default_batch_budget().max(1) as usize)),
            parked_group_handles: Arc::new(std::sync::Mutex::new(Vec::new())),
            audio_prep_semaphore: Arc::new(Semaphore::new(default_audio_prep_permits())),
            tokenizer_registry,
            scheduler_registry,
            shutdown,
            config_apply_state,
            pool_admission,
            scheduler_drain_handles: Arc::new(Mutex::new(HashMap::new())),
            generation_handles: Arc::new(Mutex::new(Vec::new())),
            batch_cancel_state,
            request_cancel_state,
            work_deadline: WorkDeadlinePolicy::from_env(),
            dispatch_widths: Arc::new(std::sync::RwLock::new(HashMap::new())),
            pipelines: Arc::new(std::sync::Mutex::new(HashMap::new())),
        }
    }
}

impl Dispatcher {
    /// Execute one already-bound generation item without assuming a queue
    /// result substrate. The caller supplies a backpressured chunk sink;
    /// Python remains responsible for model semantics and chunk encoding.
    pub async fn process_local_generate<F, Fut>(
        &self,
        mut wi: WorkItem,
        on_chunk: F,
    ) -> Result<(), GenerateDispatchError>
    where
        F: Fn(Vec<u8>) -> Fut + Clone,
        Fut: std::future::Future<Output = Result<(), String>>,
    {
        let model_id = wi.model_id.clone();
        if self.model_is_unsupported(&model_id) {
            return Err(GenerateDispatchError::new(
                "BUNDLE_CONFIG_MISMATCH",
                "worker configuration cannot serve this model",
            ));
        }
        match self.backend.ensure_model_ready(&model_id).await {
            Ok(response) => match response.state {
                ReadinessState::Ready => {}
                ReadinessState::LoadingStarted
                | ReadinessState::LoadingInProgress
                | ReadinessState::RetryLater => {
                    return Err(GenerateDispatchError::new(
                        MODEL_LOADING_ERROR_CODE,
                        format!("model {model_id:?} is loading"),
                    ));
                }
                ReadinessState::Failed => {
                    return Err(GenerateDispatchError::new(
                        MODEL_LOAD_FAILED_ERROR_CODE,
                        format!("model {model_id:?} failed to load"),
                    ));
                }
            },
            Err(error) => {
                return Err(GenerateDispatchError::new(
                    "BACKEND_UNAVAILABLE",
                    format!("EnsureModelReady failed: {error}"),
                ));
            }
        }

        if let Some(generate) = wi.generate.as_mut() {
            crate::prep::media::normalize_generate_media(generate).map_err(|error| {
                GenerateDispatchError::new(INVALID_INPUT_ERROR_CODE, error.to_string())
            })?;
        } else {
            return Err(GenerateDispatchError::new(
                INVALID_INPUT_ERROR_CODE,
                "generate parameters are required",
            ));
        }

        let _execution_guard = if let Some(state) = self.config_apply_state.as_ref() {
            Some(state.lock_execution().await)
        } else {
            None
        };
        if unknown_bundle_config_hash([&wi], self.config_apply_state.as_deref()).is_some() {
            return Err(GenerateDispatchError::new(
                "BUNDLE_CONFIG_MISMATCH",
                "worker configuration changed before generation execution",
            ));
        }
        let executed_hash = wi.bundle_config_hash.clone();
        let reply_subject = wi.reply_subject.clone();
        let expected_request_id = wi.request_id.clone();
        let work_item_msgpack = rmp_serde::to_vec_named(&wi).map_err(|error| {
            GenerateDispatchError::new(
                "INTERNAL_ERROR",
                format!("failed to encode generate work item: {error}"),
            )
        })?;
        let state = Arc::new(Mutex::new(LocalGenerateState::default()));
        let callback_state = Arc::clone(&state);

        // The local-ingest streaming lane's execution-commit point, past its
        // own bundle-hash barrier above. Local ingest bypasses the broker, so
        // these observations are normally near zero — which is the correct
        // answer for this lane, not a reason to omit it. Omitting it would
        // rebuild the blind spot this metric was fixed for: a generation path
        // that executes real work and reports nothing.
        record_work_item_ages(&self.runtime_state.telemetry, std::iter::once(&wi));
        let _inflight_guard = InflightBatchGuard::enter(Arc::clone(&self.runtime_state));
        let result = self
            .worker_pool
            .process_generate(
                ProcessGenerateRequest {
                    model_id,
                    work_item_msgpack,
                },
                move |event| {
                    let state = Arc::clone(&callback_state);
                    let on_chunk = on_chunk.clone();
                    let executed_hash = executed_hash.clone();
                    let expected_request_id = expected_request_id.clone();
                    let reply_subject = reply_subject.clone();
                    async move {
                        match event.kind.as_str() {
                            "publish" => {
                                if event.reply_subject != reply_subject {
                                    return Err(IpcError::Server(
                                        "generation publish reply_subject mismatch".to_string(),
                                    ));
                                }
                                let publication = {
                                    let mut state = state.lock().await;
                                    validate_local_generate_publication(
                                        event.payload,
                                        &expected_request_id,
                                        &executed_hash,
                                        &mut state,
                                    )
                                    .map_err(IpcError::Server)?
                                };
                                match publication {
                                    LocalGeneratePublication::Chunk(payload) => {
                                        on_chunk(payload).await.map_err(IpcError::Server)
                                    }
                                    LocalGeneratePublication::Retry => Ok(()),
                                }
                            }
                            "ack" => {
                                let mut state = state.lock().await;
                                state.observe_ack().map_err(IpcError::Server)
                            }
                            "nak" => {
                                let mut state = state.lock().await;
                                state.observe_transport_nak().map_err(IpcError::Server)
                            }
                            "in_progress" => {
                                let state = state.lock().await;
                                state.observe_progress().map_err(IpcError::Server)
                            }
                            other => Err(IpcError::Server(format!(
                                "unknown ProcessGenerate event {other:?}"
                            ))),
                        }
                    }
                },
            )
            .await;

        if let Err(error) = result {
            let _ = self
                .worker_pool
                .signal_generate_cancel(wi.request_id.clone())
                .await;
            return Err(GenerateDispatchError::new(
                "TRANSPORT_FAILURE",
                format!("generation backend stream failed: {error}"),
            ));
        }
        let phase = state.lock().await.phase.clone();
        match phase {
            LocalGeneratePhase::Complete => Ok(()),
            LocalGeneratePhase::Retry { reason } => Err(GenerateDispatchError::new(
                "RETRY_LATER",
                format!("generation backend requested retry: {reason}"),
            )),
            phase => {
                let _ = self
                    .worker_pool
                    .signal_generate_cancel(wi.request_id.clone())
                    .await;
                Err(GenerateDispatchError::new(
                    "TRANSPORT_FAILURE",
                    format!("generation ended in incomplete phase {phase:?}"),
                ))
            }
        }
    }

    pub async fn signal_local_generate_cancel(
        &self,
        request_id: &str,
    ) -> Result<bool, GenerateDispatchError> {
        self.worker_pool
            .signal_generate_cancel(request_id.to_string())
            .await
            .map(|response| response.matched)
            .map_err(|error| {
                GenerateDispatchError::new(
                    "TRANSPORT_FAILURE",
                    format!("generation cancel IPC failed: {error}"),
                )
            })
    }

    fn model_is_unsupported(&self, model_id: &str) -> bool {
        self.config_apply_state
            .as_ref()
            .is_some_and(|state| state.model_is_unsupported(model_id))
    }

    fn current_bundle_config_hash(&self) -> Option<String> {
        self.config_apply_state
            .as_ref()
            .map(|state| state.current_bundle_config_hash())
    }

    fn verified_execution_hash<'a>(&self, wi: &'a WorkItem) -> Option<&'a str> {
        self.config_apply_state
            .as_ref()
            .filter(|state| state.accepts_bundle_config_hash(&wi.bundle_config_hash))
            .and_then(|_| {
                (!wi.bundle_config_hash.is_empty()).then_some(wi.bundle_config_hash.as_str())
            })
    }

    fn cancellation_for(
        &self,
        router_id: &str,
        request_id: &str,
        operation: &str,
        worker_direct: bool,
    ) -> Option<WorkCancellation> {
        classify_cancellation(
            &self.request_cancel_state,
            &self.batch_cancel_state,
            router_id,
            request_id,
            operation,
            worker_direct,
        )
    }

    async fn settle_if_cancelled(
        &self,
        wi: &WorkItem,
        delivery: &Delivery,
        stage: &'static str,
    ) -> bool {
        if self.settle_if_expired(wi, delivery, stage).await {
            return true;
        }
        let Some(scope) = self.cancellation_for(
            &wi.router_id,
            &wi.request_id,
            &wi.operation,
            delivery.worker_direct(),
        ) else {
            return false;
        };
        debug!(
            request_id = %wi.request_id,
            work_item_id = %wi.work_item_id,
            operation = %wi.operation,
            origin = %delivery.log_ref(),
            cancellation_scope = scope.as_str(),
            stage,
            "ACKing abandoned work item"
        );
        match ack(delivery, &self.runtime_state.telemetry).await {
            Ok(()) => {}
            Err(e) => {
                warn!(error = %e, stage, "ack failed on abandoned work item");
            }
        }
        true
    }

    /// Handle a NATS delivery whose gateway deadline has passed. With
    /// enforcement on it is ACK-dropped; otherwise it is counted and executed.
    /// Local-ingest callers bound their own calls and always get a result, and
    /// generation keeps its own cancellation contract.
    async fn settle_if_expired(
        &self,
        wi: &WorkItem,
        delivery: &Delivery,
        stage: &'static str,
    ) -> bool {
        if wi.operation == "generate" || !matches!(delivery, Delivery::Nats(..)) {
            return false;
        }
        let now = unix_now_s();
        let DeadlineStatus::Expired(overdue) =
            self.work_deadline.status(wi.deadline, wi.timestamp, now)
        else {
            return false;
        };
        let telemetry = &self.runtime_state.telemetry;
        // A bridged caller never waits past the gateway's deadline, so
        // admitted work is dropped then whatever the enforcement setting.
        if !self.work_deadline.enforce && wi.numerical_admission_sha256.is_none() {
            if stage == "before_ipc" {
                telemetry.work_item_deadline_exceeded(&wi.operation, "executed");
                if let Some(suppressed) = EXPIRED_EXECUTE_WARNINGS.allow() {
                    warn!(
                        request_id = %wi.request_id,
                        work_item_id = %wi.work_item_id,
                        operation = %wi.operation,
                        overdue_ms = overdue.as_millis() as u64,
                        apparent_age_ms = apparent_age_ms(wi.timestamp, now),
                        suppressed,
                        "executing work item past its deadline because SIE_WORK_DEADLINE_ENFORCE is off"
                    );
                }
            }
            return false;
        }
        telemetry.work_item_deadline_exceeded(&wi.operation, "dropped");
        if let Some(suppressed) = EXPIRED_DROP_WARNINGS.allow() {
            warn!(
                request_id = %wi.request_id,
                work_item_id = %wi.work_item_id,
                operation = %wi.operation,
                overdue_ms = overdue.as_millis() as u64,
                apparent_age_ms = apparent_age_ms(wi.timestamp, now),
                stage,
                suppressed,
                "ACK-dropping work item past its deadline"
            );
        }
        if let Err(e) = ack_with_reason(delivery, telemetry, "deadline_exceeded").await {
            warn!(error = %e, stage, "ack failed on expired work item");
        }
        true
    }

    /// Warn when a delivery's deadline is ignored for its budget, or when its
    /// timestamps show that this worker's clock and the gateway's disagree by
    /// more than the skew tolerance.
    fn observe_deadline_clock(&self, wi: &WorkItem, delivery: &Delivery) {
        let Delivery::Nats(msg, ..) = delivery else {
            return;
        };
        if wi.operation == "generate" {
            return;
        }
        if let Some(budget_s) = self
            .work_deadline
            .rejected_budget_s(wi.deadline, wi.timestamp)
        {
            if let Some(suppressed) = REJECTED_DEADLINE_WARNINGS.allow() {
                warn!(
                    request_id = %wi.request_id,
                    deadline_budget_s = budget_s,
                    max_budget_s = self.work_deadline.max_budget.as_secs(),
                    suppressed,
                    "ignoring a work item deadline that is not within SIE_WORK_DEADLINE_MAX_BUDGET_S of its timestamp; raise the setting to at least the gateway request timeout"
                );
            }
            return;
        }
        let now = unix_now_s();
        let first_delivery = msg.info().is_ok_and(|info| info.delivered == 1);
        let Some(signal) =
            self.work_deadline
                .clock_skew_signal(wi.deadline, wi.timestamp, first_delivery, now)
        else {
            return;
        };
        let Some(suppressed) = CLOCK_SKEW_WARNINGS.allow() else {
            return;
        };
        match signal {
            ClockSkewSignal::TimestampAhead { ahead_ms } => warn!(
                request_id = %wi.request_id,
                ahead_ms,
                skew_tolerance_ms = self.work_deadline.skew_tolerance.as_millis() as u64,
                suppressed,
                "work item was published later than this worker's clock reads; the worker clock is likely behind the gateway clock"
            ),
            ClockSkewSignal::FirstDeliveryExpired { overdue_ms } => warn!(
                request_id = %wi.request_id,
                overdue_ms,
                apparent_age_ms = apparent_age_ms(wi.timestamp, now),
                suppressed,
                "first delivery of a work item is already past its deadline; it waited in the stream longer than its budget or this worker's clock is ahead of the gateway clock"
            ),
        }
    }

    /// Keep a held NATS delivery's JetStream lease alive until it settles or
    /// its lease horizon passes, so slow queues and long backend calls do not
    /// trigger a redelivery of work that is still running.
    fn hold_progress_lease(&self, wi: &WorkItem, delivery: &mut Delivery) {
        if let Some(horizon) =
            self.work_deadline
                .lease_horizon(wi.deadline, wi.timestamp, unix_now_s())
        {
            delivery.hold_progress_lease(horizon, &self.runtime_state.telemetry);
        }
    }

    async fn retain_uncancelled(
        &self,
        items: Vec<(WorkItem, Delivery)>,
        stage: &'static str,
    ) -> Vec<(WorkItem, Delivery)> {
        let mut retained = Vec::with_capacity(items.len());
        for (wi, delivery) in items {
            if self.settle_if_cancelled(&wi, &delivery, stage).await {
                continue;
            }
            retained.push((wi, delivery));
        }
        retained
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WorkCancellation {
    Request,
    BatchDirect,
}

impl WorkCancellation {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Request => "request",
            Self::BatchDirect => "batch_direct",
        }
    }
}

fn classify_cancellation(
    request_state: &RequestCancelState,
    batch_state: &BatchCancelState,
    router_id: &str,
    request_id: &str,
    operation: &str,
    worker_direct: bool,
) -> Option<WorkCancellation> {
    if operation != "generate" && request_state.is_cancelled(router_id, request_id) {
        return Some(WorkCancellation::Request);
    }
    (worker_direct && operation != "generate" && batch_state.is_cancelled(request_id))
        .then_some(WorkCancellation::BatchDirect)
}

/// First work item this worker must not execute under its current config: an
/// unknown bundle config hash, or a model the worker reported it cannot serve.
fn unknown_bundle_config_hash<'a>(
    items: impl IntoIterator<Item = &'a WorkItem>,
    state: Option<&ConfigApplyState>,
) -> Option<(&'a str, usize)> {
    let mut first_unknown: Option<&'a str> = None;
    let mut count = 0usize;
    for wi in items {
        if state.map_or(!wi.bundle_config_hash.is_empty(), |state| {
            !state.accepts_work(&wi.bundle_config_hash, &wi.model_id)
        }) {
            count += 1;
            if first_unknown.is_none() {
                first_unknown = Some(wi.bundle_config_hash.as_str());
            }
        }
    }
    first_unknown.map(|hash| (hash, count))
}

/// Telemetry reason for NAKing `model_id` work that a config barrier refused.
/// A model the worker reports it cannot serve is `model_unsupported`, as it is
/// at intake and before readiness; any other refusal is an old bundle hash
/// (`retry`).
fn barrier_nak_reason(state: Option<&ConfigApplyState>, model_id: &str) -> &'static str {
    if state.is_some_and(|state| state.model_is_unsupported(model_id)) {
        "model_unsupported"
    } else {
        "retry"
    }
}

impl Dispatcher {
    /// Process a full fetched batch.
    ///
    /// Legacy op handlers return after every message has either been ACKed
    /// (we published a result) or NAKed (we'll see it again). Scheduler-routed
    /// handlers return after enqueue, but any pull-loop admission permit
    /// rides the item's [`Delivery`] (inside [`SchedulerMeta`]) until the
    /// scheduler/backend path settles it.
    ///
    /// Model-id routing: derived from the NATS **subject**, falling back
    /// to `WorkItem.model_id` when the subject is malformed. On
    /// disagreement the subject wins (that's what JetStream used to
    /// dispatch us) and we warn.
    ///
    /// Concurrency:
    /// * group by `model_id` only.
    /// * model groups run concurrently; once a group's model is ready its
    ///   dispatch is capped by `batch_semaphore` to avoid ACK-timeout storms,
    ///   and a group whose model is still loading is parked in its own task
    ///   so this call does not wait for the load.
    /// * within a model, encode/score/extract run concurrently via
    ///   `tokio::join!` so slow payload fetches don't block other ops.
    pub(crate) async fn handle_batch(self: &Arc<Self>, messages: Vec<QueuedMessage>) {
        let batch_started = Instant::now();
        let batch_size = messages.len();
        info!(batch_size, "handle_batch: start");

        let base_delay_ms = base_nak_delay_ms();
        let mut decoded: Vec<(WorkItem, Delivery)> = Vec::with_capacity(batch_size);
        for queued in messages {
            // The admission permit moves into the [`Delivery`] here: every
            // reject path below settles (ACK/NAK) and drops it immediately,
            // and successful decodes carry it until downstream settlement.
            let (msg, admission_permit) = queued.into_parts();
            self.runtime_state
                .telemetry
                .nats_received(msg.info().ok().map(|info| info.delivered as u64));
            if let Some(header) = unexpected_work_header(msg.headers.as_ref()) {
                warn!(
                    subject = %msg.subject,
                    header = %header,
                    "rejecting work the NATS server copied from another stream — ACKing to drop",
                );
                if let Err(e) = ack(
                    &Delivery::Nats(msg, admission_permit, None),
                    &self.runtime_state.telemetry,
                )
                .await
                {
                    warn!(error = %e, "ack failed on drop");
                }
                continue;
            }
            // Source of truth for routing is the NATS subject (JetStream
            // already used it to dispatch to this consumer). If the subject
            // doesn't yield a model_id, we can't trust the payload either,
            // so NAK for redelivery and let max_deliver → DLQ handle it.
            let subject_model = match extract_model_id(&msg.subject) {
                Some(m) => m,
                None => {
                    warn!(
                        subject = %msg.subject,
                        "could not extract model_id from subject — NAKing for redelivery",
                    );
                    nak_one(
                        &Delivery::Nats(msg, admission_permit, None),
                        base_delay_ms,
                        &self.runtime_state.telemetry,
                    )
                    .await;
                    continue;
                }
            };
            match rmp_serde::from_slice::<WorkItem>(&msg.payload) {
                Ok(mut wi) => {
                    // These contracts are derived from the consumer's
                    // versioned subject. Admitted work travels only on a
                    // subject no sidecar without the admission fence
                    // consumes, and its payload field must agree with that
                    // subject. Refuse before readiness or payload fetch.
                    let admission_violation = numerical_admission_violation(&msg.subject, &wi);
                    let stale_admission = admission_violation.is_none()
                        && wi.numerical_admission_sha256.is_some()
                        && !self.execution_hash_is_current(&wi);
                    if admission_violation.is_none()
                        && !stale_admission
                        && requires_execution_authority_v1(&msg.subject)
                        && (!execution_authority_model_matches(&msg.subject, &wi.model_id)
                            || !self
                                .execution_authority_is_available(&wi, wi.operation != "generate"))
                    {
                        nak_one_with_reason(
                            &Delivery::Nats(msg, admission_permit, None),
                            base_delay_ms,
                            &self.runtime_state.telemetry,
                            "execution_authority_unavailable",
                        )
                        .await;
                        continue;
                    }
                    if !reply_subject_is_safe(&wi.reply_subject) {
                        // ACK-to-drop (not NAK): the subject is attacker-
                        // controlled; retrying just amplifies the attempt.
                        warn!(
                            work_item_id = %wi.work_item_id,
                            reply_subject = %truncate(&wi.reply_subject, 60),
                            "rejecting WorkItem with suspicious reply_subject — ACKing to drop",
                        );
                        match ack(
                            &Delivery::Nats(msg, admission_permit, None),
                            &self.runtime_state.telemetry,
                        )
                        .await
                        {
                            Ok(()) => {}
                            Err(e) => {
                                warn!(error = %e, "ack failed on drop");
                            }
                        }
                        continue;
                    }
                    let mut delivery = Delivery::Nats(msg, admission_permit, None);
                    if let Some(violation) = admission_violation {
                        warn!(
                            work_item_id = %wi.work_item_id,
                            model = %wi.model_id,
                            violation,
                            "work breaks the numerical admission contract — answering and ACKing",
                        );
                        self.refuse_violation(&wi, &delivery).await;
                        continue;
                    }
                    if stale_admission {
                        self.refuse_stale_admission(&wi, &delivery).await;
                        continue;
                    }
                    self.observe_deadline_clock(&wi, &delivery);
                    if self.settle_if_cancelled(&wi, &delivery, "intake").await {
                        continue;
                    }
                    if let Some(gate) = self.pool_admission.as_ref() {
                        let admission_pool = wi.admission_pool.trim();
                        if !gate.admits_work_item_pool(admission_pool) {
                            debug!(
                                work_item_id = %wi.work_item_id,
                                request_id = %wi.request_id,
                                admission_pool = %admission_pool,
                                physical_pool = %wi.pool_name,
                                "WorkItem admission_pool does not assign this worker — NAKing for redelivery"
                            );
                            nak_one_with_reason(
                                &delivery,
                                base_delay_ms,
                                &self.runtime_state.telemetry,
                                "pool_not_assigned",
                            )
                            .await;
                            continue;
                        }
                    }
                    if wi.model_id != subject_model {
                        warn!(
                            work_item_id = %wi.work_item_id,
                            origin = %delivery.log_ref(),
                            wi_model_id = %wi.model_id,
                            subject_model_id = %subject_model,
                            "WorkItem.model_id disagrees with subject — trusting subject",
                        );
                        wi.model_id = subject_model;
                    }
                    if self.model_is_unsupported(&wi.model_id) {
                        debug!(
                            work_item_id = %wi.work_item_id,
                            request_id = %wi.request_id,
                            model = %wi.model_id,
                            "worker cannot serve this model under its current config — NAKing for redelivery"
                        );
                        nak_one_with_reason(
                            &delivery,
                            base_delay_ms,
                            &self.runtime_state.telemetry,
                            "model_unsupported",
                        )
                        .await;
                        continue;
                    }
                    if wi.operation != "generate" {
                        self.hold_progress_lease(&wi, &mut delivery);
                    }
                    decoded.push((wi, delivery));
                }
                Err(e) => {
                    // NAK so JetStream redelivers (possibly to a worker on a
                    // newer wire version) and eventually DLQs after
                    // max_deliver. ACK-dropping would silently discard the
                    // item on a transient msgpack glitch.
                    warn!(error = %e, subject = %msg.subject, "failed to decode WorkItem — NAKing for redelivery");
                    nak_one(
                        &Delivery::Nats(msg, admission_permit, None),
                        base_delay_ms,
                        &self.runtime_state.telemetry,
                    )
                    .await;
                }
            }
        }
        if decoded.is_empty() {
            info!(
                batch_size,
                elapsed_ms = batch_started.elapsed().as_millis() as u64,
                "handle_batch: done (all messages rejected before dispatch)"
            );
            return;
        }
        self.dispatch_decoded(decoded, batch_size, batch_started)
            .await;
    }

    /// Dispatch already-decoded `(WorkItem, Delivery)` pairs — the shared
    /// tail of [`Self::handle_batch`], also fed directly by the local-ingest
    /// server (P2.10, §4.6) whose items arrive pre-decoded over the UDS
    /// rather than as NATS messages. Both ingest paths coalesce in the same
    /// per-model scheduler batch assembly downstream.
    pub async fn dispatch_decoded(
        self: &Arc<Self>,
        decoded: Vec<(WorkItem, Delivery)>,
        batch_size: usize,
        batch_started: Instant,
    ) {
        let mut generate_items = Vec::new();
        let mut regular_items = Vec::with_capacity(decoded.len());
        for (wi, delivery) in decoded {
            if wi.operation == "generate" {
                match delivery {
                    // Generation bypasses the scheduler; re-bundle the permit
                    // with the message so intake capacity stays held until
                    // the generate task settles the delivery.
                    Delivery::Nats(msg, permit, _) => {
                        generate_items.push((wi, QueuedMessage::new(msg, permit)))
                    }
                    delivery @ Delivery::Local(_) => {
                        // Generation streams chunk envelopes over NATS reply
                        // subjects; the local-ingest publish_work op is
                        // one-shot (PROTOCOL.md v0.1 — streaming ops land
                        // with P2.6). Answer a typed error instead of
                        // silently sinking the item.
                        let _ = self
                            .publish_error(
                                &wi,
                                &delivery,
                                "bad_operation",
                                "generate is not supported on the local-ingest lane (P2.6)",
                            )
                            .await;
                    }
                }
            } else {
                regular_items.push((wi, delivery));
            }
        }
        let generate_count = generate_items.len();
        if generate_count > 0 {
            self.spawn_generate_items(generate_items).await;
        }
        if regular_items.is_empty() {
            info!(
                batch_size,
                generate = generate_count,
                elapsed_ms = batch_started.elapsed().as_millis() as u64,
                "handle_batch: done (generation items handed off)"
            );
            return;
        }

        let model_groups = group_by_model_only(regular_items);
        let group_count = model_groups.len();
        let mut futs = Vec::with_capacity(group_count);
        for (model_id, items) in model_groups {
            let this = Arc::clone(self);
            futs.push(async move {
                let result = this.handle_model_group(&model_id, items, None).await;
                if let Err(e) = result {
                    warn!(model = %model_id, error = %ErrChain(&e), "model group handling failed");
                }
            });
        }
        join_all(futs).await;
        info!(
            batch_size,
            group_count,
            elapsed_ms = batch_started.elapsed().as_millis() as u64,
            "handle_batch: done"
        );
    }

    async fn spawn_generate_items(self: &Arc<Self>, items: Vec<(WorkItem, QueuedMessage)>) {
        let mut handles = self.generation_handles.lock().await;
        handles.retain(|h| !h.is_finished());
        for (wi, msg) in items {
            let this = Arc::clone(self);
            handles.push(tokio::spawn(async move {
                this.handle_generate_item(wi, msg).await;
            }));
        }
    }

    async fn handle_generate_item(self: Arc<Self>, mut wi: WorkItem, msg: QueuedMessage) {
        let model_id = wi.model_id.clone();
        let profile_id =
            (!wi.profile_id.trim().is_empty()).then(|| wi.profile_id.trim().to_string());
        let delivery = DeliveryContext::from_message(&msg);
        let base_delay_ms = base_nak_delay_ms();
        if requires_execution_authority_v1(&msg.subject)
            && (!execution_authority_model_matches(&msg.subject, &wi.model_id)
                || !self.execution_authority_is_available(&wi, false))
        {
            nak_msg_with_reason(
                &msg,
                base_delay_ms,
                &self.runtime_state.telemetry,
                "execution_authority_unavailable",
            )
            .await;
            return;
        }
        info!(
            work_item_id = %wi.work_item_id,
            request_id = %wi.request_id,
            model = %model_id,
            subject = %delivery.subject,
            stream = %delivery.stream,
            consumer = %delivery.consumer,
            stream_seq = delivery.stream_sequence,
            consumer_seq = delivery.consumer_sequence,
            delivery_count = delivery.delivered,
            pending = delivery.pending,
            has_metadata = delivery.has_metadata,
            "generate delivery received"
        );

        if self.model_is_unsupported(&model_id) {
            info!(
                work_item_id = %wi.work_item_id,
                model = %model_id,
                "worker cannot serve this model under its current config — NAKing before readiness"
            );
            nak_msg_with_reason(
                &msg,
                base_delay_ms,
                &self.runtime_state.telemetry,
                "model_unsupported",
            )
            .await;
            return;
        }
        let readiness_resp = match self.backend.ensure_model_ready(&model_id).await {
            Ok(r) => r,
            Err(e) => {
                warn!(
                    work_item_id = %wi.work_item_id,
                    request_id = %wi.request_id,
                    model = %model_id,
                    subject = %delivery.subject,
                    stream = %delivery.stream,
                    consumer = %delivery.consumer,
                    stream_seq = delivery.stream_sequence,
                    consumer_seq = delivery.consumer_sequence,
                    delivery_count = delivery.delivered,
                    pending = delivery.pending,
                    error = %ErrChain(&e),
                    "EnsureModelReady failed for generate — NAKing"
                );
                nak_msg(
                    &msg,
                    nak_delay_for_backend_error(&e),
                    &self.runtime_state.telemetry,
                )
                .await;
                return;
            }
        };
        match &readiness_resp.state {
            ReadinessState::Ready => {}
            ReadinessState::LoadingStarted => {
                info!(
                    work_item_id = %wi.work_item_id,
                    request_id = %wi.request_id,
                    model = %model_id,
                    readiness = ?readiness_resp.state,
                    delay_ms = base_delay_ms,
                    subject = %delivery.subject,
                    stream = %delivery.stream,
                    consumer = %delivery.consumer,
                    stream_seq = delivery.stream_sequence,
                    consumer_seq = delivery.consumer_sequence,
                    delivery_count = delivery.delivered,
                    pending = delivery.pending,
                    "generate model started loading — publishing MODEL_LOADING chunk + ACK"
                );
                let message = format!("Model '{model_id}' is loading; retry later.");
                match self
                    .publish_generate_terminal_error(&wi, MODEL_LOADING_ERROR_CODE, &message)
                    .await
                {
                    Ok(_) => match ack_msg(&msg, &self.runtime_state.telemetry).await {
                        Ok(()) => self
                            .runtime_state
                            .telemetry
                            .generation_model_loading_response(
                                &model_id,
                                profile_id.as_deref(),
                                "loading_started",
                                "success",
                            ),
                        Err(e) => {
                            self.runtime_state
                                .telemetry
                                .generation_model_loading_response(
                                    &model_id,
                                    profile_id.as_deref(),
                                    "loading_started",
                                    "ack_error",
                                );
                            warn!(
                                work_item_id = %wi.work_item_id,
                                request_id = %wi.request_id,
                                model = %model_id,
                                stream_seq = delivery.stream_sequence,
                                delivery_count = delivery.delivered,
                                error = %e,
                                "ack after MODEL_LOADING chunk publish failed"
                            );
                        }
                    },
                    Err(_) => {
                        self.runtime_state
                            .telemetry
                            .generation_model_loading_response(
                                &model_id,
                                profile_id.as_deref(),
                                "loading_started",
                                "publish_error",
                            );
                        nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await;
                    }
                }
                return;
            }
            ReadinessState::RetryLater => {
                info!(
                    work_item_id = %wi.work_item_id,
                    request_id = %wi.request_id,
                    model = %model_id,
                    readiness = ?readiness_resp.state,
                    delay_ms = base_delay_ms,
                    subject = %delivery.subject,
                    stream = %delivery.stream,
                    consumer = %delivery.consumer,
                    stream_seq = delivery.stream_sequence,
                    consumer_seq = delivery.consumer_sequence,
                    delivery_count = delivery.delivered,
                    pending = delivery.pending,
                    "generate model retry requested — NAKing"
                );
                nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await;
                return;
            }
            ReadinessState::LoadingInProgress => {
                let delay_ms = readiness_progress_delay_ms(&readiness_resp.state, base_delay_ms)
                    .unwrap_or_else(|| base_delay_ms.saturating_mul(2));
                info!(
                    work_item_id = %wi.work_item_id,
                    request_id = %wi.request_id,
                    model = %model_id,
                    readiness = ?readiness_resp.state,
                    delay_ms,
                    subject = %delivery.subject,
                    stream = %delivery.stream,
                    consumer = %delivery.consumer,
                    stream_seq = delivery.stream_sequence,
                    consumer_seq = delivery.consumer_sequence,
                    delivery_count = delivery.delivered,
                    pending = delivery.pending,
                    "generate model still loading — publishing MODEL_LOADING chunk + ACK"
                );
                let message = format!("Model '{model_id}' is still loading; retry later.");
                match self
                    .publish_generate_terminal_error(&wi, MODEL_LOADING_ERROR_CODE, &message)
                    .await
                {
                    Ok(_) => match ack_msg(&msg, &self.runtime_state.telemetry).await {
                        Ok(()) => self
                            .runtime_state
                            .telemetry
                            .generation_model_loading_response(
                                &model_id,
                                profile_id.as_deref(),
                                "loading_in_progress",
                                "success",
                            ),
                        Err(e) => {
                            self.runtime_state
                                .telemetry
                                .generation_model_loading_response(
                                    &model_id,
                                    profile_id.as_deref(),
                                    "loading_in_progress",
                                    "ack_error",
                                );
                            warn!(
                                work_item_id = %wi.work_item_id,
                                request_id = %wi.request_id,
                                model = %model_id,
                                stream_seq = delivery.stream_sequence,
                                delivery_count = delivery.delivered,
                                error = %e,
                                "ack after MODEL_LOADING chunk publish failed"
                            );
                        }
                    },
                    Err(_) => {
                        self.runtime_state
                            .telemetry
                            .generation_model_loading_response(
                                &model_id,
                                profile_id.as_deref(),
                                "loading_in_progress",
                                "publish_error",
                            );
                        nak_msg(&msg, delay_ms, &self.runtime_state.telemetry).await;
                    }
                }
                return;
            }
            ReadinessState::Failed => {
                // Terminal load failure (permanent cooldown). Re-driving would
                // hang the streaming client forever, so
                // publish a terminal MODEL_LOAD_FAILED chunk + ACK — the
                // gateway's streaming collector maps the code to a typed
                // failure exactly like the batch path.
                info!(
                    work_item_id = %wi.work_item_id,
                    request_id = %wi.request_id,
                    model = %model_id,
                    readiness = ?readiness_resp.state,
                    subject = %delivery.subject,
                    stream = %delivery.stream,
                    consumer = %delivery.consumer,
                    stream_seq = delivery.stream_sequence,
                    consumer_seq = delivery.consumer_sequence,
                    delivery_count = delivery.delivered,
                    pending = delivery.pending,
                    "generate model load failed terminally — publishing MODEL_LOAD_FAILED chunk + ACK"
                );
                let message = format!("Model '{model_id}' failed to load permanently.");
                match self
                    .publish_generate_terminal_error(&wi, MODEL_LOAD_FAILED_ERROR_CODE, &message)
                    .await
                {
                    Ok(_) => match ack_msg(&msg, &self.runtime_state.telemetry).await {
                        Ok(()) => self
                            .runtime_state
                            .telemetry
                            .generation_model_loading_response(
                                &model_id,
                                profile_id.as_deref(),
                                "failed",
                                "success",
                            ),
                        Err(e) => {
                            self.runtime_state
                                .telemetry
                                .generation_model_loading_response(
                                    &model_id,
                                    profile_id.as_deref(),
                                    "failed",
                                    "ack_error",
                                );
                            warn!(
                                work_item_id = %wi.work_item_id,
                                request_id = %wi.request_id,
                                model = %model_id,
                                stream_seq = delivery.stream_sequence,
                                delivery_count = delivery.delivered,
                                error = %e,
                                "ack after MODEL_LOAD_FAILED chunk publish failed"
                            );
                        }
                    },
                    Err(_) => {
                        self.runtime_state
                            .telemetry
                            .generation_model_loading_response(
                                &model_id,
                                profile_id.as_deref(),
                                "failed",
                                "publish_error",
                            );
                        // Terminal failure but the publish itself failed: NAK
                        // so redelivery can retry surfacing the typed error
                        // rather than silently dropping the client's request.
                        nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await;
                    }
                }
                return;
            }
        }

        // Resolve an offloaded generate payload. The gateway offloads large
        // vision work items to the object store (``payload_ref`` set,
        // ``generate`` blanked); fetch + inline so the adapter worker — which
        // has no object-store access — receives a self-contained WorkItem. The
        // blob is base64-string image data, so it decodes cleanly as
        // ``serde_json::Value`` (msgpack ``bin`` would not).
        if let Some(payload_ref) = wi.payload_ref.clone() {
            match self.payload_store.get(&payload_ref).await {
                Ok(bytes) => match decode_offloaded_generate(&bytes) {
                    Ok(generate) => {
                        wi.generate = Some(generate);
                        wi.payload_ref = None;
                    }
                    Err(e) => {
                        warn!(
                            work_item_id = %wi.work_item_id,
                            request_id = %wi.request_id,
                            model = %model_id,
                            subject = %delivery.subject,
                            stream = %delivery.stream,
                            consumer = %delivery.consumer,
                            stream_seq = delivery.stream_sequence,
                            consumer_seq = delivery.consumer_sequence,
                            delivery_count = delivery.delivered,
                            pending = delivery.pending,
                            error = %e,
                            "failed to decode offloaded generate payload — publishing error + ACK"
                        );
                        match self
                            .publish_error_generate(
                                &wi,
                                "internal_error",
                                "failed to decode offloaded generate payload",
                                is_worker_direct_work_subject(&msg.subject),
                            )
                            .await
                        {
                            Ok(_) => match ack_msg(&msg, &self.runtime_state.telemetry).await {
                                Ok(()) => {}
                                Err(e) => {
                                    warn!(
                                        work_item_id = %wi.work_item_id,
                                        request_id = %wi.request_id,
                                        model = %model_id,
                                        stream_seq = delivery.stream_sequence,
                                        delivery_count = delivery.delivered,
                                        error = %e,
                                        "ack after offload-decode error failed"
                                    );
                                }
                            },
                            Err(_) => {
                                nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await
                            }
                        }
                        return;
                    }
                },
                Err(e) => {
                    if matches!(&e, PayloadError::TooLarge { .. }) {
                        warn!(
                            work_item_id = %wi.work_item_id,
                            request_id = %wi.request_id,
                            model = %model_id,
                            error = %e,
                            "offloaded generate payload too large — publishing terminal error + ACK"
                        );
                        match self
                            .publish_generate_terminal_error(
                                &wi,
                                PAYLOAD_TOO_LARGE_ERROR_CODE,
                                PAYLOAD_TOO_LARGE_MESSAGE,
                            )
                            .await
                        {
                            Ok(_) => match ack_msg(&msg, &self.runtime_state.telemetry).await {
                                Ok(()) => {}
                                Err(e) => {
                                    warn!(error = %e, "ack after oversized generate payload failed");
                                }
                            },
                            Err(_) => {
                                nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await
                            }
                        }
                        return;
                    }
                    warn!(
                        work_item_id = %wi.work_item_id,
                        request_id = %wi.request_id,
                        model = %model_id,
                        subject = %delivery.subject,
                        stream = %delivery.stream,
                        consumer = %delivery.consumer,
                        stream_seq = delivery.stream_sequence,
                        consumer_seq = delivery.consumer_sequence,
                        delivery_count = delivery.delivered,
                        pending = delivery.pending,
                        error = %e,
                        "failed to resolve offloaded generate payload — NAKing"
                    );
                    nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await;
                    return;
                }
            }
        }

        if let Some(generate) = wi.generate.as_mut() {
            if let Err(error) = crate::prep::media::normalize_generate_media(generate) {
                warn!(
                    work_item_id = %wi.work_item_id,
                    request_id = %wi.request_id,
                    model = %model_id,
                    error = %error,
                    "invalid generation media — publishing terminal error + ACK"
                );
                match self
                    .publish_generate_terminal_error(
                        &wi,
                        INVALID_INPUT_ERROR_CODE,
                        &error.to_string(),
                    )
                    .await
                {
                    Ok(_) => {
                        let _ = ack_msg(&msg, &self.runtime_state.telemetry).await;
                    }
                    Err(_) => {
                        nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await;
                    }
                }
                return;
            }
        }

        // Bind the whole streaming execution to one stable worker config.
        // Config applies take the write side of this barrier; concurrent
        // inference takes shared guards. Re-check after payload resolution so
        // a queued A request can never execute after the worker advances to B.
        let _execution_guard = if let Some(state) = self.config_apply_state.as_ref() {
            Some(state.lock_execution().await)
        } else {
            None
        };
        if unknown_bundle_config_hash([&wi], self.config_apply_state.as_deref()).is_some() {
            let reason = barrier_nak_reason(self.config_apply_state.as_deref(), &model_id);
            info!(
                model = %model_id,
                expected_hash = %wi.bundle_config_hash,
                local_hash = %self.config_apply_state.as_ref().map(|state| state.current_bundle_config_hash()).unwrap_or_default(),
                reason,
                "generate work refused at the config barrier before execution — NAKing"
            );
            nak_msg_with_reason(&msg, base_delay_ms, &self.runtime_state.telemetry, reason).await;
            return;
        }

        let work_item_msgpack = match rmp_serde::to_vec_named(&wi) {
            Ok(bytes) => bytes,
            Err(e) => {
                warn!(
                    work_item_id = %wi.work_item_id,
                    request_id = %wi.request_id,
                    model = %model_id,
                    subject = %delivery.subject,
                    stream = %delivery.stream,
                    consumer = %delivery.consumer,
                    stream_seq = delivery.stream_sequence,
                    consumer_seq = delivery.consumer_sequence,
                    delivery_count = delivery.delivered,
                    pending = delivery.pending,
                    error = %e,
                    "failed to re-encode generate WorkItem — publishing error + ACK"
                );
                match self
                    .publish_error_generate(
                        &wi,
                        "internal_error",
                        "failed to encode generate work item",
                        is_worker_direct_work_subject(&msg.subject),
                    )
                    .await
                {
                    Ok(_) => match ack_msg(&msg, &self.runtime_state.telemetry).await {
                        Ok(()) => {}
                        Err(e) => {
                            warn!(
                                work_item_id = %wi.work_item_id,
                                request_id = %wi.request_id,
                                model = %model_id,
                                stream_seq = delivery.stream_sequence,
                                delivery_count = delivery.delivered,
                                error = %e,
                                "ack after generate encode error failed"
                            );
                        }
                    },
                    Err(_) => nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await,
                }
                return;
            }
        };

        let Some(publisher) = self.publisher.clone() else {
            // Unreachable by construction: generate items only arrive here
            // as NATS deliveries, and `run()` always wires the publisher.
            warn!(
                work_item_id = %wi.work_item_id,
                "generate item without a NATS publisher — NAKing"
            );
            nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await;
            return;
        };
        let settled = Arc::new(AtomicBool::new(false));
        let msg = Arc::new(msg);
        let delivery_log = Arc::new(GenerateDeliveryLogContext {
            work_item_id: wi.work_item_id.clone(),
            request_id: wi.request_id.clone(),
            model_id: model_id.clone(),
            reply_subject: wi.reply_subject.clone(),
            delivery,
        });
        let executed_bundle_config_hash: Arc<str> = Arc::from(wi.bundle_config_hash.clone());
        let settled_for_events = Arc::clone(&settled);
        let msg_for_events = Arc::clone(&msg);
        let delivery_log_for_events = Arc::clone(&delivery_log);
        let telemetry_for_events = self.runtime_state.telemetry.clone();
        // Generation's execution-commit point. It never reaches
        // `apply_outcome`, so without this call the most expensive operation in
        // the system — and the one B2 singles out as excluded from
        // cancellation — would be entirely absent from the age distribution.
        record_work_item_ages(&self.runtime_state.telemetry, std::iter::once(&wi));
        self.runtime_state.inflight_batches.inc();
        let requires_authority = requires_execution_authority_v1(&msg.subject);
        let result = self
            .worker_pool
            .process_generate_with_authority(
                ProcessGenerateRequest {
                    model_id: model_id.clone(),
                    work_item_msgpack,
                },
                move |event| {
                    let publisher = Arc::clone(&publisher);
                    let executed_bundle_config_hash = Arc::clone(&executed_bundle_config_hash);
                    let settled = Arc::clone(&settled_for_events);
                    let msg = Arc::clone(&msg_for_events);
                    let delivery_log = Arc::clone(&delivery_log_for_events);
                    let telemetry = telemetry_for_events.clone();
                    async move {
                        handle_generate_event(
                            event,
                            publisher,
                            telemetry,
                            settled,
                            msg,
                            delivery_log,
                            &executed_bundle_config_hash,
                        )
                        .await
                        .map_err(|e| IpcError::Server(e.to_string()))
                    }
                },
                requires_authority,
            )
            .await;
        decrement_gauge(&self.runtime_state.inflight_batches, 1);

        match result {
            Ok(()) => {
                if !settled.load(Ordering::SeqCst) {
                    warn!(
                        work_item_id = %wi.work_item_id,
                        request_id = %wi.request_id,
                        model = %model_id,
                        subject = %delivery_log.delivery.subject,
                        stream = %delivery_log.delivery.stream,
                        consumer = %delivery_log.delivery.consumer,
                        stream_seq = delivery_log.delivery.stream_sequence,
                        consumer_seq = delivery_log.delivery.consumer_sequence,
                        delivery_count = delivery_log.delivery.delivered,
                        pending = delivery_log.delivery.pending,
                        "ProcessGenerate ended without ACK/NAK event — NAKing"
                    );
                    nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await;
                }
            }
            Err(e) => {
                warn!(
                    work_item_id = %wi.work_item_id,
                    request_id = %wi.request_id,
                    model = %model_id,
                    subject = %delivery_log.delivery.subject,
                    stream = %delivery_log.delivery.stream,
                    consumer = %delivery_log.delivery.consumer,
                    stream_seq = delivery_log.delivery.stream_sequence,
                    consumer_seq = delivery_log.delivery.consumer_sequence,
                    delivery_count = delivery_log.delivery.delivered,
                    pending = delivery_log.delivery.pending,
                    error = %e,
                    "ProcessGenerate failed — NAKing if unsettled"
                );
                if !settled.swap(true, Ordering::SeqCst) {
                    nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await;
                }
            }
        }
    }

    /// Move a group whose model is still loading into its own task, so the
    /// wait holds no batch permit, keeps no pull-loop dispatch task alive,
    /// and gives back each item's pull-loop admission permit. Items trade
    /// that permit for a parked-item permit; items beyond the parked-item
    /// capacity are NAKed for redelivery rather than held.
    fn park_model_group(self: &Arc<Self>, model_id: &str, items: Vec<(WorkItem, Delivery)>) {
        let mut parked = Vec::with_capacity(items.len());
        let mut overflow = Vec::new();
        for (wi, mut delivery) in items {
            if delivery.holds_admission_permit() {
                match Arc::clone(&self.parked_item_permits).try_acquire_owned() {
                    Ok(permit) => delivery.exchange_admission_permit(permit),
                    Err(_) => {
                        overflow.push((wi, delivery));
                        continue;
                    }
                }
            }
            parked.push((wi, delivery));
        }
        // Parked items are progress-ACKed, so JetStream never redelivers
        // them on its own; bound the wait by the envelope it would give an
        // unacknowledged message instead.
        let ready_deadline =
            tokio::time::Instant::now() + crate::nats_consumer::redelivery_envelope();
        let this = Arc::clone(self);
        let model = model_id.to_string();
        let handle = tokio::spawn(async move {
            if !overflow.is_empty() {
                info!(
                    model = %model,
                    overflow = overflow.len(),
                    "parked-item capacity exhausted while the model loads — NAKing overflow"
                );
                nak_all(
                    &overflow,
                    base_nak_delay_ms(),
                    &this.runtime_state.telemetry,
                )
                .await;
            }
            if parked.is_empty() {
                return;
            }
            if let Err(e) = this
                .handle_model_group(&model, parked, Some(ready_deadline))
                .await
            {
                warn!(model = %model, error = %ErrChain(&e), "parked model group handling failed");
            }
        });
        let mut handles = self
            .parked_group_handles
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        handles.retain(|h| !h.is_finished());
        handles.push(handle);
    }

    /// `EnsureModelReady` for `items`. A parked group's call is bounded by its
    /// readiness deadline and progress-ACKs the group while it is pending, so
    /// a slow call neither outlives the deadline nor lets JetStream redeliver
    /// the group. `None` when the group was NAKed instead: the worker lists the
    /// model in `unsupported_models` (a config commit can add it after
    /// intake), the deadline passed first, a progress ACK failed, or shutdown
    /// requested redelivery.
    async fn ensure_model_ready_by(
        &self,
        model_id: &str,
        items: &[(WorkItem, Delivery)],
        ready_wait: Option<&mut ModelReadinessWait>,
    ) -> Option<Result<crate::ipc_types::EnsureModelReadyResponse, BackendError>> {
        if self.model_is_unsupported(model_id) {
            info!(
                model = %model_id,
                group_size = items.len(),
                "worker cannot serve this model under its current config — NAKing group before readiness"
            );
            for (_, delivery) in items {
                nak_one_with_reason(
                    delivery,
                    base_nak_delay_ms(),
                    &self.runtime_state.telemetry,
                    "model_unsupported",
                )
                .await;
            }
            return None;
        }
        let readiness = self.backend.ensure_model_ready(model_id);
        let Some(ready_wait) = ready_wait else {
            return Some(readiness.await);
        };
        self.wait_during_model_loading(model_id, items, ready_wait, readiness)
            .await
    }

    async fn wait_during_model_loading<T>(
        &self,
        model_id: &str,
        items: &[(WorkItem, Delivery)],
        ready_wait: &mut ModelReadinessWait,
        operation: impl Future<Output = T>,
    ) -> Option<T> {
        tokio::pin!(operation);
        loop {
            let shutdown_wait = async {
                match self.shutdown.as_ref() {
                    Some(shutdown) => shutdown.wait().await,
                    None => std::future::pending().await,
                }
            };
            tokio::select! {
                biased;
                () = shutdown_wait => {
                    nak_all(items, NAK_DELAY_DRAINING_MS, &self.runtime_state.telemetry).await;
                    return None;
                }
                () = tokio::time::sleep_until(ready_wait.deadline) => {
                    self.nak_group_past_ready_deadline(model_id, items).await;
                    return None;
                }
                () = tokio::time::sleep_until(ready_wait.next_progress) => {
                    if !progress_all(items, &self.runtime_state.telemetry).await {
                        nak_all(items, base_nak_delay_ms(), &self.runtime_state.telemetry).await;
                        return None;
                    }
                    ready_wait.next_progress =
                        tokio::time::Instant::now() + MODEL_READINESS_PROGRESS_INTERVAL;
                }
                result = &mut operation => return Some(result),
            }
        }
    }

    async fn nak_group_past_ready_deadline(&self, model_id: &str, items: &[(WorkItem, Delivery)]) {
        info!(
            model = %model_id,
            group_size = items.len(),
            "model not ready within the parked readiness wait — NAKing group"
        );
        nak_all(items, base_nak_delay_ms(), &self.runtime_state.telemetry).await;
    }

    async fn handle_model_group(
        self: &Arc<Self>,
        model_id: &str,
        items: Vec<(WorkItem, Delivery)>,
        ready_deadline: Option<tokio::time::Instant>,
    ) -> Result<(), DispatchError> {
        let items = self
            .retain_uncancelled(items, "before_model_readiness")
            .await;
        let mut items = self.answer_stale_admissions(items).await;
        if items.is_empty() {
            return Ok(());
        }
        let group_started = Instant::now();
        let group_size = items.len();
        let base_delay_ms = base_nak_delay_ms();
        let mut ready_wait = ready_deadline.map(ModelReadinessWait::new);
        if items.iter().any(|(wi, delivery)| {
            delivery.requires_execution_authority_v1()
                && (!delivery.execution_authority_model_matches(&wi.model_id)
                    || !self.execution_authority_is_available(wi, true))
        }) {
            nak_all(&items, base_delay_ms, &self.runtime_state.telemetry).await;
            return Ok(());
        }
        if let Some((expected_hash, unknown_hash_count)) = unknown_bundle_config_hash(
            items.iter().map(|(wi, _)| wi),
            self.config_apply_state.as_deref(),
        ) {
            let local_hash = self.current_bundle_config_hash().unwrap_or_default();
            info!(
                model = %model_id,
                unknown_hash_count,
                group_size,
                local_hash = %local_hash,
                expected_hash,
                "request bundle config hash is unknown locally, or the model is unsupported — NAKing group"
            );
            nak_all_at_barrier(
                &items,
                base_delay_ms,
                &self.runtime_state.telemetry,
                self.config_apply_state.as_deref(),
            )
            .await;
            return Ok(());
        }
        let readiness_started = Instant::now();
        let readiness_resp = loop {
            items = self.retain_uncancelled(items, "model_readiness").await;
            items = self.answer_stale_admissions(items).await;
            if items.is_empty() {
                return Ok(());
            }
            let Some(readiness) = self
                .ensure_model_ready_by(model_id, &items, ready_wait.as_mut())
                .await
            else {
                return Ok(());
            };
            let readiness_resp = match readiness {
                Ok(r) => r,
                Err(e) => {
                    warn!(
                        model = %model_id,
                        group_size,
                        error = %ErrChain(&e),
                        "EnsureModelReady failed — NAKing group"
                    );
                    nak_all(&items, base_delay_ms, &self.runtime_state.telemetry).await;
                    return Err(e.into());
                }
            };
            if readiness_resp.state == ReadinessState::Ready {
                break readiness_resp;
            }
            if readiness_resp.state == ReadinessState::Failed {
                // Terminal load failure (permanent cooldown on the Python
                // registry). Re-driving `EnsureModelReady` would loop forever
                // and hang the client, so dead-letter
                // the whole group as `MODEL_LOAD_FAILED` — the gateway maps
                // that code to a typed 502, exactly like the batch/`run_batch`
                // path. ACK each item after publishing its error so JetStream
                // stops redelivering the doomed work.
                info!(
                    model = %model_id,
                    group_size,
                    "model load failed terminally — dead-lettering group as MODEL_LOAD_FAILED"
                );
                self.dead_letter_all(&items, model_id).await;
                return Ok(());
            }
            if matches!(
                readiness_resp.state,
                ReadinessState::LoadingStarted | ReadinessState::LoadingInProgress
            ) {
                let Some(ready_wait) = ready_wait.as_mut() else {
                    self.park_model_group(model_id, items);
                    return Ok(());
                };
                debug!(
                    model = %model_id,
                    group_size,
                    readiness = ?readiness_resp.state,
                    "model loading — waiting before readiness probe"
                );
                if self
                    .wait_during_model_loading(
                        model_id,
                        &items,
                        ready_wait,
                        tokio::time::sleep(MODEL_READINESS_POLL_INTERVAL),
                    )
                    .await
                    .is_none()
                {
                    return Ok(());
                }
                continue;
            }
            info!(model = %model_id, "model not available — NAKing group");
            nak_all(&items, base_delay_ms, &self.runtime_state.telemetry).await;
            return Ok(());
        };

        let readiness_finished = Instant::now();

        // A parked group's last progress ACK may be a full readiness delay
        // old; refresh it so the batch-permit wait starts from a full ACK wait.
        if ready_deadline.is_some() && !progress_all(&items, &self.runtime_state.telemetry).await {
            nak_all(&items, base_delay_ms, &self.runtime_state.telemetry).await;
            return Ok(());
        }
        let batch_permit_started = Instant::now();
        let Ok(_batch_permit) = self.batch_semaphore.acquire().await else {
            warn!(model = %model_id, "batch semaphore closed — dropping group");
            return Ok(());
        };
        let batch_permit_acquired = Instant::now();
        let _inflight_batch = self
            .scheduler_registry
            .is_none()
            .then(|| InflightBatchGuard::enter(Arc::clone(&self.runtime_state)));

        items = self
            .retain_uncancelled(items, "after_model_readiness")
            .await;
        if items.is_empty() {
            return Ok(());
        }

        // Adapter handshake: fold the adapter's `ModelDescriptor`
        // (if any) into our local registries. Idempotent on
        // re-handshake — the registry hashes the loaded
        // tokenizer.json and short-circuits if the declared
        // `tokenizer_id` already matches what's cached.
        self.record_dispatch_width(model_id, readiness_resp.descriptor.as_ref());
        if let Some(descriptor) = readiness_resp.descriptor.as_ref() {
            match self
                .tokenizer_registry
                .register_from_descriptor(model_id, descriptor)
            {
                Ok(true) => {
                    debug!(
                        model = %model_id,
                        "rust-tokenize: registered tokeniser from EnsureModelReady descriptor"
                    );
                }
                Ok(false) => {} // no path, idempotent, or hash mismatch (warning logged inside)
                Err(e) => {
                    // Non-fatal: model just falls back to Python
                    // tokenisation, exactly the same as if no
                    // descriptor had been declared at all.
                    warn!(
                        model = %model_id,
                        error = %e,
                        "rust-tokenize: descriptor load failed — Python will tokenise this model"
                    );
                }
            }
        }

        // Cap the group at the per-model batch budget reported by Python.
        // Overflow gets NAK'd with a short delay so it redelivers to
        // (possibly) another worker — keeps one hot model from starving
        // the others on this worker's GPU.
        let budget = readiness_resp
            .batch_budget
            .filter(|&b| b > 0)
            .unwrap_or_else(default_batch_budget) as usize;
        let (dispatch, overflow) = split_by_budget(items, budget);
        if !overflow.is_empty() {
            debug!(
                model = %model_id,
                budget,
                overflow = overflow.len(),
                "fair dispatch: NAKing overflow"
            );
            nak_all(
                &overflow,
                NAK_DELAY_OVERFLOW_MS,
                &self.runtime_state.telemetry,
            )
            .await;
        }
        if dispatch.is_empty() {
            return Ok(());
        }
        // Fan out by operation; each op runs concurrently below. The IPC
        // client serialises at the socket but payload resolution, NATS
        // ACKs and publishes all overlap across ops.
        let mut encode_items = Vec::new();
        let mut score_items = Vec::new();
        let mut extract_items = Vec::new();
        let mut unknown_items: Vec<(WorkItem, Delivery)> = Vec::new();
        for (wi, delivery) in dispatch {
            match wi.operation.as_str() {
                "encode" => encode_items.push((wi, delivery)),
                "score" => score_items.push((wi, delivery)),
                "extract" => extract_items.push((wi, delivery)),
                // The model is ready by now, which is all a load asks for.
                LOAD_OPERATION => {
                    debug!(model = %model_id, "load-only work item: model ready");
                    if let Err(e) = ack(&delivery, &self.runtime_state.telemetry).await {
                        warn!(error = %e, "ack of a load-only work item failed");
                    }
                }
                _ => unknown_items.push((wi, delivery)),
            }
        }

        for (wi, delivery) in &unknown_items {
            warn!(op = %wi.operation, "unknown operation — publishing error + ACK");
            match self
                .publish_error(wi, delivery, "bad_operation", "unknown operation")
                .await
            {
                Ok(_) => match ack(delivery, &self.runtime_state.telemetry).await {
                    Ok(()) => {}
                    Err(e) => {
                        warn!(error = %e, "ack after bad_operation error-publish failed");
                    }
                },
                Err(_) => {
                    // Error publish failed — NAK so JetStream redelivers
                    // and we get another chance to either succeed or hit
                    // max_deliver → DLQ (preserves the failure rather
                    // than silently dropping it).
                    nak_one(delivery, base_nak_delay_ms(), &self.runtime_state.telemetry).await;
                }
            }
        }

        let encode_n = encode_items.len();
        let score_n = score_items.len();
        let extract_n = extract_items.len();
        let unknown_n = unknown_items.len();

        // When `scheduler_registry` is wired, every op routes through
        // the scheduler's submit-then-drain path instead of the per-op
        // `process_*_batch` path. The scheduler owns batch formation +
        // adaptive control and hands flushed batches to the backend via
        // `run_batch`; the per-model drain loop (spawned lazily on first
        // traffic inside [`Self::resolve_scheduler`]) handles inference
        // + publish + ACK/NAK.
        //
        // Registry absent ⇒ legacy path unchanged. Only unit tests
        // exercise that branch today.
        let scheduler_opt = self
            .resolve_scheduler(model_id, readiness_resp.max_batch_tokens)
            .await;
        let encode_fut = async {
            if encode_items.is_empty() {
                return Ok(());
            }
            if let Some(sched) = scheduler_opt.as_ref() {
                self.enqueue_encode_into_scheduler(model_id, sched, encode_items)
                    .await;
                return Ok(());
            }
            self.handle_encode(model_id, encode_items).await
        };
        let score_fut = async {
            if score_items.is_empty() {
                return Ok(());
            }
            if let Some(sched) = scheduler_opt.as_ref() {
                self.enqueue_score_into_scheduler(model_id, sched, score_items)
                    .await;
                return Ok(());
            }
            self.handle_score(model_id, score_items).await
        };
        let extract_fut = async {
            if extract_items.is_empty() {
                return Ok(());
            }
            if let Some(sched) = scheduler_opt.as_ref() {
                self.enqueue_extract_into_scheduler(model_id, sched, extract_items)
                    .await;
                return Ok(());
            }
            self.handle_extract(model_id, extract_items).await
        };
        let (r_enc, r_score, r_ext) = tokio::join!(encode_fut, score_fut, extract_fut);
        let prepare_dispatch_finished = Instant::now();
        if let Err(e) = &r_enc {
            warn!(model = %model_id, error = %ErrChain(e), "encode batch failed");
        }
        if let Err(e) = &r_score {
            warn!(model = %model_id, error = %ErrChain(e), "score batch failed");
        }
        if let Err(e) = &r_ext {
            warn!(model = %model_id, error = %ErrChain(e), "extract batch failed");
        }
        info!(
            model = %model_id,
            group_size,
            encode = encode_n,
            score = score_n,
            extract = extract_n,
            unknown = unknown_n,
            encode_ok = r_enc.is_ok(),
            score_ok = r_score.is_ok(),
            extract_ok = r_ext.is_ok(),
            elapsed_ms = group_started.elapsed().as_millis() as u64,
            model_readiness_elapsed_ms = phase_elapsed_ms(readiness_started, readiness_finished),
            batch_permit_elapsed_ms = phase_elapsed_ms(batch_permit_started, batch_permit_acquired),
            prepare_dispatch_elapsed_ms =
                phase_elapsed_ms(batch_permit_acquired, prepare_dispatch_finished),
            "handle_model_group: done"
        );
        Ok(())
    }

    /// Answer admitted items instead of sending them through a method that
    /// never re-verifies a numerical admission.
    async fn refuse_admitted_items(
        &self,
        items: Vec<(WorkItem, Delivery)>,
    ) -> Vec<(WorkItem, Delivery)> {
        let mut kept = Vec::with_capacity(items.len());
        for (wi, delivery) in items {
            if wi.numerical_admission_sha256.is_none() {
                kept.push((wi, delivery));
                continue;
            }
            self.refuse_violation(&wi, &delivery).await;
        }
        kept
    }

    // -- encode -----------------------------------------------------------

    async fn handle_encode(
        &self,
        model_id: &str,
        items: Vec<(WorkItem, Delivery)>,
    ) -> Result<(), DispatchError> {
        let items = self.refuse_admitted_items(items).await;
        let mut resolved: Vec<(WorkItem, Delivery, MsgValue, f64, Option<String>)> =
            Vec::with_capacity(items.len());
        for (wi, delivery) in items {
            if self
                .settle_if_cancelled(&wi, &delivery, "before_payload_fetch")
                .await
            {
                continue;
            }
            let (item_json, fetch_ms) = match self.resolve_item(&wi).await {
                Ok(v) => v,
                Err(e) => {
                    warn!(
                        error = %ErrChain(&e),
                        work_item_id = %wi.work_item_id,
                        request_id = %wi.request_id,
                        model = %wi.model_id,
                        "failed to resolve encode item"
                    );
                    let (code, message) = payload_error_contract(&e);
                    match self.publish_error(&wi, &delivery, code, message).await {
                        Ok(_) => match ack(&delivery, &self.runtime_state.telemetry).await {
                            Ok(()) => {}
                            Err(e) => {
                                warn!(error = %e, "ack after error-publish failed");
                            }
                        },
                        Err(_) => {
                            // NATS publish failed — NAK so redelivery
                            // gives another attempt (or surfaces the
                            // error later). Swallowed publish errors
                            // would otherwise silently drop the item.
                            nak_one(
                                &delivery,
                                base_nak_delay_ms(),
                                &self.runtime_state.telemetry,
                            )
                            .await;
                        }
                    }
                    continue;
                }
            };
            if self
                .settle_if_cancelled(&wi, &delivery, "after_payload_fetch")
                .await
            {
                continue;
            }
            let caller_item_id = caller_item_id_from_value(&item_json);
            resolved.push((wi, delivery, item_json, fetch_ms, caller_item_id));
        }
        if resolved.is_empty() {
            return Ok(());
        }

        let _execution_guard = if let Some(state) = self.config_apply_state.as_ref() {
            Some(state.lock_execution().await)
        } else {
            None
        };
        if let Some((expected_hash, unknown_hash_count)) = unknown_bundle_config_hash(
            resolved.iter().map(|(wi, _, _, _, _)| wi),
            self.config_apply_state.as_deref(),
        ) {
            info!(
                model = %model_id,
                expected_hash,
                unknown_hash_count,
                local_hash = %self.config_apply_state.as_ref().map(|state| state.current_bundle_config_hash()).unwrap_or_default(),
                "encode work refused at the config barrier before execution — NAKing"
            );
            let msgs_only: Vec<(WorkItem, Delivery)> = resolved
                .into_iter()
                .map(|(wi, delivery, _, _, _)| (wi, delivery))
                .collect();
            nak_all_at_barrier(
                &msgs_only,
                base_nak_delay_ms(),
                &self.runtime_state.telemetry,
                self.config_apply_state.as_deref(),
            )
            .await;
            return Ok(());
        }

        let mut active = Vec::with_capacity(resolved.len());
        for item in resolved {
            if self
                .settle_if_cancelled(&item.0, &item.1, "before_ipc")
                .await
            {
                continue;
            }
            active.push(item);
        }
        let resolved = active;
        if resolved.is_empty() {
            return Ok(());
        }
        record_work_item_ages(
            &self.runtime_state.telemetry,
            resolved.iter().map(|(wi, _, _, _, _)| wi),
        );

        let batch_items: Vec<EncodeBatchItem> = resolved
            .iter()
            .map(|(wi, _msg, item, fm, _caller_item_id)| {
                let prepared_tokens = self.maybe_prepare_encode_tokens(model_id, wi, item);
                EncodeBatchItem {
                    work_item_id: wi.work_item_id.clone(),
                    request_id: wi.request_id.clone(),
                    item_index: wi.item_index,
                    total_items: wi.total_items,
                    timestamp: wi.timestamp,
                    item: item.clone(),
                    output_types: wi.output_types.clone(),
                    instruction: wi.instruction.clone(),
                    is_query: wi.is_query,
                    options: wi.options.clone(),
                    profile_id: opt_non_empty(&wi.profile_id),
                    bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
                    numerical_admission_sha256: None,
                    payload_fetch_ms: *fm,
                    prepared_tokens,
                }
            })
            .collect();

        let outcome = match self
            .backend
            .process_encode_batch(ProcessEncodeBatchRequest {
                model_id: model_id.to_string(),
                items: batch_items,
                accepts_batched_f16_multivectors: true,
            })
            .await
        {
            Ok(o) => o,
            Err(e) => {
                let delay = nak_delay_for_backend_error(&e);
                warn!(
                    model = %model_id,
                    error = %ErrChain(&e),
                    nak_delay_ms = delay,
                    batch_size = resolved.len(),
                    "ProcessEncodeBatch failed — NAKing group"
                );
                let msgs_only: Vec<(WorkItem, Delivery)> = resolved
                    .into_iter()
                    .map(|(wi, m, _, _, _)| (wi, m))
                    .collect();
                nak_all(&msgs_only, delay, &self.runtime_state.telemetry).await;
                return Err(e.into());
            }
        };

        self.apply_outcomes(
            outcome,
            resolved
                .into_iter()
                .map(|(wi, m, _, fm, caller_item_id)| (wi, m, fm, caller_item_id))
                .collect(),
        )
        .await;
        Ok(())
    }

    // -- score ------------------------------------------------------------

    async fn handle_score(
        &self,
        model_id: &str,
        items: Vec<(WorkItem, Delivery)>,
    ) -> Result<(), DispatchError> {
        let items = self.refuse_admitted_items(items).await;
        let mut prepared: Vec<(WorkItem, Delivery, MsgValue, Vec<MsgValue>, f64)> =
            Vec::with_capacity(items.len());
        for (wi, delivery) in items {
            if self
                .settle_if_cancelled(&wi, &delivery, "before_payload_fetch")
                .await
            {
                continue;
            }
            let (query, score_items, fetch_ms) = match self.resolve_score(&wi).await {
                Ok(v) => v,
                Err(e) => {
                    warn!(
                        error = %ErrChain(&e),
                        work_item_id = %wi.work_item_id,
                        request_id = %wi.request_id,
                        model = %wi.model_id,
                        "failed to resolve score payload"
                    );
                    let (code, message) = payload_error_contract(&e);
                    match self.publish_error(&wi, &delivery, code, message).await {
                        Ok(_) => match ack(&delivery, &self.runtime_state.telemetry).await {
                            Ok(()) => {}
                            Err(e) => {
                                warn!(error = %e, "ack after error-publish failed");
                            }
                        },
                        Err(_) => {
                            nak_one(
                                &delivery,
                                base_nak_delay_ms(),
                                &self.runtime_state.telemetry,
                            )
                            .await;
                        }
                    }
                    continue;
                }
            };
            if self
                .settle_if_cancelled(&wi, &delivery, "after_payload_fetch")
                .await
            {
                continue;
            }
            prepared.push((wi, delivery, query, score_items, fetch_ms));
        }
        if prepared.is_empty() {
            return Ok(());
        }

        let _execution_guard = if let Some(state) = self.config_apply_state.as_ref() {
            Some(state.lock_execution().await)
        } else {
            None
        };
        if let Some((expected_hash, unknown_hash_count)) = unknown_bundle_config_hash(
            prepared.iter().map(|(wi, _, _, _, _)| wi),
            self.config_apply_state.as_deref(),
        ) {
            info!(
                model = %model_id,
                expected_hash,
                unknown_hash_count,
                local_hash = %self.config_apply_state.as_ref().map(|state| state.current_bundle_config_hash()).unwrap_or_default(),
                "score work refused at the config barrier before execution — NAKing"
            );
            let msgs_only: Vec<(WorkItem, Delivery)> = prepared
                .into_iter()
                .map(|(wi, delivery, _, _, _)| (wi, delivery))
                .collect();
            nak_all_at_barrier(
                &msgs_only,
                base_nak_delay_ms(),
                &self.runtime_state.telemetry,
                self.config_apply_state.as_deref(),
            )
            .await;
            return Ok(());
        }

        let mut active = Vec::with_capacity(prepared.len());
        for item in prepared {
            if self
                .settle_if_cancelled(&item.0, &item.1, "before_ipc")
                .await
            {
                continue;
            }
            active.push(item);
        }
        let prepared = active;
        if prepared.is_empty() {
            return Ok(());
        }
        record_work_item_ages(
            &self.runtime_state.telemetry,
            prepared.iter().map(|(wi, _, _, _, _)| wi),
        );

        // Rust-tokenisation wire-noop on score: Python's
        // `_process_single_score` does not consume `prepared_tokens`
        // — the cross-encoder adapter tokenises query+doc pairs
        // internally using model-specific pair-building policy
        // (`[CLS] q [SEP] d [SEP]`, pair padding, etc.) that lives
        // adapter-side. We always set `prepared_tokens = None` here
        // so the Python path stays the source of truth. See the
        // score-path note in `docs/architecture-guide.md`.
        let batch_items: Vec<ScoreBatchItem> = prepared
            .iter()
            .map(|(wi, _, q, it, fm)| ScoreBatchItem {
                work_item_id: wi.work_item_id.clone(),
                request_id: wi.request_id.clone(),
                item_index: wi.item_index,
                total_items: wi.total_items,
                timestamp: wi.timestamp,
                query_item: q.clone(),
                score_items: it.clone(),
                instruction: wi.instruction.clone(),
                options: wi.options.clone(),
                profile_id: opt_non_empty(&wi.profile_id),
                bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
                numerical_admission_sha256: None,
                payload_fetch_ms: *fm,
                prepared_tokens: None,
            })
            .collect();

        let outcome = match self
            .backend
            .process_score_batch(ProcessScoreBatchRequest {
                model_id: model_id.to_string(),
                items: batch_items,
            })
            .await
        {
            Ok(o) => o,
            Err(e) => {
                let delay = nak_delay_for_backend_error(&e);
                warn!(
                    model = %model_id,
                    error = %ErrChain(&e),
                    nak_delay_ms = delay,
                    batch_size = prepared.len(),
                    "ProcessScoreBatch failed — NAKing group"
                );
                let msgs_only: Vec<(WorkItem, Delivery)> = prepared
                    .into_iter()
                    .map(|(wi, m, _, _, _)| (wi, m))
                    .collect();
                nak_all(&msgs_only, delay, &self.runtime_state.telemetry).await;
                return Err(e.into());
            }
        };

        self.apply_outcomes(
            outcome,
            prepared
                .into_iter()
                .map(|(wi, m, _, _, fm)| (wi, m, fm, None))
                .collect(),
        )
        .await;
        Ok(())
    }

    // -- extract ----------------------------------------------------------

    async fn handle_extract(
        &self,
        model_id: &str,
        items: Vec<(WorkItem, Delivery)>,
    ) -> Result<(), DispatchError> {
        let mut resolved: Vec<(
            WorkItem,
            Delivery,
            MsgValue,
            Option<PreparedAudioPcm16>,
            f64,
        )> = Vec::with_capacity(items.len());
        for (wi, delivery) in items {
            if self
                .settle_if_cancelled(&wi, &delivery, "before_payload_fetch")
                .await
            {
                continue;
            }
            if let Some(item) = &wi.item {
                if let Err(err) = validate_item_media(item) {
                    self.fail_invalid_media(&wi, &delivery, &err).await;
                    continue;
                }
            }
            let (item_json, fetch_ms) = match self.resolve_item(&wi).await {
                Ok(v) => v,
                Err(e) => {
                    warn!(
                        error = %ErrChain(&e),
                        work_item_id = %wi.work_item_id,
                        request_id = %wi.request_id,
                        model = %wi.model_id,
                        "failed to resolve extract item"
                    );
                    let (code, message) = payload_error_contract(&e);
                    match self.publish_error(&wi, &delivery, code, message).await {
                        Ok(_) => match ack(&delivery, &self.runtime_state.telemetry).await {
                            Ok(()) => {}
                            Err(e) => {
                                warn!(error = %e, "ack after error-publish failed");
                            }
                        },
                        Err(_) => {
                            nak_one(
                                &delivery,
                                base_nak_delay_ms(),
                                &self.runtime_state.telemetry,
                            )
                            .await;
                        }
                    }
                    continue;
                }
            };
            if self
                .settle_if_cancelled(&wi, &delivery, "after_payload_fetch")
                .await
            {
                continue;
            }
            if wi.item.is_none() {
                if let Err(err) = validate_item_media(&item_json) {
                    self.fail_invalid_media(&wi, &delivery, &err).await;
                    continue;
                }
            }
            let (item_json, prepared_audio) =
                match prepare_extract_audio(item_json, &self.audio_prep_semaphore).await {
                    Ok(prepared) => prepared,
                    Err(error) => {
                        self.fail_invalid_audio(&wi, &delivery, &error).await;
                        continue;
                    }
                };
            resolved.push((wi, delivery, item_json, prepared_audio, fetch_ms));
        }
        if resolved.is_empty() {
            return Ok(());
        }

        let _execution_guard = if let Some(state) = self.config_apply_state.as_ref() {
            Some(state.lock_execution().await)
        } else {
            None
        };
        if let Some((expected_hash, unknown_hash_count)) = unknown_bundle_config_hash(
            resolved.iter().map(|(wi, _, _, _, _)| wi),
            self.config_apply_state.as_deref(),
        ) {
            info!(
                model = %model_id,
                expected_hash,
                unknown_hash_count,
                local_hash = %self.config_apply_state.as_ref().map(|state| state.current_bundle_config_hash()).unwrap_or_default(),
                "extract work refused at the config barrier before execution — NAKing"
            );
            let msgs_only: Vec<(WorkItem, Delivery)> = resolved
                .into_iter()
                .map(|(wi, delivery, _, _, _)| (wi, delivery))
                .collect();
            nak_all_at_barrier(
                &msgs_only,
                base_nak_delay_ms(),
                &self.runtime_state.telemetry,
                self.config_apply_state.as_deref(),
            )
            .await;
            return Ok(());
        }

        let mut active = Vec::with_capacity(resolved.len());
        for item in resolved {
            if self
                .settle_if_cancelled(&item.0, &item.1, "before_ipc")
                .await
            {
                continue;
            }
            active.push(item);
        }
        let mut resolved = active;
        if resolved.is_empty() {
            return Ok(());
        }
        record_work_item_ages(
            &self.runtime_state.telemetry,
            resolved.iter().map(|(wi, _, _, _, _)| wi),
        );

        let mut batch_items = Vec::with_capacity(resolved.len());
        for (wi, _, item, prepared_audio, fm) in &mut resolved {
            batch_items.push(ExtractBatchItem {
                work_item_id: wi.work_item_id.clone(),
                request_id: wi.request_id.clone(),
                item_index: wi.item_index,
                total_items: wi.total_items,
                timestamp: wi.timestamp,
                item: std::mem::replace(item, MsgValue::Map(Vec::new())),
                labels: wi.labels.clone(),
                output_schema: wi.output_schema.clone(),
                instruction: wi.instruction.clone(),
                options: wi.options.clone(),
                profile_id: opt_non_empty(&wi.profile_id),
                bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
                payload_fetch_ms: *fm,
                prepared_audio: prepared_audio.take(),
            });
        }

        let outcome = match self
            .backend
            .process_extract_batch(ProcessExtractBatchRequest {
                model_id: model_id.to_string(),
                items: batch_items,
            })
            .await
        {
            Ok(o) => o,
            Err(e) => {
                let delay = nak_delay_for_backend_error(&e);
                warn!(
                    model = %model_id,
                    error = %ErrChain(&e),
                    nak_delay_ms = delay,
                    batch_size = resolved.len(),
                    "ProcessExtractBatch failed — NAKing group"
                );
                let msgs_only: Vec<(WorkItem, Delivery)> = resolved
                    .into_iter()
                    .map(|(wi, m, _, _, _)| (wi, m))
                    .collect();
                nak_all(&msgs_only, delay, &self.runtime_state.telemetry).await;
                return Err(e.into());
            }
        };

        self.apply_outcomes(
            outcome,
            resolved
                .into_iter()
                .map(|(wi, m, _, _, fm)| (wi, m, fm, None))
                .collect(),
        )
        .await;
        Ok(())
    }

    // -- outcome / publish helpers ---------------------------------------

    async fn apply_outcomes(&self, outcome: BatchOutcome, resolved: Vec<ResolvedWorkItem>) {
        let BatchOutcome {
            outcomes,
            batched_f16_multivectors,
        } = outcome;
        let mut batched_f16_by_work_item_id =
            index_batched_f16_multivectors(&batched_f16_multivectors);
        // Decide which index (if any) each outcome binds to, using the
        // pure `resolve_outcome_indices` helper. Indices are into
        // `resolved`; `None` means "ghost outcome, no matching item".
        let wiids: Vec<&str> = resolved
            .iter()
            .map(|(wi, _, _, _)| wi.work_item_id.as_str())
            .collect();
        let bindings =
            resolve_outcome_indices(&wiids, outcomes.iter().map(|o| o.work_item_id.as_str()));

        let mut resolved: Vec<Option<ResolvedWorkItem>> = resolved.into_iter().map(Some).collect();

        for (outcome_idx, item_outcome) in outcomes.into_iter().enumerate() {
            let Some(idx) = bindings[outcome_idx] else {
                warn!(
                    work_item_id = %item_outcome.work_item_id,
                    "outcome for unknown or already-consumed work_item_id — ignoring"
                );
                continue;
            };
            let Some((wi, delivery, fetch_ms, caller_item_id)) = resolved[idx].take() else {
                continue;
            };
            let owned;
            let effective_outcome =
                match batched_f16_by_work_item_id.remove(item_outcome.work_item_id.as_str()) {
                    Some(Ok(multivector)) => {
                        owned = shape_batched_f16_multivector_outcome(
                            &item_outcome,
                            multivector.values_f16,
                            multivector.num_tokens,
                            multivector.token_dims,
                            caller_item_id.as_deref(),
                        );
                        &owned
                    }
                    Some(Err(message)) => {
                        owned = batched_f16_multivector_error_outcome(&item_outcome, &message);
                        &owned
                    }
                    None => &item_outcome,
                };
            self.apply_outcome(
                &wi,
                &delivery,
                effective_outcome,
                fetch_ms,
                caller_item_id.as_deref(),
            )
            .await;
        }

        for (work_item_id, _) in batched_f16_by_work_item_id {
            warn!(
                work_item_id,
                "batched f16 multivector had no matching outcome — ignoring"
            );
        }

        // Any messages left without a corresponding outcome: the executor
        // dropped them. NAK so they get redelivered.
        for slot in resolved.iter_mut() {
            let Some((_wi, delivery, _fm, _caller_item_id)) = slot.take() else {
                continue;
            };
            warn!(
                origin = %delivery.log_ref(),
                "no outcome from executor — NAKing"
            );
            nak_one(
                &delivery,
                base_nak_delay_ms(),
                &self.runtime_state.telemetry,
            )
            .await;
        }
    }

    async fn apply_outcome(
        &self,
        wi: &WorkItem,
        delivery: &Delivery,
        outcome: &ItemOutcome,
        payload_fetch_ms: f64,
        caller_item_id: Option<&str>,
    ) {
        match outcome.disposition {
            Disposition::PublishAndAck | Disposition::PublishErrorAndAck => {
                if should_publish(&outcome.disposition) {
                    let queue_ms = queue_ms_from(wi.timestamp);
                    // NOTE: `sie.worker.work_item.age` is NOT recorded here.
                    // It is recorded at each execution-commit point (see
                    // [`record_work_item_ages`]) so that every operation shares
                    // one definition and generation, which never reaches this
                    // function, is not silently missing from the distribution.
                    let timings = Some(Timings {
                        queue_ms,
                        payload_fetch_ms,
                    });
                    match self
                        .deliver_result(wi, delivery, outcome, timings, caller_item_id)
                        .await
                    {
                        Ok(()) => {
                            // Record latency only on the success path —
                            // sampling error-path latency would bias the
                            // FetchExpiry controller toward shrinking the
                            // pull-loop quantum.
                            //
                            // By default `queue_ms_from(wi.timestamp)`
                            // (gateway-publish → NATS-pull) is **excluded**:
                            // including it would feed upstream queue depth
                            // into the tracker that drives the pull-loop
                            // quantum, collapsing the quantum to its floor
                            // under saturation even though the pull-loop
                            // itself isn't the bottleneck. Mirrors the semantics applied
                            // to the scheduler's adaptive-batch tracker
                            // (see `dispatch_batch_inner` per_item_total_ms).
                            //
                            // Operators can opt in to whole-path latency
                            // feedback (queue + inference + postprocess) via
                            // `SIE_PULL_QUANTUM_INCLUDE_QUEUE_MS=1`. See
                            // [`crate::pull_quantum_includes_queue_ms`] and
                            // `docs/architecture-guide.md`.
                            if matches!(outcome.disposition, Disposition::PublishAndAck) {
                                let inference_ms = outcome.inference_ms.unwrap_or(0.0);
                                let postprocess_ms = outcome.postprocessing_ms.unwrap_or(0.0);
                                let mut total = inference_ms + postprocess_ms;
                                if crate::pull_quantum_includes_queue_ms() {
                                    total += queue_ms;
                                }
                                self.latency_tracker.lock().await.record(total);
                            }
                        }
                        Err(crate::publisher::PublishError::EmptyReplySubject) => {
                            // Fire-and-forget work item — ACK anyway so
                            // JetStream doesn't redeliver forever.
                            debug!(
                                work_item_id = %wi.work_item_id,
                                "skipping publish — empty reply_subject; will still ACK"
                            );
                        }
                        Err(e) => {
                            // NATS publish failed — skip ACK so JetStream
                            // redelivers (caller may still NAK explicitly).
                            warn!(
                                work_item_id = %wi.work_item_id,
                                error = %e,
                                "failed to publish WorkResult — skipping ACK",
                            );
                            return;
                        }
                    }
                }
                match ack(delivery, &self.runtime_state.telemetry).await {
                    Ok(()) => {}
                    Err(e) => {
                        warn!(error = %e, "ack failed");
                    }
                }
            }
            Disposition::NakRetry => {
                let delay_ms = outcome.nak_delay_ms.unwrap_or_else(base_nak_delay_ms);
                if wi.fallback_reason.is_some() || wi.numerical_admission_sha256.is_some() {
                    let retry_after_s = outcome
                        .retry_after_s
                        .unwrap_or_else(|| delay_ms.div_ceil(1000).try_into().unwrap_or(u32::MAX));
                    self.refuse_fallback_attempt(
                        wi,
                        delivery,
                        outcome
                            .error_code
                            .as_deref()
                            .unwrap_or(QUEUE_FULL_ERROR_CODE),
                        retry_after_s,
                    )
                    .await;
                    return;
                }
                nak_one(delivery, delay_ms, &self.runtime_state.telemetry).await;
            }
        }
    }

    /// Answer an item that breaks the numerical admission contract and ACK it
    /// whatever the publish result: it can never become valid, and a NAK
    /// could hand it to a consumer without the fence.
    async fn refuse_violation(&self, wi: &WorkItem, delivery: &Delivery) {
        let mut outcome =
            synthetic_error_outcome(wi, INFERENCE_ERROR_CODE, FALLBACK_REFUSAL_MESSAGE);
        outcome.retry_after_s = Some(NUMERICAL_ADMISSION_RETRY_AFTER_S);
        if let Err(e) = self
            .deliver_result(wi, delivery, &outcome, None, None)
            .await
        {
            warn!(
                work_item_id = %wi.work_item_id,
                error = %e,
                "failed to publish a numerical admission refusal — ACKing anyway"
            );
        }
        if let Err(e) = ack(delivery, &self.runtime_state.telemetry).await {
            warn!(error = %e, "ack after a numerical admission refusal failed");
        }
    }

    /// Answer an admitted item whose configuration hash this worker no longer
    /// holds. Redelivery to the pinned worker rarely converges, and its
    /// bridged caller is waiting with a local refusal.
    async fn refuse_stale_admission(&self, wi: &WorkItem, delivery: &Delivery) {
        info!(
            work_item_id = %wi.work_item_id,
            model = %wi.model_id,
            "admitted work names a configuration this worker does not hold — answering"
        );
        self.refuse_fallback_attempt(
            wi,
            delivery,
            INFERENCE_ERROR_CODE,
            NUMERICAL_ADMISSION_RETRY_AFTER_S,
        )
        .await;
    }

    /// Answer the admitted items whose configuration hash is no longer
    /// current, and return the others.
    async fn answer_stale_admissions(
        &self,
        items: Vec<(WorkItem, Delivery)>,
    ) -> Vec<(WorkItem, Delivery)> {
        let mut kept = Vec::with_capacity(items.len());
        for (wi, delivery) in items {
            if wi.numerical_admission_sha256.is_some() && !self.execution_hash_is_current(&wi) {
                self.refuse_stale_admission(&wi, &delivery).await;
            } else {
                kept.push((wi, delivery));
            }
        }
        kept
    }

    /// Answer a work item the gateway sent to a remote profile in place of a
    /// refusing local route. The gateway is holding that local refusal for
    /// its caller, so a redelivery would only make the caller wait: the item
    /// is answered at once with a retryable error and ACKed. If the error
    /// cannot be published the item is NAKed, as for any failed publish.
    async fn refuse_fallback_attempt(
        &self,
        wi: &WorkItem,
        delivery: &Delivery,
        code: &str,
        retry_after_s: u32,
    ) {
        let mut outcome = synthetic_error_outcome(wi, code, FALLBACK_REFUSAL_MESSAGE);
        outcome.retry_after_s = Some(retry_after_s);
        match self
            .deliver_result(wi, delivery, &outcome, None, None)
            .await
        {
            Ok(()) | Err(crate::publisher::PublishError::EmptyReplySubject) => {
                if let Err(e) = ack(delivery, &self.runtime_state.telemetry).await {
                    warn!(error = %e, "ack after a fallback refusal failed");
                }
            }
            Err(e) => {
                warn!(
                    work_item_id = %wi.work_item_id,
                    error = %e,
                    "failed to publish a fallback refusal — NAKing"
                );
                nak_one(delivery, base_nak_delay_ms(), &self.runtime_state.telemetry).await;
            }
        }
    }

    /// Route one publishable outcome to its delivery-appropriate result
    /// sink: NATS reply-subject publish for [`Delivery::Nats`] (verbatim
    /// legacy behaviour, including the fire-and-forget empty-reply-subject
    /// contract), or an in-process [`crate::delivery::LocalDeliveryEvent`]
    /// for [`Delivery::Local`] — same `WorkResult` bytes either way via
    /// [`shape_and_build_work_result`].
    async fn deliver_result(
        &self,
        wi: &WorkItem,
        delivery: &Delivery,
        outcome: &ItemOutcome,
        timings: Option<Timings>,
        caller_item_id: Option<&str>,
    ) -> Result<(), crate::publisher::PublishError> {
        match delivery {
            Delivery::Nats(..) => {
                let Some(publisher) = self.publisher.as_ref() else {
                    // Unreachable by construction (`run()` wires NATS +
                    // publisher together); keep the item redeliverable
                    // rather than sinking it if the invariant ever breaks.
                    warn!(
                        work_item_id = %wi.work_item_id,
                        "NATS delivery without a publisher — skipping publish"
                    );
                    return Err(crate::publisher::PublishError::NoPublisher);
                };
                publisher
                    .publish_result(
                        &wi.reply_subject,
                        outcome,
                        PublishResultContext {
                            caller_item_id,
                            timings,
                            worker_direct: delivery.worker_direct(),
                            executed_bundle_config_hash: self.verified_execution_hash(wi),
                            accepts_result_chunks: wi.accepts_result_chunks,
                        },
                    )
                    .await
            }
            Delivery::Local(local) => {
                // reply_subject is NATS-only; local results always ride the
                // ingest socket back to the caller that is awaiting them.
                let result = shape_and_build_work_result(
                    outcome,
                    caller_item_id,
                    &self.worker_id,
                    timings,
                    delivery.worker_direct(),
                    self.verified_execution_hash(wi),
                );
                if !local.send_result(result) {
                    debug!(
                        work_item_id = %wi.work_item_id,
                        origin = %delivery.log_ref(),
                        "local ingest caller gone — dropping WorkResult"
                    );
                }
                Ok(())
            }
        }
    }

    /// Publish a synthetic error `WorkResult` on `wi.reply_subject`
    /// ([`Delivery::Nats`]) or straight to the local ingest caller
    /// ([`Delivery::Local`]).
    ///
    /// Returns:
    /// * `Ok(true)` — published (or fire-and-forget: empty reply_subject).
    ///   The caller may safely ACK the NATS message.
    /// * `Ok(false)` — (reserved) never returned today, kept for future
    ///   cases where the caller should NAK without logging.
    /// * `Err(_)` — NATS publish itself failed. The caller MUST NOT ACK:
    ///   the client never got the error reply, so we rely on redelivery
    ///   to give another worker (or this one, later) a chance to surface
    ///   the failure.
    async fn publish_error(
        &self,
        wi: &WorkItem,
        delivery: &Delivery,
        code: &str,
        message: &str,
    ) -> Result<bool, crate::publisher::PublishError> {
        let outcome = synthetic_error_outcome(wi, code, message);
        match self
            .deliver_result(wi, delivery, &outcome, None, None)
            .await
        {
            Ok(()) => Ok(true),
            Err(crate::publisher::PublishError::EmptyReplySubject) => {
                // Fire-and-forget work item. No one is waiting for the
                // error; ACKing lets JetStream drop it on the floor,
                // which is the right behaviour.
                debug!(work_item_id = %wi.work_item_id, "skipping error publish — empty reply_subject");
                Ok(true)
            }
            Err(e) => {
                warn!(
                    work_item_id = %wi.work_item_id,
                    error = %e,
                    "failed to publish error WorkResult"
                );
                Err(e)
            }
        }
    }

    /// Dead-letter a whole (op, model) group on a TERMINAL load failure:
    /// publish a typed `MODEL_LOAD_FAILED` error `WorkResult` for every item
    /// and ACK it. This is the [`ReadinessState::Failed`] fast-path twin of
    /// the batch/`run_batch` `MODEL_LOAD_FAILED` mapping — the gateway
    /// turns the code into an HTTP 502 so the client fails fast instead of
    /// blocking while the sidecar re-drives a doomed model forever.
    ///
    /// Per-item settlement mirrors [`Self::apply_outcome`] for a
    /// `PublishErrorAndAck` outcome: ACK once the error is published (or the
    /// item is fire-and-forget); if the NATS publish itself fails, NAK so
    /// JetStream redelivers and another attempt can surface the failure.
    async fn dead_letter_all(&self, items: &[(WorkItem, Delivery)], model_id: &str) {
        let message = format!("Model '{model_id}' failed to load permanently.");
        for (wi, delivery) in items {
            match self
                .publish_error(wi, delivery, MODEL_LOAD_FAILED_ERROR_CODE, &message)
                .await
            {
                Ok(_) => match ack(delivery, &self.runtime_state.telemetry).await {
                    Ok(()) => {}
                    Err(e) => {
                        warn!(
                            work_item_id = %wi.work_item_id,
                            error = %e,
                            "ack after MODEL_LOAD_FAILED publish failed"
                        );
                    }
                },
                Err(_) => {
                    // Publish failed — the client never got the typed error,
                    // so rely on redelivery rather than ACKing it away.
                    nak_one(delivery, base_nak_delay_ms(), &self.runtime_state.telemetry).await;
                }
            }
        }
        debug!(
            count = items.len(),
            model = %model_id,
            "dead-lettered group as MODEL_LOAD_FAILED"
        );
    }

    /// Generate-path twin of [`Self::publish_error`]. The generate flow is
    /// NATS-only (local-ingest generate items are rejected before reaching
    /// it, see [`Self::dispatch_decoded`]) and holds its [`Message`] in an
    /// `Arc` for the event stream, so it cannot wrap one into a
    /// [`Delivery`]; publish straight through the NATS publisher.
    async fn publish_error_generate(
        &self,
        wi: &WorkItem,
        code: &str,
        message: &str,
        worker_direct: bool,
    ) -> Result<bool, crate::publisher::PublishError> {
        let Some(publisher) = self.publisher.as_ref() else {
            return Err(crate::publisher::PublishError::NoPublisher);
        };
        let outcome = synthetic_error_outcome(wi, code, message);
        match publisher
            .publish_result(
                &wi.reply_subject,
                &outcome,
                PublishResultContext {
                    caller_item_id: None,
                    timings: None,
                    worker_direct,
                    executed_bundle_config_hash: None,
                    accepts_result_chunks: wi.accepts_result_chunks,
                },
            )
            .await
        {
            Ok(()) => Ok(true),
            Err(crate::publisher::PublishError::EmptyReplySubject) => {
                debug!(work_item_id = %wi.work_item_id, "skipping error publish — empty reply_subject");
                Ok(true)
            }
            Err(e) => {
                warn!(
                    work_item_id = %wi.work_item_id,
                    error = %e,
                    "failed to publish error WorkResult"
                );
                Err(e)
            }
        }
    }

    /// Publish a terminal generation chunk error on `wi.reply_subject`.
    ///
    /// Generation requests are tracked by the gateway's streaming collector, so
    /// a one-shot `WorkResult` would not unblock the client. Use the same chunk
    /// envelope Python's `StreamingProcessor` emits for terminal pre-execution
    /// errors.
    async fn publish_generate_terminal_error(
        &self,
        wi: &WorkItem,
        code: &str,
        message: &str,
    ) -> Result<bool, crate::publisher::PublishError> {
        if wi.reply_subject.is_empty() {
            debug!(
                work_item_id = %wi.work_item_id,
                "skipping generate terminal error publish — empty reply_subject"
            );
            return Ok(true);
        }
        let Some(publisher) = self.publisher.as_ref() else {
            return Err(crate::publisher::PublishError::NoPublisher);
        };
        let payload = encode_generate_terminal_error_chunk(wi, code, message)?;
        match publisher.publish_raw(&wi.reply_subject, payload).await {
            Ok(()) => Ok(true),
            Err(crate::publisher::PublishError::EmptyReplySubject) => {
                debug!(
                    work_item_id = %wi.work_item_id,
                    "skipping generate terminal error publish — empty reply_subject"
                );
                Ok(true)
            }
            Err(e) => {
                warn!(
                    work_item_id = %wi.work_item_id,
                    error = %e,
                    "failed to publish generate terminal error chunk"
                );
                Err(e)
            }
        }
    }

    // -- scheduler -------------------------------------------------------

    /// Return the per-model [`ProductionScheduler`] when
    /// [`Self::scheduler_registry`] is present. `None` means
    /// "legacy path: submit straight to `process_*_batch`" — used
    /// only in unit tests that don't wire the scheduler.
    ///
    /// Lazily materialises the scheduler on first touch. When a new
    /// one is created, also spawns that model's drain loop so the
    /// submitted items get consumed — that's the counterpart to the
    /// old eager-at-startup `spawn_scheduler_drains`. Schedulers are
    /// now materialised only for active models that land on a sidecar
    /// worker, so boot does not need a model list to iterate.
    ///
    /// `model_max_batch_tokens` is the model's batch cost budget from the
    /// `EnsureModelReady` answer for this group; the registry sizes the
    /// scheduler's cost cap and adaptive range from it (see
    /// [`crate::scheduler::SchedulerRegistry::get_or_create`]).
    async fn resolve_scheduler(
        self: &Arc<Self>,
        model_id: &str,
        model_max_batch_tokens: Option<u64>,
    ) -> Option<Arc<ProductionScheduler>> {
        let registry = self.scheduler_registry.as_ref()?;
        let shutdown = self.shutdown.as_ref()?;
        let (sched, created) = registry
            .get_or_create(model_id, model_max_batch_tokens)
            .await;
        if created {
            let mut handles = self.scheduler_drain_handles.lock().await;
            // Double-check under the lock: a concurrent `resolve_scheduler`
            // for the same model could have won the `get_or_create` race
            // and already inserted a handle. Without this guard we'd spawn
            // two drain loops racing the same scheduler queue.
            if !handles.contains_key(model_id) {
                let disp = Arc::clone(self);
                let sched_c = Arc::clone(&sched);
                let shutdown_c = Arc::clone(shutdown);
                let model_id_s = model_id.to_owned();
                let model_id_log = model_id.to_owned();
                let handle = tokio::spawn(async move {
                    scheduler_drain_loop(model_id_s, disp, sched_c, shutdown_c).await;
                });
                handles.insert(model_id.to_owned(), handle);
                info!(
                    model = %model_id_log,
                    "rust-scheduler: drain loop spawned on first traffic",
                );
            }
        }
        Some(sched)
    }

    /// Remove and return every scheduler drain handle registered so
    /// far. Called at shutdown from `lib.rs` so the main shutdown
    /// path can `await` each task to completion (bounded inside the
    /// loop by `DEFAULT_SCHEDULER_DRAIN_DEADLINE_MS`, overridable via
    /// `SIE_SCHEDULER_DRAIN_DEADLINE_MS`).
    pub async fn take_scheduler_drain_handles(&self) -> Vec<JoinHandle<()>> {
        let mut guard = self.scheduler_drain_handles.lock().await;
        guard.drain().map(|(_, h)| h).collect()
    }

    /// Remove and return all in-flight generation task handles. Called
    /// during shutdown after the pull loops stop so long-running streams can
    /// settle before the backend drain RPC closes backend-side state.
    pub async fn take_generation_handles(&self) -> Vec<JoinHandle<()>> {
        let mut guard = self.generation_handles.lock().await;
        guard.drain(..).collect()
    }

    /// Wait, up to `deadline`, for groups parked while their model loads.
    /// Called at shutdown after the pull loops stop and before the scheduler
    /// drain: a parked group sees the shutdown signal, NAKs its items and
    /// exits, or enqueues them if its model became ready first.
    pub async fn join_parked_groups(&self, deadline: Duration) {
        let handles: Vec<JoinHandle<()>> = self
            .parked_group_handles
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .drain(..)
            .collect();
        if handles.is_empty() {
            return;
        }
        let mut pending = handles;
        let joined = tokio::time::timeout(deadline, async {
            while let Some(handle) = pending.last_mut() {
                let _ = handle.await;
                pending.pop();
            }
        })
        .await;
        if joined.is_err() {
            // An aborted group drops its deliveries unsettled, so JetStream
            // redelivers them after the ACK wait.
            warn!(
                parked_groups = pending.len(),
                deadline_ms = deadline.as_millis() as u64,
                "parked model groups did not settle before the shutdown deadline — aborting them"
            );
            for handle in &pending {
                handle.abort();
            }
            for handle in pending {
                let _ = handle.await;
            }
        }
    }

    /// Resolve every encode item's payload then submit it into the
    /// model scheduler under its `options["lora"]` key. Items whose
    /// payload resolution fails follow the same publish_error + ACK
    /// (or NAK on publish failure) path as [`Self::handle_encode`];
    /// the scheduler never sees them.
    ///
    /// Returns immediately once all items are enqueued — the drain
    /// loop owns the actual backend call + outcome publish.
    async fn enqueue_encode_into_scheduler(
        &self,
        model_id: &str,
        scheduler: &Arc<ProductionScheduler>,
        items: Vec<(WorkItem, Delivery)>,
    ) {
        let mut grouped: HashMap<LoraKey, Vec<(SchedulerItem, SchedulerMeta)>> = HashMap::new();
        for (wi, delivery) in items {
            if self
                .settle_if_cancelled(&wi, &delivery, "before_payload_fetch")
                .await
            {
                continue;
            }
            let (item_json, fetch_ms) = match self.resolve_item(&wi).await {
                Ok(v) => v,
                Err(e) => {
                    self.fail_resolve(&wi, &delivery, &e, "failed to resolve encode item")
                        .await;
                    continue;
                }
            };
            if self
                .settle_if_cancelled(&wi, &delivery, "after_payload_fetch")
                .await
            {
                continue;
            }
            let caller_item_id = caller_item_id_from_value(&item_json);
            let prepared_tokens = self.maybe_prepare_encode_tokens(model_id, &wi, &item_json);
            let lora = lora_from_options(&wi.options);
            let ebi = EncodeBatchItem {
                work_item_id: wi.work_item_id.clone(),
                request_id: wi.request_id.clone(),
                item_index: wi.item_index,
                total_items: wi.total_items,
                timestamp: wi.timestamp,
                item: item_json,
                output_types: wi.output_types.clone(),
                instruction: wi.instruction.clone(),
                is_query: wi.is_query,
                options: wi.options.clone(),
                profile_id: opt_non_empty(&wi.profile_id),
                bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
                numerical_admission_sha256: wi.numerical_admission_sha256.clone(),
                payload_fetch_ms: fetch_ms,
                prepared_tokens,
            };
            let item = SchedulerItem::Encode(ebi);
            let child_index = self.record_scheduler_enqueue(model_id, &wi.profile_id, &item);
            let worker_direct = delivery.worker_direct();
            let meta = SchedulerMeta::new_with_worker_direct(wi, delivery, fetch_ms, worker_direct)
                .with_worker_child_index(child_index)
                .with_caller_item_id(caller_item_id);
            grouped.entry(lora).or_default().push((item, meta));
        }
        for (lora, grouped_items) in grouped {
            scheduler
                .submit_many(SchedOp::Encode, lora, grouped_items)
                .await;
        }
    }

    /// Score twin of [`Self::enqueue_encode_into_scheduler`]. See
    /// [`Self::handle_score`] for the Rust-tokenisation note on
    /// `prepared_tokens` being `None` (cross-encoder tokenisation
    /// stays Python-side for now).
    ///
    /// Routing policy: score always goes to `LoraKey::base`
    /// regardless of what's on `options["lora"]`. That's enforced
    /// inside [`crate::scheduler::Scheduler::submit`] so the call
    /// here passes the parsed key through transparently.
    async fn enqueue_score_into_scheduler(
        &self,
        model_id: &str,
        scheduler: &Arc<ProductionScheduler>,
        items: Vec<(WorkItem, Delivery)>,
    ) {
        let mut grouped: Vec<(SchedulerItem, SchedulerMeta)> = Vec::new();
        for (wi, delivery) in items {
            if self
                .settle_if_cancelled(&wi, &delivery, "before_payload_fetch")
                .await
            {
                continue;
            }
            let (query, score_items, fetch_ms) = match self.resolve_score(&wi).await {
                Ok(v) => v,
                Err(e) => {
                    self.fail_resolve(&wi, &delivery, &e, "failed to resolve score payload")
                        .await;
                    continue;
                }
            };
            if self
                .settle_if_cancelled(&wi, &delivery, "after_payload_fetch")
                .await
            {
                continue;
            }
            let sbi = ScoreBatchItem {
                work_item_id: wi.work_item_id.clone(),
                request_id: wi.request_id.clone(),
                item_index: wi.item_index,
                total_items: wi.total_items,
                timestamp: wi.timestamp,
                query_item: query,
                score_items,
                instruction: wi.instruction.clone(),
                options: wi.options.clone(),
                profile_id: opt_non_empty(&wi.profile_id),
                bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
                numerical_admission_sha256: wi.numerical_admission_sha256.clone(),
                payload_fetch_ms: fetch_ms,
                prepared_tokens: None,
            };
            let item = SchedulerItem::score(sbi);
            let child_index = self.record_scheduler_enqueue(model_id, &wi.profile_id, &item);
            let worker_direct = delivery.worker_direct();
            let meta = SchedulerMeta::new_with_worker_direct(wi, delivery, fetch_ms, worker_direct)
                .with_worker_child_index(child_index);
            grouped.push((item, meta));
        }
        if !grouped.is_empty() {
            scheduler
                .submit_many(SchedOp::Score, LoraKey::base(), grouped)
                .await;
        }
    }

    /// Extract twin of [`Self::enqueue_encode_into_scheduler`].
    /// Extract items don't emit `prepared_tokens` on the Rust side
    /// (Python owns extract tokenisation in v1), so the outgoing
    /// [`ExtractBatchItem`] matches the current
    /// [`Self::handle_extract`] shape.
    async fn enqueue_extract_into_scheduler(
        &self,
        model_id: &str,
        scheduler: &Arc<ProductionScheduler>,
        items: Vec<(WorkItem, Delivery)>,
    ) {
        let mut grouped: HashMap<LoraKey, Vec<(SchedulerItem, SchedulerMeta)>> = HashMap::new();
        for (wi, delivery) in items {
            if self
                .settle_if_cancelled(&wi, &delivery, "before_payload_fetch")
                .await
            {
                continue;
            }
            if let Some(item) = &wi.item {
                if let Err(err) = validate_item_media(item) {
                    self.fail_invalid_media(&wi, &delivery, &err).await;
                    continue;
                }
            }
            let (item_json, fetch_ms) = match self.resolve_item(&wi).await {
                Ok(v) => v,
                Err(e) => {
                    self.fail_resolve(&wi, &delivery, &e, "failed to resolve extract item")
                        .await;
                    continue;
                }
            };
            if self
                .settle_if_cancelled(&wi, &delivery, "after_payload_fetch")
                .await
            {
                continue;
            }
            if wi.item.is_none() {
                if let Err(err) = validate_item_media(&item_json) {
                    self.fail_invalid_media(&wi, &delivery, &err).await;
                    continue;
                }
            }
            let lora = lora_from_options(&wi.options);
            let (item_json, prepared_audio) =
                match prepare_extract_audio(item_json, &self.audio_prep_semaphore).await {
                    Ok(prepared) => prepared,
                    Err(error) => {
                        self.fail_invalid_audio(&wi, &delivery, &error).await;
                        continue;
                    }
                };
            let xbi = ExtractBatchItem {
                work_item_id: wi.work_item_id.clone(),
                request_id: wi.request_id.clone(),
                item_index: wi.item_index,
                total_items: wi.total_items,
                timestamp: wi.timestamp,
                item: item_json,
                labels: wi.labels.clone(),
                output_schema: wi.output_schema.clone(),
                instruction: wi.instruction.clone(),
                options: wi.options.clone(),
                profile_id: opt_non_empty(&wi.profile_id),
                bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
                payload_fetch_ms: fetch_ms,
                prepared_audio,
            };
            let item = SchedulerItem::Extract(xbi);
            let child_index = self.record_scheduler_enqueue(model_id, &wi.profile_id, &item);
            let worker_direct = delivery.worker_direct();
            let meta = SchedulerMeta::new_with_worker_direct(wi, delivery, fetch_ms, worker_direct)
                .with_worker_child_index(child_index);
            grouped.entry(lora).or_default().push((item, meta));
        }
        for (lora, grouped_items) in grouped {
            scheduler
                .submit_many(SchedOp::Extract, lora, grouped_items)
                .await;
        }
    }

    fn record_scheduler_enqueue(
        &self,
        model_id: &str,
        profile_id: &str,
        item: &SchedulerItem,
    ) -> usize {
        let cost = item.cost();
        self.runtime_state.telemetry.queue_enqueued(
            scheduler_operation_label(item.op()),
            model_id,
            (!profile_id.is_empty()).then_some(profile_id),
        );
        self.runtime_state.worker_queue_depth.inc();
        self.runtime_state
            .worker_pending_cost
            .add(clamp_u64_to_i64(cost));
        self.worker_pool
            .record_model_pending_enqueue(model_id, cost)
    }

    /// Shared failure tail for the three scheduler-enqueue paths.
    /// Shared by legacy and scheduler paths: deterministic oversized payloads
    /// publish `PAYLOAD_TOO_LARGE`; other resolution failures retain the
    /// generic `payload_error`. Both ACK after a successful terminal publish;
    /// if the publish itself
    /// fails, NAK so JetStream redelivers.
    async fn fail_resolve(
        &self,
        wi: &WorkItem,
        delivery: &Delivery,
        err: &PayloadError,
        log_msg: &str,
    ) {
        warn!(
            error = %ErrChain(err),
            work_item_id = %wi.work_item_id,
            request_id = %wi.request_id,
            model = %wi.model_id,
            "{log_msg}"
        );
        let (code, message) = payload_error_contract(err);
        match self.publish_error(wi, delivery, code, message).await {
            Ok(_) => match ack(delivery, &self.runtime_state.telemetry).await {
                Ok(()) => {}
                Err(e) => {
                    warn!(error = %e, "ack after error-publish failed");
                }
            },
            Err(_) => {
                nak_one(delivery, base_nak_delay_ms(), &self.runtime_state.telemetry).await;
            }
        }
    }

    /// Reject malformed media before Python IPC while preserving the same
    /// terminal INVALID_INPUT + ACK settlement used by Python's
    /// `InvalidMediaError`. Error text contains only field paths and sizes,
    /// never user media bytes.
    async fn fail_invalid_media(
        &self,
        wi: &WorkItem,
        delivery: &Delivery,
        err: &MediaValidationError,
    ) {
        warn!(
            error = %err,
            work_item_id = %wi.work_item_id,
            request_id = %wi.request_id,
            model = %wi.model_id,
            "extract media validation failed before IPC"
        );
        match self
            .publish_error(wi, delivery, INVALID_INPUT_ERROR_CODE, &err.to_string())
            .await
        {
            Ok(_) => match ack(delivery, &self.runtime_state.telemetry).await {
                Ok(()) => {}
                Err(e) => {
                    warn!(error = %e, "ack after invalid-media error publish failed");
                }
            },
            Err(_) => {
                nak_one(delivery, base_nak_delay_ms(), &self.runtime_state.telemetry).await;
            }
        }
    }

    async fn fail_invalid_audio(&self, wi: &WorkItem, delivery: &Delivery, error: &str) {
        warn!(
            error,
            work_item_id = %wi.work_item_id,
            request_id = %wi.request_id,
            model = %wi.model_id,
            "audio preparation rejected extract item"
        );
        match self
            .publish_error(wi, delivery, "invalid_request", error)
            .await
        {
            Ok(_) => match ack(delivery, &self.runtime_state.telemetry).await {
                Ok(()) => {}
                Err(error) => {
                    warn!(error = %error, "ack after invalid-audio publish failed");
                }
            },
            Err(_) => nak_one(delivery, base_nak_delay_ms(), &self.runtime_state.telemetry).await,
        }
    }

    // -- payload resolution ----------------------------------------------

    async fn resolve_item(&self, wi: &WorkItem) -> Result<(MsgValue, f64), PayloadError> {
        if let Some(item) = &wi.item {
            return Ok((item.clone(), 0.0));
        }
        let Some(payload_ref) = &wi.payload_ref else {
            return Err(PayloadError::InvalidRef(format!(
                "work item {} has neither item nor payload_ref",
                wi.work_item_id
            )));
        };
        let start = std::time::Instant::now();
        let bytes = self.payload_store.get(payload_ref).await?;
        let ms = start.elapsed().as_secs_f64() * 1000.0;
        let item: MsgValue = rmp_serde::from_slice(&bytes)
            .map_err(|e| PayloadError::InvalidRef(format!("decode payload: {e}")))?;
        Ok((item, ms))
    }

    // -- Rust-side tokenisation -------------------------------------------
    //
    // `maybe_prepare_encode_tokens` consults the tokenizer registry
    // and returns `Some(PreparedTokens)` when the v2 safety rules
    // hold:
    //
    //   1. Registry has an entry for `model_id` (the adapter declared
    //      a tokeniser on `EnsureModelReady`).
    //   2. The msgpack-native `item` payload has a populated string `text`
    //      field. Image / audio / multimodal items fall through to
    //      Python as today.
    //
    // The registry-backed path no longer bails out on `is_query=true`
    // or `instruction!=""`: when a model has shipped its template
    // defaults via `ModelDescriptor.default_query_template` /
    // `default_doc_template`, the sidecar applies the template via
    // [`crate::prep::text_prep::TextPrep`] before tokenising — bit-exact
    // with Python's `_utils.extract_texts` for the two known
    // placeholders. Per-request `options.query_template` /
    // `options.doc_template` overrides still win.
    //
    // Any tokenise error at runtime returns `None` and the Python
    // adapter tokenises from `item` exactly like today. Failures are
    // logged at `debug` so they don't drown out real incidents.
    //
    // Score path: there is no Rust-side fast path. The cross-encoder
    // adapter on the Python side owns pair-building + tokenisation
    // (model-specific `[CLS] q [SEP] d [SEP]` policies plus pair
    // padding), so Rust always sets `ScoreBatchItem.prepared_tokens =
    // None`. Re-introducing a `maybe_prepare_score_tokens` helper
    // is straightforward when the Python score path grows a
    // `prepared_tokens` consumer; until then the dead helper has
    // been removed to keep the surface honest.
    fn maybe_prepare_encode_tokens(
        &self,
        model_id: &str,
        wi: &WorkItem,
        item: &MsgValue,
    ) -> Option<PreparedTokens> {
        let entry = self.tokenizer_registry.get(model_id)?;

        // Text-only inputs. Treat absent / non-string / empty text as
        // "not a fast-path request" and defer to Python. An empty
        // string would tokenise to a 2-token `[CLS][SEP]` padding
        // sequence — harmless but pure IPC overhead vs letting Python
        // short-circuit on its own empty-text guard.
        let raw_text = msg_map_get(item, "text")
            .and_then(msg_as_str)
            .filter(|s| !s.is_empty())?;

        // Resolve per-request template overrides; fall back to the
        // adapter's defaults from the handshake. Same precedence as
        // Python's `resolve_embedding_options`.
        let (query_template, doc_template) = crate::prep::text_prep::extract_templates_from_options(
            wi.options.as_ref(),
            entry.default_query_template(),
            entry.default_doc_template(),
        );

        // Apply the template / instruction transform. Borrowing-style
        // `apply` so plain (non-templated, non-instructed) text is a
        // no-op pass-through with no allocation beyond the input.
        let prep = crate::prep::text_prep::TextPrep {
            instruction: wi.instruction.as_deref(),
            is_query: wi.is_query,
            query_template,
            doc_template,
        };
        let prepared_text = prep.apply(raw_text);
        let text: &str = prepared_text.as_str();

        let rag = match entry.tokenize(&[text]) {
            Ok(r) if r.len() == 1 => r,
            Ok(_) => return None, // empty/unexpected — defer
            Err(e) => {
                tracing::debug!(
                    model = %model_id,
                    error = %e,
                    "rust-tokenize: encode tokenise failed; deferring to Python"
                );
                return None;
            }
        };

        Some(rag_to_wire(entry.tokenizer_id(), entry.max_seq_len(), rag))
    }

    async fn resolve_score(
        &self,
        wi: &WorkItem,
    ) -> Result<(MsgValue, Vec<MsgValue>, f64), PayloadError> {
        // Inline path: both query + items provided on the WorkItem.
        if let (Some(q), Some(items)) = (&wi.query_item, &wi.score_items) {
            return Ok((q.clone(), items.clone(), 0.0));
        }

        // Offloaded path: query_payload_ref points at a msgpack-encoded
        // `{"query": ..., "items": [...]}` blob.
        let Some(ref_key) = &wi.query_payload_ref else {
            return Err(PayloadError::InvalidRef(format!(
                "score item {} missing query/items and query_payload_ref",
                wi.work_item_id
            )));
        };
        let start = std::time::Instant::now();
        let bytes = self.payload_store.get(ref_key).await?;
        let ms = start.elapsed().as_secs_f64() * 1000.0;
        let decoded: MsgValue = rmp_serde::from_slice(&bytes)
            .map_err(|e| PayloadError::InvalidRef(format!("decode score payload: {e}")))?;
        let query = msg_map_get(&decoded, "query")
            .cloned()
            .ok_or_else(|| PayloadError::InvalidRef("score payload missing 'query'".into()))?;
        let items = match msg_map_get(&decoded, "items") {
            Some(MsgValue::Array(items)) => items.clone(),
            _ => {
                return Err(PayloadError::InvalidRef(
                    "score payload missing 'items' array".into(),
                ));
            }
        };
        Ok((query, items, ms))
    }
}

// -----------------------------------------------------------------------------
// Grouping (pure logic, tested independently)
// -----------------------------------------------------------------------------

/// Group by `(model_id, operation)`. Retained for tests and callers
/// that want explicit per-op grouping; the hot path uses
/// [`group_by_model_only`] so encode/score/extract for the same model
/// can run concurrently under a single readiness check.
pub fn group_by_model<T>(
    items: Vec<(WorkItem, T)>,
) -> BTreeMap<(String, String), Vec<(WorkItem, T)>> {
    let mut groups: BTreeMap<(String, String), Vec<(WorkItem, T)>> = BTreeMap::new();
    for (wi, extra) in items {
        let key = (wi.model_id.clone(), wi.operation.clone());
        groups.entry(key).or_default().push((wi, extra));
    }
    groups
}

/// Group decoded messages by `model_id` only — hot-path grouping.
pub fn group_by_model_only<T>(items: Vec<(WorkItem, T)>) -> BTreeMap<String, Vec<(WorkItem, T)>> {
    let mut groups: BTreeMap<String, Vec<(WorkItem, T)>> = BTreeMap::new();
    for (wi, extra) in items {
        let key = wi.model_id.clone();
        groups.entry(key).or_default().push((wi, extra));
    }
    groups
}

/// Split a per-model group at the batch budget. First `budget` items go
/// to dispatch, the rest to overflow (the caller NAKs with a short delay).
pub(crate) type DispatchSplit<T> = (Vec<(WorkItem, T)>, Vec<(WorkItem, T)>);

pub(crate) fn split_by_budget<T>(items: Vec<(WorkItem, T)>, budget: usize) -> DispatchSplit<T> {
    if items.len() <= budget {
        return (items, Vec::new());
    }
    let mut it = items.into_iter();
    let dispatch: Vec<(WorkItem, T)> = it.by_ref().take(budget).collect();
    let overflow: Vec<(WorkItem, T)> = it.collect();
    (dispatch, overflow)
}

/// Scheduler-local latency for one successful request-ID occurrence within one
/// backend batch. Both fields use a monotonic [`Instant`] interval and are
/// retained as [`Duration`] so the semantic facade owns unit conversion.
#[derive(Debug, Clone, Copy)]
struct PerRequestSchedulerLatency {
    /// Scheduler enqueue through the instant immediately before `run_batch`.
    dispatch_wait: Duration,
    /// Scheduler enqueue through the completed `run_batch` reply.
    total: Duration,
}

/// Compute one scheduler-local latency sample per *unique successful*
/// `request_id` in this backend batch. A client request split across multiple
/// backend batches contributes one sample in each batch, and a partially
/// failed request contributes in a batch when at least one outcome is
/// `PublishAndAck`. Mirrors Python's batch-local `_complete_requests` dedup
/// pattern (see
/// `model_worker.py:947-976` on main `bbe409c3`):
///
/// ```python
/// completed_metadata: set[int] = set()
/// for metadata in batch.metadata:
///     meta_id = id(metadata)
///     if meta_id in completed_metadata:
///         continue
///     completed_metadata.add(meta_id)
///     ...
///     self._latency_tracker.record(metadata.timing.total_ms)
/// ```
///
/// In the Rust scheduler each NATS message is its own
/// [`SchedulerMeta`] with its own `submitted_at`; when the gateway
/// fans out a multi-item client request it produces N work-items with
/// the same `request_id` and distinct `item_index`es. We pick the
/// **first** occurrence's `submitted_at` (lowest `item_index` is not
/// guaranteed because the BatchFormer sorts by cost, but all items in
/// a request share the same gateway publish time so any of them is a
/// fair stand-in for Python's request-level `_start_time`).
///
/// Items are skipped if:
///   * the IPC reply marked them anything other than `PublishAndAck`
///     (errors / NAK paths shouldn't bias the controller toward fast
///     no-op replies);
///   * total latency came out non-positive. Letting zero-duration replay
///     samples in would bias `observed_p50_ms` toward zero and pin the
///     wait knob at the floor.
///
/// Takes an iterator of `(request_id, submitted_at, outcome)` triples
/// rather than a `&[SchedulerMeta]` so unit tests don't need to
/// fabricate a `jetstream::Message` (which has no public constructor).
fn dedupe_per_batch_request_latencies<'a, I>(
    rows: I,
    dispatch_started_at: Instant,
    completed_at: Instant,
) -> Vec<PerRequestSchedulerLatency>
where
    I: IntoIterator<Item = (&'a str, Instant, &'a ItemOutcome)>,
{
    let iter = rows.into_iter();
    let (lower, _) = iter.size_hint();
    let mut seen: HashSet<&str> = HashSet::with_capacity(lower);
    let mut out: Vec<PerRequestSchedulerLatency> = Vec::with_capacity(lower);
    for (request_id, submitted_at, o) in iter {
        if !matches!(o.disposition, Disposition::PublishAndAck) {
            continue;
        }
        if !seen.insert(request_id) {
            continue;
        }
        // `completed_at` is captured after RunBatch returns, so this
        // interval already contains scheduler wait, IPC, inference,
        // and postprocessing. Adding the outcome phase fields again
        // would double-count backend work in the controller signal.
        // Saturating subtract keeps future timestamps in tests/replays
        // from panicking.
        let total = completed_at.saturating_duration_since(submitted_at);
        if !total.is_zero() {
            let dispatch_wait = dispatch_started_at.saturating_duration_since(submitted_at);
            out.push(PerRequestSchedulerLatency {
                dispatch_wait,
                total,
            });
        }
    }
    out
}

/// Record the transport-queue age of every work item this worker is COMMITTING
/// TO EXECUTE, measured from the gateway publish timestamp on each envelope.
///
/// Call this at an execution-commit point: after the cancellation filter has
/// removed abandoned items, AFTER the bundle-config execution barrier, and
/// immediately before the batch (or the generation stream) is handed to the
/// backend. There are six such points — the three batch handlers, the scheduler
/// drain, the NATS generation lane, and the local-ingest generation lane — and
/// every one of them must call this, because `sie.worker.work_item.age` exists
/// to answer "how much work does this cluster execute after its client gave up"
/// and a missing path silently biases that distribution toward zero.
///
/// The barrier ordering is load-bearing in the other direction. A bundle-hash
/// change NAKs the whole batch without ever calling the backend, so recording
/// before the barrier would count redelivered work as executed. Hash changes
/// land during a config rollout, which is also when backlog builds, so that
/// over-count would land exactly where the number has to be trustworthy.
///
/// Age at execution START is deliberate, and it is the reason this is not
/// recorded next to the result publish in [`Dispatcher::apply_outcome`]:
///
/// - Generation never passes through `apply_outcome` at all. It streams from
///   its own task, so a publish-time observation would omit the single most
///   expensive operation to run for nobody — which is precisely the case the
///   measurement exists to size.
/// - Age at publish is age at execution start PLUS execution time. For an
///   embedding batch that difference is milliseconds, but for generation it is
///   tens of seconds, so mixing the two would make the per-operation
///   comparison meaningless.
/// - Age at execution start is the quantity a deadline check would actually
///   evaluate: it is what a worker knows at the instant it decides whether
///   spending GPU on this item is still worth anything.
///
/// Items that never execute are deliberately NOT observed: cancellation
/// ack-drops, payload-fetch failures, unknown-operation rejections,
/// bundle-hash mismatches, and NAK-for-redelivery all leave before this point.
/// Counting them would answer a different question ("how long do items sit in
/// the queue") with a series whose name promises this one. A NAK'd item that is
/// later redelivered and does execute is observed then, carrying its full age
/// since the original gateway publish, which is the correct and more alarming
/// number.
///
/// One caveat for readers of the resulting distribution: broker-delivered work
/// and local-ingest work share a series when one sidecar serves both. Local
/// ingest has no broker hop, so it contributes near-zero ages and pulls the p50
/// down. That is an accurate statement about the work this process ran, but it
/// is not a statement about broker staleness alone.
///
/// One clock read covers the whole batch: a 4096-item request would otherwise
/// pay 4096 `SystemTime::now()` calls for a diagnostic.
fn record_work_item_ages<'a>(
    telemetry: &crate::observability::metrics::SidecarTelemetry,
    items: impl IntoIterator<Item = &'a WorkItem>,
) {
    if !telemetry.is_enabled() {
        return;
    }
    let Ok(now) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) else {
        return;
    };
    let now_s = now.as_secs_f64();
    for wi in items {
        // A zero/absent publish timestamp has no measurable age. Recording 0
        // would plant a false spike in the lowest bucket rather than admitting
        // the envelope carried nothing. Negative and non-finite deltas (clock
        // skew) are dropped by the facade for the same reason.
        if wi.timestamp <= 0.0 {
            continue;
        }
        telemetry.work_item_age_observed(&wi.operation, now_s - wi.timestamp);
    }
}

fn queue_ms_from(timestamp_s: f64) -> f64 {
    if timestamp_s <= 0.0 {
        return 0.0;
    }
    let now_s = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs_f64())
        .unwrap_or(timestamp_s);
    let delta_ms = (now_s - timestamp_s) * 1000.0;
    if delta_ms < 0.0 {
        0.0
    } else {
        delta_ms
    }
}

/// Convert a [`crate::tokenize::RaggedTokens`] bundle into the wire
/// [`PreparedTokens`] form. Wrapping here (rather than inline at each
/// call site) keeps the "what to elide to save bytes" policy in one
/// place: BERT-style all-zero `token_type_ids` skip the wire, since
/// Python treats an empty outer vec as "all zeros".
fn rag_to_wire(
    tokenizer_id: &str,
    max_seq_len: usize,
    rag: crate::tokenize::RaggedTokens,
) -> PreparedTokens {
    let token_type_ids = if rag.token_type_ids_all_zero() {
        Vec::new()
    } else {
        rag.token_type_ids
    };
    PreparedTokens {
        input_ids: rag.input_ids,
        attention_mask: rag.attention_mask,
        token_type_ids,
        tokenizer_id: tokenizer_id.to_string(),
        max_seq_len: max_seq_len as u32,
    }
}

/// Synthetic error `ItemOutcome` for pre-execution failures (payload
/// resolution, bad operation, offload decode). Shared by the NATS and
/// local delivery error paths so both emit the identical wire shape.
/// No timings: error-only publishes omit queue_ms / processing_ms /
/// payload_fetch_ms.
fn synthetic_error_outcome(wi: &WorkItem, code: &str, message: &str) -> ItemOutcome {
    ItemOutcome {
        work_item_id: wi.work_item_id.clone(),
        request_id: wi.request_id.clone(),
        item_index: wi.item_index,
        disposition: Disposition::PublishErrorAndAck,
        nak_delay_ms: None,
        result_msgpack: Vec::new(),
        error: Some(message.to_string()),
        error_code: Some(code.to_string()),
        inference_ms: None,
        tokenization_ms: None,
        postprocessing_ms: None,
        raw_output: None,
        units: None,
        retry_after_s: None,
    }
}

async fn prepare_extract_audio(
    item: MsgValue,
    permits: &Arc<Semaphore>,
) -> Result<(MsgValue, Option<PreparedAudioPcm16>), String> {
    let item = match crate::audio_prep::classify_item(item).map_err(|error| error.to_string())? {
        crate::audio_prep::AudioPreparation::Ready(item) => return Ok((item, None)),
        crate::audio_prep::AudioPreparation::Decode(item) => item,
    };
    let _permit = permits
        .acquire()
        .await
        .map_err(|_| "audio preparation permit pool closed".to_string())?;
    tokio::task::spawn_blocking(move || crate::audio_prep::prepare_item(item))
        .await
        .map_err(|error| format!("audio preparation task failed: {error}"))?
        .map_err(|error| error.to_string())
}

fn opt_non_empty(s: &str) -> Option<String> {
    if s.is_empty() {
        None
    } else {
        Some(s.to_string())
    }
}

fn truncate(s: &str, n: usize) -> &str {
    match s.char_indices().nth(n) {
        Some((idx, _)) => &s[..idx],
        None => s,
    }
}

fn encode_generate_terminal_error_chunk(
    wi: &WorkItem,
    code: &str,
    message: &str,
) -> Result<Vec<u8>, rmp_serde::encode::Error> {
    let chunk = GenerateTerminalErrorChunk {
        kind: "chunk",
        request_id: &wi.request_id,
        attempt_id: format!("{}:model-loading", wi.work_item_id),
        seq: 0,
        text_delta: "",
        done: true,
        finish_reason: "error",
        error: GenerateTerminalError { code, message },
    };
    rmp_serde::to_vec_named(&chunk)
}

async fn handle_generate_event(
    event: GenerateEvent,
    publisher: Arc<WorkPublisher>,
    telemetry: crate::observability::metrics::SidecarTelemetry,
    settled: Arc<AtomicBool>,
    msg: Arc<QueuedMessage>,
    delivery_log: Arc<GenerateDeliveryLogContext>,
    executed_bundle_config_hash: &str,
) -> Result<(), DispatchError> {
    match event.kind.as_str() {
        "publish" => {
            if event.reply_subject != delivery_log.reply_subject {
                return Err(DispatchError::Ipc(IpcError::Server(
                    "generation publish reply_subject mismatch".to_string(),
                )));
            }
            let payload =
                stamp_generate_execution_hash(event.payload, executed_bundle_config_hash)?;
            publisher.publish_raw(&event.reply_subject, payload).await?;
        }
        "ack" => {
            if !settled.swap(true, Ordering::SeqCst) {
                match ack_msg(&msg, &telemetry).await {
                    Ok(()) => {
                        info!(
                            work_item_id = %delivery_log.work_item_id,
                            request_id = %delivery_log.request_id,
                            model = %delivery_log.model_id,
                            subject = %delivery_log.delivery.subject,
                            stream = %delivery_log.delivery.stream,
                            consumer = %delivery_log.delivery.consumer,
                            stream_seq = delivery_log.delivery.stream_sequence,
                            consumer_seq = delivery_log.delivery.consumer_sequence,
                            delivery_count = delivery_log.delivery.delivered,
                            pending = delivery_log.delivery.pending,
                            "generate delivery ACKed"
                        );
                    }
                    Err(e) => {
                        warn!(
                            work_item_id = %delivery_log.work_item_id,
                            request_id = %delivery_log.request_id,
                            model = %delivery_log.model_id,
                            subject = %delivery_log.delivery.subject,
                            stream = %delivery_log.delivery.stream,
                            consumer = %delivery_log.delivery.consumer,
                            stream_seq = delivery_log.delivery.stream_sequence,
                            consumer_seq = delivery_log.delivery.consumer_sequence,
                            delivery_count = delivery_log.delivery.delivered,
                            pending = delivery_log.delivery.pending,
                            error = %e,
                            "generate ACK failed"
                        );
                    }
                }
            }
        }
        "nak" => {
            if !settled.swap(true, Ordering::SeqCst) {
                let delay_ms = event.delay_ms.unwrap_or_else(base_nak_delay_ms);
                warn!(
                    work_item_id = %delivery_log.work_item_id,
                    request_id = %delivery_log.request_id,
                    model = %delivery_log.model_id,
                    delay_ms,
                    subject = %delivery_log.delivery.subject,
                    stream = %delivery_log.delivery.stream,
                    consumer = %delivery_log.delivery.consumer,
                    stream_seq = delivery_log.delivery.stream_sequence,
                    consumer_seq = delivery_log.delivery.consumer_sequence,
                    delivery_count = delivery_log.delivery.delivered,
                    pending = delivery_log.delivery.pending,
                    "generate delivery NAKed by Python"
                );
                nak_msg(&msg, delay_ms, &telemetry).await;
            }
        }
        "in_progress" => {
            if !settled.load(Ordering::SeqCst) {
                let progress = msg.ack_with(async_nats::jetstream::AckKind::Progress).await;
                telemetry.nats_operation(
                    "progress",
                    if progress.is_ok() { "success" } else { "error" },
                    "none",
                    1,
                );
                match progress {
                    Ok(()) => {
                        debug!(
                            work_item_id = %delivery_log.work_item_id,
                            request_id = %delivery_log.request_id,
                            model = %delivery_log.model_id,
                            subject = %delivery_log.delivery.subject,
                            stream = %delivery_log.delivery.stream,
                            consumer = %delivery_log.delivery.consumer,
                            stream_seq = delivery_log.delivery.stream_sequence,
                            consumer_seq = delivery_log.delivery.consumer_sequence,
                            delivery_count = delivery_log.delivery.delivered,
                            pending = delivery_log.delivery.pending,
                            "generate delivery progress ACKed"
                        );
                    }
                    Err(e) => {
                        debug!(
                            work_item_id = %delivery_log.work_item_id,
                            request_id = %delivery_log.request_id,
                            model = %delivery_log.model_id,
                            subject = %delivery_log.delivery.subject,
                            stream = %delivery_log.delivery.stream,
                            consumer = %delivery_log.delivery.consumer,
                            stream_seq = delivery_log.delivery.stream_sequence,
                            consumer_seq = delivery_log.delivery.consumer_sequence,
                            delivery_count = delivery_log.delivery.delivered,
                            pending = delivery_log.delivery.pending,
                            error = %e,
                            "generate in-progress ACK failed"
                        );
                    }
                }
            }
        }
        other => {
            warn!(event = %other, "unknown ProcessGenerate event from Python");
        }
    }
    Ok(())
}

fn stamp_generate_execution_hash(
    payload: Vec<u8>,
    executed_bundle_config_hash: &str,
) -> Result<Vec<u8>, DispatchError> {
    if executed_bundle_config_hash.is_empty() {
        return Ok(payload);
    }
    let mut value: rmpv::Value = rmp_serde::from_slice(&payload)
        .map_err(|error| IpcError::Server(format!("decode generation chunk: {error}")))?;
    let rmpv::Value::Map(fields) = &mut value else {
        return Err(IpcError::Server("generation chunk is not a msgpack map".to_string()).into());
    };
    fields.retain(|(key, _)| key.as_str() != Some("executed_bundle_config_hash"));
    fields.push((
        rmpv::Value::from("executed_bundle_config_hash"),
        rmpv::Value::from(executed_bundle_config_hash),
    ));
    rmp_serde::to_vec_named(&value)
        .map_err(|error| IpcError::Server(format!("encode generation chunk: {error}")).into())
}

fn validate_local_generate_publication(
    payload: Vec<u8>,
    expected_request_id: &str,
    executed_bundle_config_hash: &str,
    state: &mut LocalGenerateState,
) -> Result<LocalGeneratePublication, String> {
    let mut value: MsgValue = rmp_serde::from_slice(&payload)
        .map_err(|error| format!("decode generation publication: {error}"))?;
    let MsgValue::Map(fields) = &value else {
        return Err("generation publication is not a msgpack map".to_string());
    };
    let kind = unique_generate_chunk_field(fields, "kind")?
        .and_then(MsgValue::as_str)
        .ok_or_else(|| "generation publication kind must be a string".to_string())?
        .to_string();

    match kind.as_str() {
        "chunk" => {
            validate_local_generate_chunk_fields(fields, expected_request_id, state)?;
            if !executed_bundle_config_hash.is_empty() {
                let MsgValue::Map(fields) = &mut value else {
                    unreachable!("publication map was validated above")
                };
                fields.retain(|(key, _)| key.as_str() != Some("executed_bundle_config_hash"));
                fields.push((
                    MsgValue::from("executed_bundle_config_hash"),
                    MsgValue::from(executed_bundle_config_hash),
                ));
            }
            let payload = rmp_serde::to_vec_named(&value)
                .map_err(|error| format!("encode generation chunk: {error}"))?;
            Ok(LocalGeneratePublication::Chunk(payload))
        }
        "nak" => {
            validate_local_generate_nak_fields(fields, expected_request_id, state)?;
            Ok(LocalGeneratePublication::Retry)
        }
        other => Err(format!("unexpected generation publication kind {other:?}")),
    }
}

#[cfg(test)]
fn validate_local_generate_chunk(
    payload: &[u8],
    expected_request_id: &str,
    state: &mut LocalGenerateState,
) -> Result<(), String> {
    let value: MsgValue = rmp_serde::from_slice(payload)
        .map_err(|error| format!("decode generation chunk: {error}"))?;
    let MsgValue::Map(fields) = value else {
        return Err("generation chunk is not a msgpack map".to_string());
    };
    validate_local_generate_chunk_fields(&fields, expected_request_id, state)
}

fn validate_local_generate_chunk_fields(
    fields: &[(MsgValue, MsgValue)],
    expected_request_id: &str,
    state: &mut LocalGenerateState,
) -> Result<(), String> {
    if !matches!(state.phase, LocalGeneratePhase::Streaming) {
        return Err(format!(
            "generation emitted a chunk after terminal/settlement phase {:?}",
            state.phase
        ));
    }
    let kind = unique_generate_chunk_field(fields, "kind")?
        .and_then(MsgValue::as_str)
        .ok_or_else(|| "generation chunk kind must be a string".to_string())?;
    if kind != "chunk" {
        return Err(format!("unexpected generation chunk kind {kind:?}"));
    }
    let request_id = unique_generate_chunk_field(fields, "request_id")?
        .and_then(MsgValue::as_str)
        .ok_or_else(|| "generation chunk request_id must be a string".to_string())?;
    if request_id != expected_request_id {
        return Err("generation chunk request_id mismatch".to_string());
    }
    let attempt_id = unique_generate_chunk_field(fields, "attempt_id")?
        .and_then(MsgValue::as_str)
        .filter(|value| !value.is_empty() && value.len() <= 128)
        .ok_or_else(|| "generation chunk attempt_id is invalid".to_string())?;
    match state.attempt_id.as_deref() {
        Some(expected) if expected != attempt_id => {
            return Err("generation chunk attempt_id changed within stream".to_string());
        }
        None => state.attempt_id = Some(attempt_id.to_string()),
        _ => {}
    }
    let seq = unique_generate_chunk_field(fields, "seq")?
        .and_then(MsgValue::as_u64)
        .and_then(|value| u32::try_from(value).ok())
        .ok_or_else(|| "generation chunk seq must be a u32".to_string())?;
    if seq != state.next_seq {
        return Err(format!(
            "generation chunk seq gap: got {seq}, expected {}",
            state.next_seq
        ));
    }
    state.next_seq = state
        .next_seq
        .checked_add(1)
        .ok_or_else(|| "generation chunk sequence overflow".to_string())?;
    let done = unique_generate_chunk_field(fields, "done")?
        .and_then(MsgValue::as_bool)
        .ok_or_else(|| "generation chunk done must be a bool".to_string())?;
    if done {
        state.phase = LocalGeneratePhase::AwaitingChunkAck;
    }
    Ok(())
}

fn validate_local_generate_nak_fields(
    fields: &[(MsgValue, MsgValue)],
    expected_request_id: &str,
    state: &mut LocalGenerateState,
) -> Result<(), String> {
    if !matches!(state.phase, LocalGeneratePhase::Streaming) || state.next_seq != 0 {
        return Err(format!(
            "generation emitted a semantic NAK after output/settlement phase {:?}",
            state.phase
        ));
    }
    let request_id = unique_generate_chunk_field(fields, "request_id")?
        .and_then(MsgValue::as_str)
        .ok_or_else(|| "generation NAK request_id must be a string".to_string())?;
    if request_id != expected_request_id {
        return Err("generation NAK request_id mismatch".to_string());
    }
    let attempt_id = unique_generate_chunk_field(fields, "attempt_id")?
        .and_then(MsgValue::as_str)
        .filter(|value| !value.is_empty() && value.len() <= 128)
        .ok_or_else(|| "generation NAK attempt_id is invalid".to_string())?;
    match state.attempt_id.as_deref() {
        Some(expected) if expected != attempt_id => {
            return Err("generation NAK attempt_id changed within stream".to_string());
        }
        None => state.attempt_id = Some(attempt_id.to_string()),
        _ => {}
    }
    let reason = unique_generate_chunk_field(fields, "reason")?
        .and_then(MsgValue::as_str)
        .filter(|value| !value.is_empty() && value.len() <= 64)
        .ok_or_else(|| "generation NAK reason is invalid".to_string())?;
    state.phase = LocalGeneratePhase::AwaitingRetryAck {
        reason: reason.to_string(),
    };
    Ok(())
}

fn unique_generate_chunk_field<'a>(
    fields: &'a [(MsgValue, MsgValue)],
    expected: &str,
) -> Result<Option<&'a MsgValue>, String> {
    let mut found = None;
    for (key, value) in fields {
        if key.as_str() != Some(expected) {
            continue;
        }
        if found.replace(value).is_some() {
            return Err(format!(
                "generation chunk contains duplicate {expected:?} field"
            ));
        }
    }
    Ok(found)
}

async fn ack(
    delivery: &Delivery,
    telemetry: &crate::observability::metrics::SidecarTelemetry,
) -> Result<(), DispatchError> {
    ack_with_reason(delivery, telemetry, "completed").await
}

async fn ack_with_reason(
    delivery: &Delivery,
    telemetry: &crate::observability::metrics::SidecarTelemetry,
    reason: &str,
) -> Result<(), DispatchError> {
    let result = delivery.ack().await.map_err(DispatchError::Ack);
    if matches!(delivery, Delivery::Nats(..)) {
        telemetry.nats_operation(
            "ack",
            if result.is_ok() { "success" } else { "error" },
            reason,
            1,
        );
    }
    result
}

async fn nak_all(
    items: &[(WorkItem, Delivery)],
    delay_ms: u64,
    telemetry: &crate::observability::metrics::SidecarTelemetry,
) {
    for (_, d) in items {
        nak_one(d, delay_ms, telemetry).await;
    }
    debug!(count = items.len(), delay_ms, "NAKed group");
}

/// NAK work a config barrier refused, each item counted with its own reason
/// ([`barrier_nak_reason`]).
async fn nak_all_at_barrier(
    items: &[(WorkItem, Delivery)],
    delay_ms: u64,
    telemetry: &crate::observability::metrics::SidecarTelemetry,
    state: Option<&ConfigApplyState>,
) {
    for (wi, d) in items {
        nak_one_with_reason(
            d,
            delay_ms,
            telemetry,
            barrier_nak_reason(state, &wi.model_id),
        )
        .await;
    }
    debug!(
        count = items.len(),
        delay_ms, "NAKed group at a config barrier"
    );
}

async fn nak_one(
    delivery: &Delivery,
    delay_ms: u64,
    telemetry: &crate::observability::metrics::SidecarTelemetry,
) {
    nak_one_with_reason(delivery, delay_ms, telemetry, "retry").await;
}

/// Why an item breaks the numerical admission contract, if it does. Admitted
/// work names a numerical admission, travels only on the admission subject
/// for its own model, and is encode or score: the operations whose backend
/// method re-verifies the admission before execution. A numerical remote
/// attempt that stands in for a local refusal is always admitted work.
fn numerical_admission_violation(subject: &str, wi: &WorkItem) -> Option<&'static str> {
    let numerical = matches!(wi.operation.as_str(), "encode" | "score");
    match (
        wi.numerical_admission_sha256.is_some(),
        requires_numerical_admission_v1(subject),
    ) {
        (true, false) => Some("admitted_work_off_the_admission_subject"),
        (false, true) => Some("unadmitted_work_on_the_admission_subject"),
        (true, true) if !numerical => Some("admitted_work_is_not_encode_or_score"),
        (true, true) if wi.bundle_config_hash.is_empty() => {
            Some("admitted_work_names_no_configuration")
        }
        (true, true) if !execution_authority_model_matches(subject, &wi.model_id) => {
            Some("admitted_work_names_another_model")
        }
        (false, false) if numerical && wi.fallback_reason.is_some() => {
            Some("numerical_fallback_without_admission")
        }
        _ => None,
    }
}

async fn nak_one_with_reason(
    delivery: &Delivery,
    delay_ms: u64,
    telemetry: &crate::observability::metrics::SidecarTelemetry,
    reason: &str,
) {
    let result = delivery.nak(delay_ms).await;
    if matches!(delivery, Delivery::Nats(..)) {
        telemetry.nats_operation(
            "nak",
            if result.is_ok() { "success" } else { "error" },
            reason,
            1,
        );
    }
    match result {
        Ok(()) => {}
        Err(e) => {
            warn!(error = %e, "nak failed");
        }
    }
}

async fn progress_all(
    items: &[(WorkItem, Delivery)],
    telemetry: &crate::observability::metrics::SidecarTelemetry,
) -> bool {
    let mut all_ok = true;
    for (_, d) in items {
        if !progress_one(d, telemetry).await {
            all_ok = false;
        }
    }
    if all_ok {
        debug!(count = items.len(), "progress ACKed group");
    }
    all_ok
}

async fn progress_one(
    delivery: &Delivery,
    telemetry: &crate::observability::metrics::SidecarTelemetry,
) -> bool {
    let result = delivery.progress().await;
    if matches!(delivery, Delivery::Nats(..)) {
        telemetry.nats_operation(
            "progress",
            if result.is_ok() { "success" } else { "error" },
            "none",
            1,
        );
    }
    match result {
        Ok(()) => true,
        Err(e) => {
            warn!(error = %e, "progress ack failed");
            false
        }
    }
}

// Generate-path (NATS-only) settlement helpers. The generation flow shares
// its `Message` behind an `Arc` with the streaming-event callback, so it
// cannot move it into a [`Delivery`]; these mirror `ack`/`nak_one` exactly.

async fn ack_msg(
    msg: &Message,
    telemetry: &crate::observability::metrics::SidecarTelemetry,
) -> Result<(), DispatchError> {
    let result = msg
        .ack()
        .await
        .map_err(|e| DispatchError::Ack(e.to_string()));
    telemetry.nats_operation(
        "ack",
        if result.is_ok() { "success" } else { "error" },
        "completed",
        1,
    );
    result
}

async fn nak_msg(
    msg: &Message,
    delay_ms: u64,
    telemetry: &crate::observability::metrics::SidecarTelemetry,
) {
    nak_msg_with_reason(msg, delay_ms, telemetry, "retry").await;
}

async fn nak_msg_with_reason(
    msg: &Message,
    delay_ms: u64,
    telemetry: &crate::observability::metrics::SidecarTelemetry,
    reason: &str,
) {
    let delay = std::time::Duration::from_millis(delay_ms);
    let result = msg
        .ack_with(async_nats::jetstream::AckKind::Nak(Some(delay)))
        .await;
    telemetry.nats_operation(
        "nak",
        if result.is_ok() { "success" } else { "error" },
        reason,
        1,
    );
    match result {
        Ok(()) => {}
        Err(e) => {
            warn!(error = %e, "nak failed");
        }
    }
}

// -----------------------------------------------------------------------------
// Scheduler drain loop
// -----------------------------------------------------------------------------

/// Default deadline (ms) for the shutdown-time drain of a model's
/// scheduler queue. After this the loop exits and any residual items
/// redeliver via JetStream's `ack_wait` — correct but slower. Tuned
/// to stay well under `DRAIN_DEADLINE_MS` on the backend so the
/// overall shutdown budget isn't exceeded. Overridable with
/// `SIE_SCHEDULER_DRAIN_DEADLINE_MS` for ops; see
/// [`scheduler_drain_deadline_ms`].
const DEFAULT_SCHEDULER_DRAIN_DEADLINE_MS: u64 = 10_000;

/// Resolved drain deadline honouring the `SIE_SCHEDULER_DRAIN_DEADLINE_MS`
/// env override. Parsed per call (the drain loop reads it exactly
/// once, at shutdown-time) so tests + ops can nudge it without
/// restarting threads. Invalid / non-positive values fall back to
/// the default rather than silently producing a zero deadline.
fn scheduler_drain_deadline_ms() -> u64 {
    std::env::var("SIE_SCHEDULER_DRAIN_DEADLINE_MS")
        .ok()
        .and_then(|s| s.parse::<u64>().ok())
        .filter(|v| *v > 0)
        .unwrap_or(DEFAULT_SCHEDULER_DRAIN_DEADLINE_MS)
}

/// Process-wide monotonic batch id. Shared across every per-model
/// drain loop so a batch id collision across models can't happen,
/// which keeps log-correlation unambiguous on the Python side.
static SCHEDULER_BATCH_ID_COUNTER: std::sync::atomic::AtomicU64 =
    std::sync::atomic::AtomicU64::new(0);

/// Role of a batch within a scheduler wave.
///
/// A wave starts with one **primary** batch and may continue with zero
/// or more **drain** batches from the same `(op, lora)` queue. The
/// adaptive controller must step exactly once per wave, using the
/// primary batch size. Drains still feed inference-time and per-batch
/// request-ID latency samples, but they do not trigger efficiency records or PI
/// controller steps; otherwise the controller sees a stream of smaller
/// drain batches and drives the wait knob too low under saturation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WaveRole {
    /// First batch in a wave (or shutdown final-drain — every
    /// flush there is its own degenerate wave with no following
    /// drains). Drives a full `record_completion` →
    /// efficiency-record + controller step + cap propagation.
    Primary,
    /// Continuation batch produced by `try_drain_same` on the same
    /// `(op, lora)` queue as the wave's primary. Feeds the
    /// inference-calibration tracker (one sample) + the per-batch request-ID
    /// latency tracker, but does **not** step the controller and
    /// does **not** record an efficiency sample. The caps from the
    /// preceding primary's step stay in effect for the rest of the
    /// wave; adaptive controller state retains the primary's value
    /// (`gauge.set` is idempotent), so dashboards show one update
    /// per wave instead of one per IPC roundtrip.
    Drain,
}

fn scheduler_operation_label(operation: SchedOp) -> &'static str {
    match operation {
        SchedOp::Encode => "encode",
        SchedOp::Score => "score",
        SchedOp::Extract => "extract",
    }
}

fn homogeneous_catalog_profile(metadata: &[SchedulerMeta]) -> Option<&str> {
    let first = metadata.first()?.wi.profile_id.trim();
    if first.is_empty()
        || metadata
            .iter()
            .any(|meta| meta.wi.profile_id.trim() != first)
    {
        None
    } else {
        Some(first)
    }
}

fn release_scheduler_pressure(
    runtime_state: &RuntimeState,
    worker_pool: &AdapterWorkerPool,
    model_id: &str,
    items: &[SchedulerItem],
    metadata: &[SchedulerMeta],
) {
    if items.is_empty() {
        return;
    }
    assert_eq!(
        items.len(),
        metadata.len(),
        "FormattedBatch items and metadata must stay aligned",
    );

    let mut total_cost = 0_u64;
    let mut child_pending: BTreeMap<usize, (usize, u64)> = BTreeMap::new();
    let mut unattributed_count = 0_usize;
    let mut unattributed_cost = 0_u64;

    for (item, meta) in items.iter().zip(metadata.iter()) {
        let item_cost = item.cost();
        runtime_state.telemetry.queue_released(
            scheduler_operation_label(item.op()),
            model_id,
            (!meta.wi.profile_id.is_empty()).then_some(meta.wi.profile_id.as_str()),
            meta.submitted_at.elapsed(),
        );
        total_cost = total_cost.saturating_add(item_cost);
        if let Some(child_index) = meta.worker_child_index {
            let entry = child_pending.entry(child_index).or_insert((0, 0));
            entry.0 += 1;
            entry.1 = entry.1.saturating_add(item_cost);
        } else {
            unattributed_count += 1;
            unattributed_cost = unattributed_cost.saturating_add(item_cost);
        }
    }

    decrement_gauge(&runtime_state.worker_queue_depth, items.len() as i64);
    decrement_gauge(
        &runtime_state.worker_pending_cost,
        clamp_u64_to_i64(total_cost),
    );
    for (child_index, (item_count, cost)) in child_pending {
        worker_pool.record_child_pending_dequeue(child_index, item_count, cost);
    }
    if unattributed_count > 0 {
        worker_pool.record_model_pending_dequeue(model_id, unattributed_count, unattributed_cost);
    }
}

/// Per-batch scheduler-tick: pack the flushed batch into a
/// [`RunBatchRequest`], hand it to the backend, apply outcomes
/// through the existing dispatcher publish/ACK/NAK path, and feed
/// the adaptive controller with one completion sample.
///
/// Factored out of [`scheduler_drain_loop`] so the happy-path + the
/// shutdown final-drain share the same code. Pure async fn with no
/// hidden state: the scheduler is borrowed and the dispatcher is
/// [`Arc`]'d.
///
/// `role` decides whether this batch's completion triggers a
/// controller step (see [`WaveRole`] for the cadence rules).
async fn process_scheduler_batch(
    model_id: &str,
    dispatcher: &Arc<Dispatcher>,
    scheduler: &Arc<ProductionScheduler>,
    op: SchedOp,
    lora: crate::scheduler::LoraKey,
    batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,
    role: WaveRole,
) {
    assert_eq!(
        batch.items.len(),
        batch.metadata.len(),
        "FormattedBatch items and metadata must stay aligned"
    );
    let mut partition_role = role;
    for partition in split_by_contract(batch) {
        if partition.items.is_empty() {
            continue;
        }
        process_scheduler_contract_batch(
            model_id,
            dispatcher,
            scheduler,
            op,
            lora.clone(),
            partition,
            partition_role,
        )
        .await;
        // The RPCs retain one wave/pipeline permit. Preserve its Primary/Drain
        // roles and the configured controller cadence across them.
        partition_role = WaveRole::Drain;
    }
}

/// The backend method a scheduler batch runs through.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BatchContract {
    NumericalAdmission = 0,
    ExecutionAuthority = 1,
    Legacy = 2,
}

impl BatchContract {
    fn of<'a>(metadata: impl IntoIterator<Item = &'a SchedulerMeta>) -> Self {
        let mut contract = Self::Legacy;
        for meta in metadata {
            if meta.wi.numerical_admission_sha256.is_some() {
                return Self::NumericalAdmission;
            }
            if meta.delivery.requires_execution_authority_v1() {
                contract = Self::ExecutionAuthority;
            }
        }
        contract
    }
}

/// Keep the execution contracts separate even when the scheduler coalesces
/// a verified request with an older producer's empty-hash work: the legacy
/// sibling must not invalidate or downgrade the verified request's RPC, and
/// admitted numerical work must not share a method that skips admission.
fn split_by_contract(
    batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,
) -> [crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>; 3] {
    let flush_reason = batch.flush_reason;
    let mut partitions = std::array::from_fn(|_| crate::scheduler::FormattedBatch {
        items: Vec::new(),
        metadata: Vec::new(),
        total_cost: 0,
        flush_reason,
    });
    for (item, meta) in batch.items.into_iter().zip(batch.metadata) {
        let partition: &mut crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta> =
            &mut partitions[BatchContract::of(std::iter::once(&meta)) as usize];
        partition.total_cost += item.cost();
        partition.items.push(item);
        partition.metadata.push(meta);
    }
    partitions
}

async fn process_scheduler_contract_batch(
    model_id: &str,
    dispatcher: &Arc<Dispatcher>,
    scheduler: &Arc<ProductionScheduler>,
    op: SchedOp,
    lora: crate::scheduler::LoraKey,
    batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,
    role: WaveRole,
) {
    if batch.items.is_empty() {
        return;
    }
    assert_eq!(
        batch.items.len(),
        batch.metadata.len(),
        "FormattedBatch items and metadata must stay aligned",
    );
    let crate::scheduler::FormattedBatch {
        items,
        metadata,
        total_cost: _,
        flush_reason,
    } = batch;
    let mut kept_items = Vec::with_capacity(items.len());
    let mut kept_metadata = Vec::with_capacity(metadata.len());
    let mut kept_cost = 0_u64;
    let mut cancelled = 0_usize;
    for (item, meta) in items.into_iter().zip(metadata) {
        if dispatcher
            .settle_if_cancelled(&meta.wi, &meta.delivery, "before_ipc")
            .await
        {
            release_scheduler_pressure(
                &dispatcher.runtime_state,
                &dispatcher.worker_pool,
                model_id,
                std::slice::from_ref(&item),
                std::slice::from_ref(&meta),
            );
            cancelled += 1;
            continue;
        }
        kept_cost += item.cost();
        kept_items.push(item);
        kept_metadata.push(meta);
    }
    if cancelled > 0 {
        debug!(
            model = %model_id,
            cancelled,
            "dropped abandoned scheduler items before IPC"
        );
    }
    let batch = crate::scheduler::FormattedBatch {
        items: kept_items,
        metadata: kept_metadata,
        total_cost: kept_cost,
        flush_reason,
    };
    if batch.items.is_empty() {
        return;
    }
    let batch_size = batch.items.len();
    let total_cost = batch.total_cost;
    let flush_reason = batch.flush_reason.as_label();
    release_scheduler_pressure(
        &dispatcher.runtime_state,
        &dispatcher.worker_pool,
        model_id,
        &batch.items,
        &batch.metadata,
    );
    let op_label = scheduler_operation_label(op);
    // `lora.as_str()` yields `None` for the base key; on the wire
    // we send an empty string so Python's `lora_key or None` chain
    // roundtrips to the same value.
    let lora_str = lora.as_str().unwrap_or("").to_string();
    // Worker-local monotonic batch id. `Relaxed` is fine: the value
    // is log-only (Python writes it on METHOD_RUN_BATCH) and no
    // ordering guarantees hang off it across threads.
    let batch_id = SCHEDULER_BATCH_ID_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);

    // Zip each scheduler item with its parallel metadata so we can copy
    // the originating `WorkItem`'s W3C trace context onto the wire item.
    // `batch.metadata` is borrowed here and only consumed later in this
    // function (the NAK / `apply_outcomes` paths), so `.iter()` is fine.
    // Guard the parallel-vector invariant: `zip()` would silently truncate
    // and drop work items if `items` and `metadata` ever drifted apart.
    assert_eq!(
        batch.items.len(),
        batch.metadata.len(),
        "FormattedBatch items and metadata must stay aligned",
    );
    // Open the `sidecar.dispatch` span so the queue hop is visible in
    // the trace: `gateway.proxy → sidecar.dispatch → worker.run_batch`.
    // It is created here (before the IPC dispatch) and kept alive — but
    // only *entered* synchronously, never across an `.await` — so its
    // OTel duration covers the dispatch and it is not held on the
    // worker thread while the task is parked. When no OTLP exporter is
    // configured the `tracing_opentelemetry` layer is absent, so this
    // span produces no OTel span and the gateway-context fallback below
    // keeps `gateway → worker` linkage intact (propagator-only parity).
    let dispatch_span = tracing::info_span!(
        "sidecar.dispatch",
        otel.name = "sidecar.dispatch",
        sie.op = op_label,
        sie.model = %model_id,
        sie.batch_id = batch_id,
        sie.batch_size = batch_size,
    );
    {
        // A coalesced batch can mix items from several gateway traces.
        // A span has exactly one parent but may carry many links, so we
        // parent on the first valid gateway context and record the
        // remaining distinct contexts as links (OTel batch convention).
        use tracing_opentelemetry::OpenTelemetrySpanExt;
        let mut linked: HashSet<&str> = HashSet::new();
        // Parent on the first item carrying a *valid* inbound context,
        // not merely the first item. A leading untraced item would
        // otherwise root the sidecar span on a fresh trace and — once
        // the outgoing items are overwritten with that context below —
        // strip the gateway lineage from the batch's genuinely-traced
        // items. `set_parent` then always receives a valid context, so
        // its `Result` is an `Ok` we discard.
        if let Some(parent) = batch.metadata.iter().find(|meta| {
            crate::observability::propagation::remote_span_context(
                meta.wi.traceparent.as_deref(),
                meta.wi.tracestate.as_deref(),
            )
            .is_some()
        }) {
            let tp = parent.wi.traceparent.as_deref();
            let ts = parent.wi.tracestate.as_deref();
            let _ = dispatch_span.set_parent(
                crate::observability::propagation::extract_context_from_w3c(tp, ts),
            );
            if let Some(tp) = tp {
                linked.insert(tp);
            }
        }
        for meta in batch.metadata.iter() {
            let Some(tp) = meta.wi.traceparent.as_deref() else {
                continue;
            };
            if !linked.insert(tp) {
                continue;
            }
            if let Some(sc) = crate::observability::propagation::remote_span_context(
                Some(tp),
                meta.wi.tracestate.as_deref(),
            ) {
                dispatch_span.add_link(sc);
            }
        }
    }

    // Serialise the sidecar span back into W3C strings (entered
    // synchronously — no `.await` inside). With an exporter active this
    // yields the sidecar span's context (new span_id under the inbound
    // trace); without one it returns `(None, None)` and the per-item
    // fallback below keeps the gateway context.
    let (sidecar_tp, sidecar_ts) =
        dispatch_span.in_scope(crate::observability::propagation::inject_current_context);

    let rb_items: Vec<crate::ipc_types::RunBatchItem> = batch
        .items
        .into_iter()
        .zip(batch.metadata.iter())
        .map(|(item, meta)| {
            // `into_run_batch_item_with_trace` copies the gateway
            // context as the fallback; override with the sidecar span's
            // context when one exists so `worker.run_batch` nests under
            // `sidecar.dispatch`.
            let mut rbi = item.into_run_batch_item_with_trace(&meta.wi);
            if let Some(tp) = &sidecar_tp {
                rbi.traceparent = Some(tp.clone());
                rbi.tracestate = sidecar_ts.clone();
            }
            rbi
        })
        .collect();
    let req = RunBatchRequest {
        model_id: model_id.to_string(),
        batch_id,
        lora_key: lora_str,
        total_cost,
        items: rb_items,
        accepts_batched_f16_multivectors: true,
    };
    let batch_profile = dispatcher
        .runtime_state
        .telemetry
        .is_enabled()
        .then(|| homogeneous_catalog_profile(&batch.metadata).map(ToString::to_string))
        .flatten();

    // Record the scheduler-formed shape once before the RPC so failed backend
    // calls still retain the authoritative batch observation.
    dispatcher.runtime_state.telemetry.batch_formed(
        op_label,
        model_id,
        batch_profile.as_deref(),
        flush_reason,
        batch_size,
        total_cost,
    );
    let started = Instant::now();
    dispatcher.runtime_state.inflight_batches.inc();

    let _execution_guard = if let Some(state) = dispatcher.config_apply_state.as_ref() {
        Some(state.lock_execution().await)
    } else {
        None
    };
    if let Some((expected_hash, unknown_hash_count)) = unknown_bundle_config_hash(
        batch.metadata.iter().map(|meta| &meta.wi),
        dispatcher.config_apply_state.as_deref(),
    ) {
        dispatcher.runtime_state.inflight_batches.dec();
        info!(
            model = %model_id,
            op = op_label,
            expected_hash,
            unknown_hash_count,
            local_hash = %dispatcher.config_apply_state.as_ref().map(|state| state.current_bundle_config_hash()).unwrap_or_default(),
            "scheduler work refused at the config barrier before execution — NAKing batch"
        );
        let msgs_only: Vec<(WorkItem, Delivery)> = batch
            .metadata
            .into_iter()
            .map(|meta| (meta.wi, meta.delivery))
            .collect();
        let msgs_only = dispatcher.answer_stale_admissions(msgs_only).await;
        nak_all_at_barrier(
            &msgs_only,
            base_nak_delay_ms(),
            &dispatcher.runtime_state.telemetry,
            dispatcher.config_apply_state.as_deref(),
        )
        .await;
        return;
    }

    // AFTER the config execution barrier above, not before it. The barrier can
    // still NAK the whole batch for a bundle-hash change, and a NAK'd batch
    // never reaches `run_batch` — counting it here would report work as
    // executed that was only redelivered. That matters more than it sounds:
    // hash changes land during a config rollout, which is also when backlog
    // builds, so the over-count would bias the distribution exactly under the
    // conditions B2 needs it to be trustworthy. The three batch handlers and
    // both generation paths clear their barrier before recording for the same
    // reason.
    record_work_item_ages(
        &dispatcher.runtime_state.telemetry,
        batch.metadata.iter().map(|meta| &meta.wi),
    );

    let run_batch_budget = dispatcher.work_deadline.run_batch_budget(
        batch
            .metadata
            .iter()
            .filter(|meta| matches!(meta.delivery, Delivery::Nats(..)))
            .map(|meta| (meta.wi.deadline, meta.wi.timestamp)),
        unix_now_s(),
    );

    // Capture this monotonic boundary immediately before the backend RPC. The
    // enqueue→dispatch histogram therefore includes time parked behind the
    // scheduler pipeline permit, config execution barrier, and local request
    // construction, while the enqueue→reply histogram additionally includes
    // the backend roundtrip.
    let dispatch_started_at = Instant::now();

    let result = match BatchContract::of(&batch.metadata) {
        BatchContract::NumericalAdmission => {
            dispatcher
                .backend
                .run_batch_with_numerical_admission_v1(req, run_batch_budget)
                .await
        }
        BatchContract::ExecutionAuthority => {
            dispatcher
                .backend
                .run_batch_with_execution_authority_v1(req, run_batch_budget)
                .await
        }
        BatchContract::Legacy => {
            dispatcher
                .backend
                .run_batch_with_budget(req, run_batch_budget)
                .await
        }
    };
    let outcome = match result {
        Ok(o) => o,
        Err(e) => {
            dispatcher.runtime_state.inflight_batches.dec();
            let delay = nak_delay_for_backend_error(&e);
            warn!(
                model = %model_id,
                op = op_label,
                error = %ErrChain(&e),
                nak_delay_ms = delay,
                batch_size,
                "scheduler RunBatch failed — NAKing batch",
            );
            let msgs_only: Vec<(WorkItem, Delivery)> = batch
                .metadata
                .into_iter()
                .map(|m| (m.wi, m.delivery))
                .collect();
            nak_all(&msgs_only, delay, &dispatcher.runtime_state.telemetry).await;
            return;
        }
    };
    dispatcher.runtime_state.inflight_batches.dec();

    // Collect per-item timings BEFORE we move the metadata into
    // `apply_outcomes`. Two telemetry flows out of this loop:
    //
    //  1. `inference_ms_sample` — first reported inference_ms (all
    //     items in a GPU batch share the forward pass so any one is
    //     representative). Feeds the auto-calibration tracker so
    //     `target_p50_ms` derives from GPU forward time, not the
    //     batcher+post sum.
    //  2. `per_batch_request_total_ms` — one entry per unique successful
    //     request ID in this backend batch, measured from scheduler enqueue
    //     until the RunBatch reply completes. A request spanning backend
    //     batches contributes once in each batch. Fed verbatim into the
    //     controller's latency tracker to mirror Python's batch-local
    //     `RequestTiming.total_ms` deposits. The signal must include
    //     the Rust BatchFormer wait, must exclude upstream NATS queue
    //     depth, and must not collapse a batch to its max item latency;
    //     each of those alternatives biases the PI loop enough to pin
    //     the wait knob at a floor or ceiling.
    //
    //     The closest queue-path mirror of Python's `total_ms` is
    //     `completed_at - submitted_at`. `submitted_at`
    //     (`SchedulerMeta.submitted_at`) is stamped when the dispatcher
    //     enqueues the item into our scheduler — equivalent to when
    //     Python's `RequestTiming()` is constructed at the top of
    //     `EncodePipeline.run_encode`, which is *after* the NATS pull
    //     but *before* batch formation. The delta (`completed_at -
    //     submitted_at`) covers the time the item spent inside our
    //     own (Rust) `BatchFormer`, the IPC roundtrip, and all backend
    //     work through the reply. Backend phase fields are therefore
    //     already contained in the interval and must not be added.
    //     Note: the sidecar calls Python's pre-formed batch IPC entrypoint, so Python does
    //     not run its per-LoRA BatchFormer on this path; the entire
    //     batch-form delta is observed here on the Rust side instead of
    //     being split across Rust and Python batchers.
    let completed_at = Instant::now();
    let inference_ms_sample = outcome
        .outcomes
        .iter()
        .find_map(|o| o.inference_ms)
        .unwrap_or_else(|| started.elapsed().as_secs_f64() * 1000.0);
    // Per-batch request-ID totals. When the gateway
    // splits a multi-item client request into N NATS work-items they
    // share the same `request_id` but get distinct `item_index`es —
    // they may all land in one Rust batch. Python's
    // `_complete_requests` dedupes via a `seen: set[id(metadata)]` so a
    // multi-item request deposits one latency sample per backend batch, not
    // one per item in that batch (see `model_worker.py:947-976` on main
    // `bbe409c3`). A request larger than the scheduler batch cap can therefore
    // deposit multiple samples. This preserves the existing controller signal
    // while avoiding item-count weighting within a batch. Picking the first
    // successful occurrence's
    // `submitted_at` keeps `batcher_wait_ms` aligned with Python's
    // `RequestTiming._start_time`, which is set once when the request
    // enters the worker process and shared across all its items.
    let per_batch_request_latencies = dedupe_per_batch_request_latencies(
        batch
            .metadata
            .iter()
            .zip(outcome.outcomes.iter())
            .map(|(m, o)| (m.wi.request_id.as_str(), m.submitted_at, o)),
        dispatch_started_at,
        completed_at,
    );
    let per_batch_request_total_ms: Vec<f64> = per_batch_request_latencies
        .iter()
        .map(|sample| sample.total.as_secs_f64() * 1_000.0)
        .collect();

    // Histograms preserve the full successful-request distribution across a
    // scrape interval. Unlike the controller's end-of-run p50 gauge, they
    // expose saturation tails and split upstream scheduler/pipeline residency
    // from the RunBatch RPC. The same success filter + request-id dedupe feeds
    // both histograms and the existing controller signal; observing them does
    // not alter controller inputs or cadence.
    for sample in &per_batch_request_latencies {
        dispatcher
            .runtime_state
            .telemetry
            .scheduler_request_batch_completed(SchedulerRequestBatchObservation {
                operation: op_label,
                model: model_id,
                profile: batch_profile.as_deref(),
                dispatch_wait: sample.dispatch_wait,
                total: sample.total,
            });
    }

    let resolved: Vec<ResolvedWorkItem> = batch
        .metadata
        .into_iter()
        .map(|m| (m.wi, m.delivery, m.fetch_ms, m.caller_item_id))
        .collect();
    dispatcher.apply_outcomes(outcome, resolved).await;

    // Feed the adaptive controller. Only record completion when we
    // actually saw a successful item — a batch of all-errors would
    // bias the controller toward shrinking caps based on fast
    // no-op replies.
    //
    // Calibration sample rate: **one sample per batch** (not per
    // item). Feeding one sample per item can make Rust's calibration
    // latch from a single cold-start batch, pinning the target and
    // wait knob before the GPU reaches steady state. Per-batch
    // sampling keeps calibration aging across multiple batches while
    // the GPU warms.
    //
    // PI signal sample rate: per **unique request_id in each backend batch**.
    // This avoids item-count weighting within a batch but intentionally keeps
    // the existing behavior where requests spanning multiple backend batches
    // contribute once in each batch. For typical benchmark workloads (one item
    // per request) dedup is a no-op.
    //
    // Cadence (per [`WaveRole`]): Primary triggers
    // `record_completion` (efficiency record + controller step +
    // cap propagation + canonical fill observation). Drain feeds inference +
    // latency samples only; the controller is **not** stepped — the
    // wave's caps were already updated by the primary, and Python's
    // `_process_loop` likewise steps once per wave with the primary
    // batch size (`model_worker.py:828, 855-870`).
    //
    // `SIE_RUST_WAVE_CADENCE=off` flips back to per-batch stepping
    // (every Drain also calls `record_completion`). Off-by-default;
    // see [`crate::wave_cadence_enabled`] for the rationale and the
    // p50/p99 trade-off.
    if !per_batch_request_total_ms.is_empty() {
        scheduler.record_inference_sample(inference_ms_sample).await;
        scheduler
            .record_latency_samples(&per_batch_request_total_ms)
            .await;
        if matches!(role, WaveRole::Primary) || !crate::wave_cadence_enabled() {
            let snapshot = scheduler.record_completion(total_cost, batch_size).await;

            dispatcher.runtime_state.telemetry.adaptive_snapshot(
                model_id,
                batch_profile.as_deref(),
                snapshot.new_wait_ms,
                snapshot.new_batch_cost,
                snapshot.observed_p50_ms,
                snapshot.target_p50_ms,
                snapshot.starvation_resets_delta,
            );

            if let Some(f) = snapshot.fill_ratio {
                dispatcher.runtime_state.telemetry.batch_fill_observed(
                    op_label,
                    model_id,
                    batch_profile.as_deref(),
                    flush_reason,
                    f,
                );
            }
        }
    }

    debug!(
        model = %model_id,
        op = op_label,
        batch_id,
        batch_size,
        total_cost,
        flush_reason,
        role = ?role,
        elapsed_ms = started.elapsed().as_millis() as u64,
        "scheduler batch complete",
    );
}

fn clamp_u64_to_i64(value: u64) -> i64 {
    i64::try_from(value).unwrap_or(i64::MAX)
}

fn decrement_gauge(gauge: &RuntimeGauge, value: i64) {
    if value <= 0 {
        return;
    }
    gauge.sub(value);
}

/// Per-model background task: consume flushed batches from the
/// model's [`ProductionScheduler`], run them, and cycle back. Exits
/// on the shared [`Shutdown`] signal after a bounded final-drain
/// window; any items still in the scheduler when the deadline
/// expires redeliver via JetStream `ack_wait`.
///
/// Maximum number of in-flight `process_scheduler_batch` invocations
/// per model scheduler. This controls the depth of the IPC dispatch
/// pipeline.
///
/// Default is **2**: one batch can be on the GPU while the next has
/// already crossed the IPC boundary and is waiting on Python's
/// passthrough lock. That preserves the dual-buffer behaviour the
/// Python batcher used to provide before batch formation moved into
/// Rust.
///
/// `1` is still useful as a regression-bisect and high-saturation
/// escape hatch: it forces strict serial dispatch and removes queued
/// IPC frames from the request's tail. The default stays at `2` because
/// normal saturated loads benefit from hiding IPC roundtrip/decode time
/// behind the current forward pass.
///
/// On a lane whose engine runs one batch at a time, the second slot takes
/// only a batch that is already full (see
/// [`scheduler_hold_while_busy_enabled`]): a batch that could still grow
/// stays in the queue until the engine is free.
///
/// Values are clamped to `[1, 8]`. The upper bound is intentionally
/// conservative: Python inference is still serialized by the adapter's
/// single CUDA stream, so large depths mainly park decoded batches on
/// the lock and inflate per-batch latency.
/// Ceiling on a model's pipeline depth when its backend reports a dispatch
/// width (see [`Dispatcher::pipeline_depth_for`]).
const MAX_ENGINE_BATCHED_PIPELINE_DEPTH: usize = 1024;

fn pipeline_depth() -> usize {
    std::env::var("SIE_RUST_PIPELINE_DEPTH")
        .ok()
        .and_then(|v| v.parse::<usize>().ok())
        .map(|v| v.clamp(1, 8))
        .unwrap_or(2)
}

/// Whether the scheduler may flush the first item after an idle gap
/// immediately instead of waiting for the coalesce window.
///
/// Default true preserves the current low-load latency behavior. On a
/// lane that holds while busy, "idle" is read from the lane (no batch
/// out, none just returned), so a request of several items leaves at once
/// too; with this off, an idle lane waits for the classic flush triggers.
/// Operators can set `SIE_BATCHER_IDLE_BYPASS_ENABLED=false` for
/// passthrough runtimes such as Candle when multi-worker fanout makes
/// each worker see a thinner local stream and early singleton flushes
/// under-fill GPU forwards.
fn scheduler_idle_bypass_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| {
        std::env::var("SIE_BATCHER_IDLE_BYPASS_ENABLED")
            .ok()
            .map(|raw| {
                !matches!(
                    raw.trim().to_ascii_lowercase().as_str(),
                    "0" | "false" | "no" | "off"
                )
            })
            .unwrap_or(true)
    })
}

/// Whether a lane whose engine runs one batch at a time holds arrivals
/// while a batch is with the engine and sends them together when it
/// returns (see [`crate::scheduler::Scheduler::next_dispatch`]).
///
/// Default true. `SIE_BATCHER_HOLD_WHILE_BUSY=false` restores the earlier
/// loop for every lane: whatever is pending is sent into a free pipeline
/// slot as soon as the flush triggers allow, behind the batch the engine
/// is working on. Lanes whose backend reports a dispatch width above 1
/// always use that loop.
fn scheduler_hold_while_busy_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| {
        std::env::var("SIE_BATCHER_HOLD_WHILE_BUSY")
            .ok()
            .map(|raw| {
                !matches!(
                    raw.trim().to_ascii_lowercase().as_str(),
                    "0" | "false" | "no" | "off"
                )
            })
            .unwrap_or(true)
    })
}

/// Reports a lane batch's return when dropped, so the lane is released
/// however the dispatch task ends.
struct LaneReturn {
    scheduler: Arc<ProductionScheduler>,
    answered: usize,
    sent: Instant,
}

impl Drop for LaneReturn {
    fn drop(&mut self) {
        self.scheduler
            .note_return(self.answered, self.sent.elapsed());
    }
}

/// Spawn a batch that [`crate::scheduler::Scheduler::next_dispatch`]
/// released, holding `permit` until it is back. Every such batch is a
/// whole one (everything the lane had pending under the caps), so each
/// steps the adaptive controller. `completes` is the number of requests
/// the batch answers.
#[allow(clippy::too_many_arguments)]
fn spawn_lane_batch(
    model_id: &str,
    dispatcher: &Arc<Dispatcher>,
    scheduler: &Arc<ProductionScheduler>,
    permit: OwnedSemaphorePermit,
    op: SchedOp,
    lora: crate::scheduler::LoraKey,
    batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,
    completes: usize,
) {
    let model_id_c = model_id.to_owned();
    let disp_c = Arc::clone(dispatcher);
    let sched_c = Arc::clone(scheduler);
    let lane_return = LaneReturn {
        scheduler: Arc::clone(scheduler),
        answered: completes,
        sent: Instant::now(),
    };
    tokio::spawn(async move {
        process_scheduler_batch(
            &model_id_c,
            &disp_c,
            &sched_c,
            op,
            lora,
            batch,
            WaveRole::Primary,
        )
        .await;
        // Report the return before the slot frees, so the loop that wakes
        // on the slot reads a lane that already knows.
        drop(lane_return);
        drop(permit);
    });
}

/// Spawn a dispatch as an independent task while holding a previously
/// reserved pipeline permit. The task releases its permit when it
/// returns.
///
// Each argument is independently sourced from the consume loop's
// stack frame (model_id from the per-model task, dispatcher +
// scheduler are shared Arcs, permit is loop-local, op/lora/
// batch come from the just-flushed scheduler tick, role comes from
// the wave's primary-vs-drain role assignment). Bundling them into a
// struct would introduce a one-shot wrapper type whose only purpose
// is to satisfy this lint — net less readable, so explicit allow.
#[allow(clippy::too_many_arguments)]
fn spawn_pipelined_batch_with_permit(
    model_id: &str,
    dispatcher: &Arc<Dispatcher>,
    scheduler: &Arc<ProductionScheduler>,
    permit: OwnedSemaphorePermit,
    op: SchedOp,
    lora: crate::scheduler::LoraKey,
    batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,
    role: WaveRole,
) {
    let model_id_c = model_id.to_owned();
    let disp_c = Arc::clone(dispatcher);
    let sched_c = Arc::clone(scheduler);
    tokio::spawn(async move {
        process_scheduler_batch(&model_id_c, &disp_c, &sched_c, op, lora, batch, role).await;
        drop(permit);
    });
}

/// Spawn a formed scheduler batch on `permit`, or, when the model's backend
/// takes these items one at a time (see
/// [`Dispatcher::dispatches_items_alone`]), spawn each item as its own batch.
/// Every item after the first waits for its own pipeline slot, so a model
/// never has more than its pipeline depth in flight. If shutdown wins that
/// wait, the remaining items run here as one batch: they have already left
/// the scheduler, so the final drain would not see them.
#[allow(clippy::too_many_arguments)]
async fn spawn_scheduler_batch(
    model_id: &str,
    dispatcher: &Arc<Dispatcher>,
    scheduler: &Arc<ProductionScheduler>,
    pipeline_sem: &Arc<Semaphore>,
    shutdown: &Shutdown,
    permit: OwnedSemaphorePermit,
    op: SchedOp,
    lora: crate::scheduler::LoraKey,
    batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,
    role: WaveRole,
) {
    if batch.items.len() <= 1 || !dispatcher.dispatches_items_alone(model_id, op) {
        spawn_pipelined_batch_with_permit(
            model_id, dispatcher, scheduler, permit, op, lora, batch, role,
        );
        return;
    }
    let flush_reason = batch.flush_reason;
    let mut singles = batch
        .items
        .into_iter()
        .zip(batch.metadata)
        .map(|(item, meta)| crate::scheduler::FormattedBatch {
            total_cost: item.cost(),
            items: vec![item],
            metadata: vec![meta],
            flush_reason,
        });
    let first = singles.next().expect("a batch of two or more items");
    spawn_pipelined_batch_with_permit(
        model_id,
        dispatcher,
        scheduler,
        permit,
        op,
        lora.clone(),
        first,
        role,
    );
    while let Some(single) = singles.next() {
        let Some(permit) = reserve_pipeline_slot(pipeline_sem, shutdown).await else {
            let rest = std::iter::once(single).chain(singles).fold(
                crate::scheduler::FormattedBatch {
                    items: Vec::new(),
                    metadata: Vec::new(),
                    total_cost: 0,
                    flush_reason,
                },
                |mut acc, one| {
                    acc.total_cost += one.total_cost;
                    acc.items.extend(one.items);
                    acc.metadata.extend(one.metadata);
                    acc
                },
            );
            process_scheduler_batch(
                model_id,
                dispatcher,
                scheduler,
                op,
                lora,
                rest,
                WaveRole::Drain,
            )
            .await;
            return;
        };
        spawn_pipelined_batch_with_permit(
            model_id,
            dispatcher,
            scheduler,
            permit,
            op,
            lora.clone(),
            single,
            WaveRole::Drain,
        );
    }
}

/// Reserve one pipeline slot unless shutdown wins first.
///
/// Every scheduler extract is preceded by this wait. While all slots are
/// occupied, pending items therefore remain mutable inside the `BatchFormer`
/// and later arrivals can join the next dispatch. The semaphore is loop-owned
/// and never closed; closure is an internal invariant violation, not a reason
/// to exceed the configured pipeline depth.
async fn reserve_pipeline_slot(
    pipeline_sem: &Arc<Semaphore>,
    shutdown: &Shutdown,
) -> Option<OwnedSemaphorePermit> {
    tokio::select! {
        biased;
        _ = shutdown.wait() => None,
        permit = pipeline_sem.clone().acquire_owned() => Some(
            permit.expect("scheduler pipeline semaphore is loop-owned and never closed"),
        ),
    }
}

/// Reserve the first continuation slot, then snapshot one scheduler key's
/// pending count.
///
/// This ordering admits arrivals accumulated while the pipeline was saturated
/// before freezing the bounded drain-wave size. Counting is read-only, so it is
/// safe to cancel if shutdown wins after permit acquisition; the local permit
/// is dropped on that path.
async fn reserve_continuation_slot_and_snapshot<I, T>(
    scheduler: &crate::scheduler::Scheduler<I, T>,
    pipeline_sem: &Arc<Semaphore>,
    shutdown: &Shutdown,
    op: SchedOp,
    lora: crate::scheduler::LoraKey,
) -> Option<(OwnedSemaphorePermit, usize)>
where
    I: HasCost + Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    let permit = reserve_pipeline_slot(pipeline_sem, shutdown).await?;
    let budget = tokio::select! {
        biased;
        _ = shutdown.wait() => None,
        count = scheduler.pending_count_same(op, lora) => Some(count),
    }?;
    Some((permit, budget))
}

pub(crate) async fn scheduler_drain_loop(
    model_id: String,
    dispatcher: Arc<Dispatcher>,
    scheduler: Arc<ProductionScheduler>,
    shutdown: Arc<Shutdown>,
) {
    // The loop starts after the model's first `EnsureModelReady`, which
    // reports its dispatch width; a larger width reported later widens the
    // pipeline in place (see `Dispatcher::record_dispatch_width`).
    let pipeline = dispatcher.model_pipeline(&model_id);
    let depth = pipeline.depth();
    let idle_bypass_enabled = scheduler_idle_bypass_enabled();
    let hold_while_busy = scheduler_hold_while_busy_enabled();
    info!(
        model = %model_id,
        pipeline_depth = depth,
        idle_bypass_enabled,
        hold_while_busy,
        dispatch_width = dispatcher.dispatch_width(&model_id),
        "rust-scheduler: drain loop started",
    );

    // Python runs the pre-formed batch IPC entrypoint here: there is no
    // per-LoRA BatchFormer on the queue path and every IPC frame is one
    // caller-formed GPU dispatch, serialized by ModelWorker's adapter
    // dispatch lock. All queue batching now lives in the Rust scheduler
    // (`ProductionScheduler` -> `BatchFormer`).
    //
    // What `depth = 2` still buys us in this regime: the Python IPC
    // server (`ipc_server.py::_handle_request`) spawns each `RUN_BATCH`
    // as an `asyncio.create_task` (non-blocking on the read loop), so
    // shipping batch N+1 while N is on the GPU lets N+1 cross the IPC
    // boundary, msgpack-decode, and park on the contended
    // adapter dispatch lock. When N's forward pass finishes the lock
    // releases, N+1 enters the forward pass without paying the IPC
    // roundtrip + decode on the critical path.
    //
    // We cap depth at 2 by default — Python's adapter is still single-
    // CUDA-stream so true concurrent inference isn't possible; depth
    // > 2 just inflates per-batch latency by parking more frames on
    // the lock without any throughput gain. Operators can override
    // via `SIE_RUST_PIPELINE_DEPTH`: `1` falls back to strict serial
    // dispatch (one outstanding IPC roundtrip). At very high
    // concurrency, operators may prefer `1` to avoid parking a second
    // frame behind a long GPU forward pass.
    let pipeline_sem = Arc::clone(&pipeline.permits);

    // Idle-bypass + continuous-batching state. On the queue path,
    // Python's `model_worker.py::_process_loop` is bypassed and the Rust
    // scheduler is the sole batcher in the system, so the logic below
    // stands alone:
    //
    //   * `was_idle` starts true and is forwarded to `consume_next`
    //     as the `immediate` flag when idle-bypass is enabled. When
    //     the worker just polled an empty queue, the next item to
    //     arrive can flush at once instead of paying the full
    //     `max_batch_wait_ms` (50 ms in the auto-calibrated regime).
    //     Without this, low-concurrency traffic eats one full wait
    //     window per batch and p50 ends up dominated by the
    //     controller's wait knob. Operators can disable this via
    //     `SIE_BATCHER_IDLE_BYPASS_ENABLED=false` for passthrough GPU
    //     runtimes whose per-worker stream gets too thin under
    //     multi-worker fanout.
    //
    //   * Before every primary or drain extract we reserve a pipeline
    //     slot. A saturated pipeline therefore leaves its pending tail
    //     mutable inside the Rust `BatchFormer`; arrivals during the
    //     current GPU forwards can join the next dispatch instead of
    //     sitting in an immutable third batch outside the scheduler.
    //
    //   * Once the first continuation slot opens, we snapshot the same
    //     `(op, lora)` batcher's pending count and drain at most that
    //     many items. Work accumulated during active forwards can join
    //     the snapshot; later arrivals may participate after cost
    //     sorting, but cannot grow the wave. The next iteration returns
    //     to FCFS with each key's head refreshed to its actual oldest
    //     remaining item, removing stale-head priority and restoring
    //     controller cadence under continuous arrivals.
    //
    //   * `was_idle` is reset to true only when the just-finished
    //     wave produced no drained tail and the kicking batch was a
    //     singleton — i.e. real evidence the worker outran demand.
    //     Multi-item batches or non-empty drain tails mean traffic
    //     is steady and the next iteration should accumulate (no
    //     immediate flush).
    //
    // The steps above are the loop of a lane whose backend batches by
    // itself (dispatch width above 1), and of every lane when
    // `SIE_BATCHER_HOLD_WHILE_BUSY=false`. An engine that runs one batch at
    // a time is served by the first branch of the loop instead: a batch
    // sent while another is with the engine only waits at the engine's
    // lock with its membership frozen, and the requests that return a
    // moment later start a batch of their own behind it, so two groups
    // take turns and each request waits for the other group's forward.
    // There the scheduler's lane decides when the next batch leaves: at
    // once on an idle lane, held while a batch is out unless the pending
    // work is already full, and together after the batch returns.
    let mut was_idle = true;
    'run: loop {
        if hold_while_busy && dispatcher.dispatch_width(&model_id) <= 1 {
            // The slot is reserved before the lane is asked, as below: while
            // the pipeline is full the pending work stays in the queue.
            let Some(permit) = reserve_pipeline_slot(&pipeline_sem, &shutdown).await else {
                info!(
                    model = %model_id,
                    "rust-scheduler: shutdown observed — entering final drain",
                );
                break;
            };
            let next = tokio::select! {
                biased;
                _ = shutdown.wait() => None,
                batch = scheduler.next_dispatch(idle_bypass_enabled) => Some(batch),
            };
            let Some(crate::scheduler::Dispatch {
                op,
                lora,
                batch,
                completes,
            }) = next
            else {
                drop(permit);
                info!(
                    model = %model_id,
                    "rust-scheduler: shutdown observed — entering final drain",
                );
                break;
            };
            if dispatcher.dispatch_width(&model_id) > 1 {
                // The backend reported a dispatch width while the lane was
                // waiting (a reload): this batch is the other loop's first.
                // It never went out under the lane's rule, so take it back
                // out of the lane's count before sending it that way.
                scheduler.note_return(0, Duration::ZERO);
                spawn_scheduler_batch(
                    &model_id,
                    &dispatcher,
                    &scheduler,
                    &pipeline_sem,
                    &shutdown,
                    permit,
                    op,
                    lora,
                    batch,
                    WaveRole::Primary,
                )
                .await;
            } else {
                spawn_lane_batch(
                    &model_id,
                    &dispatcher,
                    &scheduler,
                    permit,
                    op,
                    lora,
                    batch,
                    completes,
                );
            }
            // A lane that changes hands mid-run starts the other loop from idle.
            was_idle = true;
            continue;
        }

        let Some(primary_permit) = reserve_pipeline_slot(&pipeline_sem, &shutdown).await else {
            info!(
                model = %model_id,
                "rust-scheduler: shutdown observed — entering final drain",
            );
            break;
        };

        // The permit must be held before `consume_next` extracts. If the queue
        // is idle, shutdown cancels this wait and drops the reserved permit.
        let primary = tokio::select! {
            biased;
            _ = shutdown.wait() => None,
            batch = scheduler.consume_next(was_idle && idle_bypass_enabled) => Some(batch),
        };
        let Some((op, lora, batch)) = primary else {
            drop(primary_permit);
            info!(
                model = %model_id,
                "rust-scheduler: shutdown observed — entering final drain",
            );
            break;
        };

        let initial_batch_size = batch.items.len();
        // First batch in the wave drives the controller step.
        spawn_scheduler_batch(
            &model_id,
            &dispatcher,
            &scheduler,
            &pipeline_sem,
            &shutdown,
            primary_permit,
            op,
            lora.clone(),
            batch,
            WaveRole::Primary,
        )
        .await;

        // Wait for the first continuation slot before snapshotting the drain
        // budget. At saturation this is when one active backend call finishes,
        // so arrivals accumulated during those forwards can all participate in
        // the next batch. Freezing the count only now keeps later arrivals from
        // extending the wave indefinitely without forcing a stale singleton.
        let mut drained_any = false;
        let Some((first_drain_permit, mut drain_budget)) = reserve_continuation_slot_and_snapshot(
            scheduler.as_ref(),
            &pipeline_sem,
            &shutdown,
            op,
            lora.clone(),
        )
        .await
        else {
            info!(
                model = %model_id,
                "rust-scheduler: shutdown observed before continuous drain",
            );
            break 'run;
        };
        if drain_budget == 0 {
            drop(first_drain_permit);
            was_idle = initial_batch_size <= 1;
            continue;
        }

        let mut drain_permit = Some(first_drain_permit);
        while drain_budget > 0 {
            let permit = drain_permit
                .take()
                .expect("positive drain budget always owns one pipeline permit");
            let drained = tokio::select! {
                biased;
                _ = shutdown.wait() => None,
                batch = scheduler.try_drain_same_up_to(op, lora.clone(), drain_budget) => {
                    Some(batch)
                }
            };
            let Some(drain_batch) = drained else {
                drop(permit);
                info!(
                    model = %model_id,
                    "rust-scheduler: shutdown observed during continuous drain",
                );
                break 'run;
            };
            let Some(drain_batch) = drain_batch else {
                drop(permit);
                break;
            };
            if drain_batch.items.is_empty() {
                drop(permit);
                break;
            }

            drain_budget = drain_budget.saturating_sub(drain_batch.items.len());
            drained_any = true;
            // Drains continue the wave: feed inference + latency samples, but
            // no controller step.
            spawn_scheduler_batch(
                &model_id,
                &dispatcher,
                &scheduler,
                &pipeline_sem,
                &shutdown,
                permit,
                op,
                lora.clone(),
                drain_batch,
                WaveRole::Drain,
            )
            .await;

            if drain_budget > 0 {
                let Some(next_permit) = reserve_pipeline_slot(&pipeline_sem, &shutdown).await
                else {
                    info!(
                        model = %model_id,
                        "rust-scheduler: shutdown observed during continuous drain",
                    );
                    break 'run;
                };
                drain_permit = Some(next_permit);
            }
        }

        was_idle = !drained_any && initial_batch_size <= 1;
    }

    // Quiesce the pipeline: acquire all of its permits so every
    // spawned dispatch task has finished its IPC roundtrip and
    // released its permit. Only then do we enter synchronous shutdown
    // drain below. Without this the final-drain loop
    // could race with still-in-flight pipelined batches and double-
    // submit work to Python.
    if let Ok(permits) = pipeline_sem
        .clone()
        .acquire_many_owned(pipeline.depth() as u32)
        .await
    {
        // Hold the permits for the rest of the function so no further
        // spawns can sneak in (`spawn_pipelined_batch` is no longer
        // called past this point, but defence-in-depth).
        std::mem::forget(permits);
    }

    // Shutdown drain: flush whatever's still enqueued, up to a
    // deadline. `try_consume_next` is non-blocking; a `None` return
    // with `total_pending_count() > 0` means flush triggers haven't
    // fired yet — we sleep briefly to let coalesce windows expire
    // then try again.
    let started = Instant::now();
    let deadline = std::time::Duration::from_millis(scheduler_drain_deadline_ms());
    loop {
        if started.elapsed() >= deadline {
            let remaining = scheduler.total_pending_count().await;
            if remaining > 0 {
                warn!(
                    model = %model_id,
                    remaining,
                    elapsed_ms = started.elapsed().as_millis() as u64,
                    "rust-scheduler: drain deadline exceeded — residual items will redeliver via JetStream ack_wait",
                );
            }
            break;
        }
        match scheduler.try_consume_next().await {
            Some((op, lora, batch)) => {
                // Final-drain flushes are standalone waves (no
                // following `try_drain_same` loop here), so each
                // counts as its own primary.
                process_scheduler_batch(
                    &model_id,
                    &dispatcher,
                    &scheduler,
                    op,
                    lora,
                    batch,
                    WaveRole::Primary,
                )
                .await;
            }
            None => {
                if scheduler.total_pending_count().await == 0 {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(25)).await;
            }
        }
    }
    info!(
        model = %model_id,
        elapsed_ms = started.elapsed().as_millis() as u64,
        "rust-scheduler: drain loop exited",
    );
}

/// Decode an offloaded generate payload blob (msgpack) into the inline
/// `generate` value. Extracted so the transport contract is directly
/// testable: legacy gateway blobs carry base64-string images, while
/// sidecar-prepared or newer producers may already carry msgpack binary.
fn decode_offloaded_generate(bytes: &[u8]) -> Result<MsgValue, rmp_serde::decode::Error> {
    rmp_serde::from_slice(bytes)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
    use tracing::instrument::WithSubscriber;

    use crate::delivery::LocalDelivery;
    use crate::scheduler::{BatchConfig, Scheduler};

    #[derive(Clone, Default)]
    struct GroupLogCapture(Arc<std::sync::Mutex<Vec<u8>>>);

    impl std::io::Write for GroupLogCapture {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(bytes);
            Ok(bytes.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for GroupLogCapture {
        type Writer = Self;

        fn make_writer(&'a self) -> Self::Writer {
            self.clone()
        }
    }

    impl GroupLogCapture {
        fn completions(&self) -> Vec<serde_json::Value> {
            std::str::from_utf8(&self.0.lock().unwrap())
                .unwrap()
                .lines()
                .map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
                .filter(|event| event["fields"]["message"] == "handle_model_group: done")
                .collect()
        }
    }

    #[test]
    fn group_phase_timings_use_separate_monotonic_intervals() {
        let start = Instant::now();
        let readiness_finished = start + Duration::from_micros(2_000_999);
        let permit_started = readiness_finished + Duration::from_secs(10);
        let permit_acquired = permit_started + Duration::from_millis(123);
        let dispatch_finished = permit_acquired + Duration::from_micros(4_999);

        assert_eq!(phase_elapsed_ms(start, readiness_finished), 2_000);
        assert_eq!(phase_elapsed_ms(permit_started, permit_acquired), 123);
        assert_eq!(phase_elapsed_ms(permit_acquired, dispatch_finished), 4);
        assert_eq!(phase_elapsed_ms(start, start), 0);
        assert_eq!(phase_elapsed_ms(readiness_finished, start), 0);
        assert_eq!(duration_millis(Duration::MAX), u64::MAX);
    }

    #[tokio::test(start_paused = true)]
    async fn group_phase_timings_only_extend_completed_group_events() {
        let capture = GroupLogCapture::default();
        let subscriber = tracing_subscriber::fmt()
            .json()
            .without_time()
            .with_writer(capture.clone())
            .finish();
        let unobserved = tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default());
        let _subscriber = tracing::subscriber::set_default(subscriber);
        let backend = LoadingModelBackend::new("cold");
        let dispatcher = dispatcher_with_backend(backend.clone());
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();

        dispatcher
            .dispatch_decoded(
                local_group("unobserved-request", "unobserved", 2..3, &tx),
                1,
                Instant::now(),
            )
            .with_subscriber(unobserved.clone())
            .await;
        assert!(capture.completions().is_empty());
        dispatcher
            .dispatch_decoded(
                local_group("cold-request", "cold", 0..1, &tx),
                1,
                Instant::now(),
            )
            .await;
        assert!(capture.completions().is_empty());
        dispatcher
            .dispatch_decoded(
                local_group("warm-request", "warm", 1..2, &tx),
                1,
                Instant::now(),
            )
            .await;
        assert_eq!(capture.completions().len(), 1);
        backend.loaded.store(true, Ordering::SeqCst);
        dispatcher.join_parked_groups(Duration::from_secs(2)).await;

        let events = capture.completions();
        assert_eq!(events.len(), 2);
        assert_eq!(backend.encoded_models(), ["unobserved", "warm", "cold"]);
        for (event, model) in events.iter().zip(["warm", "cold"]) {
            assert_eq!(event["level"], "INFO");
            assert_eq!(event["target"], "sie_server_sidecar::dispatcher");
            let fields = event["fields"].as_object().unwrap();
            assert_eq!(fields.len(), 14);
            assert_eq!(fields["model"], model);
            for name in ["group_size", "encode"] {
                assert_eq!(fields[name], 1);
            }
            for name in ["score", "extract", "unknown"] {
                assert_eq!(fields[name], 0);
            }
            for name in ["encode_ok", "score_ok", "extract_ok"] {
                assert_eq!(fields[name], true);
            }
            for name in [
                "elapsed_ms",
                "model_readiness_elapsed_ms",
                "batch_permit_elapsed_ms",
                "prepare_dispatch_elapsed_ms",
            ] {
                assert!(fields[name].as_u64().is_some(), "{name}");
            }
        }
    }

    #[tokio::test]
    async fn filtered_group_phase_logs_do_not_change_dispatch() {
        let capture = GroupLogCapture::default();
        let subscriber = tracing_subscriber::fmt()
            .json()
            .with_max_level(tracing::Level::ERROR)
            .with_writer(capture.clone())
            .finish();
        let _subscriber = tracing::subscriber::set_default(subscriber);
        let backend = LoadingModelBackend::new("cold");
        let dispatcher = dispatcher_with_backend(backend.clone());
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();

        dispatcher
            .dispatch_decoded(
                local_group("warm-request", "warm", 0..1, &tx),
                1,
                Instant::now(),
            )
            .await;

        assert_eq!(backend.encoded_models(), ["warm"]);
        assert!(capture.completions().is_empty());
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    struct PipelineTestItem {
        idx: usize,
    }

    impl HasCost for PipelineTestItem {
        fn cost(&self) -> u64 {
            1
        }

        fn original_index(&self) -> usize {
            self.idx
        }
    }

    #[test]
    fn cancellation_matrix_separates_request_batch_and_generation() {
        let request = RequestCancelState::new(Duration::from_secs(60));
        let batch = BatchCancelState::default();
        request.cancel("gw-a".into(), "req-a".into());
        assert_eq!(
            classify_cancellation(&request, &batch, "gw-a", "req-a", "encode", false),
            Some(WorkCancellation::Request)
        );
        assert_eq!(
            classify_cancellation(&request, &batch, "gw-a", "req-a", "score", true),
            Some(WorkCancellation::Request)
        );
        assert_eq!(
            classify_cancellation(&request, &batch, "gw-b", "req-a", "encode", false),
            None
        );
        assert_eq!(
            classify_cancellation(&request, &batch, "gw-a", "req-a", "generate", true),
            None
        );

        batch.cancel("req-b".into());
        assert_eq!(
            classify_cancellation(&request, &batch, "gw-a", "req-b", "extract", false),
            None
        );
        assert_eq!(
            classify_cancellation(&request, &batch, "gw-a", "req-b", "extract", true),
            Some(WorkCancellation::BatchDirect)
        );
        assert_eq!(
            classify_cancellation(&request, &batch, "gw-a", "req-b", "generate", true),
            None
        );
    }

    #[test]
    fn payload_error_contract_maps_oversize_to_terminal_413_code() {
        let error = PayloadError::TooLarge {
            actual: 17,
            max: 16,
        };
        assert_eq!(
            payload_error_contract(&error),
            (PAYLOAD_TOO_LARGE_ERROR_CODE, PAYLOAD_TOO_LARGE_MESSAGE)
        );
    }

    #[test]
    fn payload_error_contract_keeps_other_store_failures_generic() {
        let error = PayloadError::InvalidRef("missing".into());
        assert_eq!(
            payload_error_contract(&error),
            (PAYLOAD_ERROR_CODE, PAYLOAD_RESOLVE_ERROR_MESSAGE)
        );
    }

    fn text_item(text: &str) -> MsgValue {
        MsgValue::Map(vec![(MsgValue::from("text"), MsgValue::from(text))])
    }

    #[tokio::test]
    async fn extract_audio_permit_only_gates_non_null_audio() {
        let permits = Arc::new(Semaphore::new(0));

        let (absent, prepared) = prepare_extract_audio(text_item("pass through"), &permits)
            .await
            .unwrap();
        assert_eq!(absent, text_item("pass through"));
        assert!(prepared.is_none());

        let null = MsgValue::Map(vec![
            (MsgValue::from("text"), MsgValue::from("pass through")),
            (MsgValue::from("audio"), MsgValue::Nil),
        ]);
        let (null, prepared) = prepare_extract_audio(null, &permits).await.unwrap();
        assert!(prepared.is_none());
        assert!(
            matches!(null, MsgValue::Map(fields) if fields == vec![(MsgValue::from("text"), MsgValue::from("pass through"))])
        );

        let duplicate = MsgValue::Map(vec![
            (MsgValue::from("audio"), MsgValue::Nil),
            (MsgValue::from("audio"), MsgValue::Nil),
        ]);
        let error = prepare_extract_audio(duplicate, &permits)
            .await
            .unwrap_err();
        assert!(error.contains("duplicate field"));

        let invalid_audio = MsgValue::Map(vec![(
            MsgValue::from("audio"),
            MsgValue::from("not an object"),
        )]);
        assert!(
            tokio::time::timeout(
                std::time::Duration::from_millis(20),
                prepare_extract_audio(invalid_audio.clone(), &permits),
            )
            .await
            .is_err(),
            "non-null audio must wait for the decode permit",
        );
        permits.add_permits(1);
        let error = prepare_extract_audio(invalid_audio, &permits)
            .await
            .unwrap_err();
        assert_eq!(error, "audio must be an object");
    }

    fn adapter_pool_with_runtime_state(runtime_state: Arc<RuntimeState>) -> Arc<AdapterWorkerPool> {
        let paths = [PathBuf::from("/tmp/sie-test-ipc-0.sock")];
        AdapterWorkerPool::new(&paths, 1, 60, 900, runtime_state)
    }

    fn wi(request: &str, idx: u32, model: &str, op: &str) -> WorkItem {
        WorkItem {
            work_item_id: format!("{}.{}", request, idx),
            request_id: request.into(),
            item_index: idx,
            total_items: 1,
            operation: op.into(),
            model_id: model.into(),
            profile_id: String::new(),
            engine: String::new(),
            pool_name: "l4".into(),
            admission_pool: String::new(),
            machine_profile: String::new(),
            item: Some(text_item("x")),
            payload_ref: None,
            output_types: None,
            instruction: None,
            is_query: false,
            options: None,
            query_item: None,
            query_payload_ref: None,
            score_items: None,
            labels: None,
            output_schema: None,
            generate: None,
            routing_key: None,
            prompt_cache_key: None,
            bundle_config_hash: String::new(),
            router_id: String::new(),
            accepts_result_chunks: false,
            reply_subject: "_INBOX.r.a".into(),
            traceparent: None,
            tracestate: None,
            timestamp: 0.0,
            deadline: None,
            fallback_reason: None,
            numerical_admission_sha256: None,
        }
    }

    fn encode_scheduler_item(work: &WorkItem) -> SchedulerItem {
        SchedulerItem::Encode(EncodeBatchItem {
            work_item_id: work.work_item_id.clone(),
            request_id: work.request_id.clone(),
            item_index: work.item_index,
            total_items: work.total_items,
            timestamp: work.timestamp,
            item: work.item.clone().expect("test item"),
            output_types: work.output_types.clone(),
            instruction: work.instruction.clone(),
            is_query: work.is_query,
            options: work.options.clone(),
            profile_id: Some(work.profile_id.clone()),
            bundle_config_hash: Some(work.bundle_config_hash.clone()),
            numerical_admission_sha256: work.numerical_admission_sha256.clone(),
            payload_fetch_ms: 0.0,
            prepared_tokens: None,
        })
    }

    /// Reports `LoadingInProgress` for one model until `loaded` is set and
    /// `Ready` for every other model; records which models were encoded.
    /// When `later_probe_delay` is set, every readiness call for the loading
    /// model after the first takes that long. Every readiness answer reports
    /// `max_batch_tokens` as the model's batch cost budget.
    struct LoadingModelBackend {
        loading_model: &'static str,
        loading_state: ReadinessState,
        loaded: AtomicBool,
        later_probe_delay: Option<Duration>,
        max_batch_tokens: Option<u64>,
        probes: std::sync::atomic::AtomicUsize,
        encoded_models: std::sync::Mutex<Vec<String>>,
    }

    impl LoadingModelBackend {
        fn new(loading_model: &'static str) -> Arc<Self> {
            Self::with_later_probe_delay(loading_model, None)
        }

        fn with_later_probe_delay(
            loading_model: &'static str,
            later_probe_delay: Option<Duration>,
        ) -> Arc<Self> {
            Self::build(loading_model, later_probe_delay, None)
        }

        fn with_max_batch_tokens(
            loading_model: &'static str,
            max_batch_tokens: Option<u64>,
        ) -> Arc<Self> {
            Self::build(loading_model, None, max_batch_tokens)
        }

        fn build(
            loading_model: &'static str,
            later_probe_delay: Option<Duration>,
            max_batch_tokens: Option<u64>,
        ) -> Arc<Self> {
            Arc::new(Self {
                loading_model,
                loading_state: ReadinessState::LoadingInProgress,
                loaded: AtomicBool::new(false),
                later_probe_delay,
                max_batch_tokens,
                probes: std::sync::atomic::AtomicUsize::new(0),
                encoded_models: std::sync::Mutex::new(Vec::new()),
            })
        }

        fn encoded_models(&self) -> Vec<String> {
            self.encoded_models.lock().unwrap().clone()
        }
    }

    #[async_trait::async_trait]
    impl crate::backend::InferenceBackend for LoadingModelBackend {
        fn name(&self) -> &'static str {
            "loading-model"
        }

        fn supports(&self, _model_id: &str) -> bool {
            true
        }

        async fn ensure_model_ready(
            &self,
            model_id: &str,
        ) -> Result<crate::ipc_types::EnsureModelReadyResponse, BackendError> {
            if model_id == self.loading_model && self.probes.fetch_add(1, Ordering::SeqCst) > 0 {
                if let Some(delay) = self.later_probe_delay {
                    tokio::time::sleep(delay).await;
                }
            }
            let state = if model_id == self.loading_model && !self.loaded.load(Ordering::SeqCst) {
                self.loading_state.clone()
            } else {
                ReadinessState::Ready
            };
            Ok(crate::ipc_types::EnsureModelReadyResponse {
                state,
                batch_budget: None,
                descriptor: None,
                max_batch_tokens: self.max_batch_tokens,
            })
        }

        async fn process_encode_batch(
            &self,
            req: ProcessEncodeBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            self.encoded_models
                .lock()
                .unwrap()
                .push(req.model_id.clone());
            let outcomes = req
                .items
                .iter()
                .map(|item| {
                    outcome(
                        &item.request_id,
                        item.item_index,
                        Disposition::NakRetry,
                        None,
                        None,
                    )
                })
                .collect();
            Ok(BatchOutcome {
                outcomes,
                batched_f16_multivectors: Vec::new(),
            })
        }

        async fn process_score_batch(
            &self,
            _req: ProcessScoreBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            Err(BackendError::UnsupportedModel("score".into()))
        }

        async fn process_extract_batch(
            &self,
            _req: ProcessExtractBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            Err(BackendError::UnsupportedModel("extract".into()))
        }
    }

    fn dispatcher_with_backend(backend: SharedBackend) -> Arc<Dispatcher> {
        let runtime_state = Arc::new(RuntimeState::new());
        Arc::new(Dispatcher::new(
            backend,
            adapter_pool_with_runtime_state(Arc::clone(&runtime_state)),
            Arc::new(crate::payload_store::LocalPayloadStore::new(
                None::<PathBuf>,
            )),
            None,
            "worker-test".into(),
            runtime_state,
            Arc::new(Mutex::new(LatencyTracker::new(200, 10))),
            TokenizerRegistry::empty(),
            None,
            None,
            None,
            None,
            BatchCancelState::default(),
            RequestCancelState::new(Duration::from_secs(60)),
        ))
    }

    fn local_group(
        request: &str,
        model: &str,
        slots: std::ops::Range<u32>,
        tx: &tokio::sync::mpsc::UnboundedSender<crate::delivery::LocalDeliveryEvent>,
    ) -> Vec<(WorkItem, Delivery)> {
        slots
            .map(|slot| {
                (
                    wi(request, slot, model, "encode"),
                    Delivery::Local(LocalDelivery::new(slot as usize, 0, tx.clone())),
                )
            })
            .collect()
    }

    #[tokio::test(start_paused = true)]
    async fn loading_model_group_is_parked_while_other_models_dispatch() {
        let backend = LoadingModelBackend::new("cold");
        let dispatcher = dispatcher_with_backend(backend.clone());
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();

        // Under the paused clock any wait for the load would run the
        // timeout out; parking returns without waiting.
        tokio::time::timeout(
            Duration::from_secs(1),
            dispatcher.dispatch_decoded(
                local_group("cold-req", "cold", 0..3, &tx),
                3,
                Instant::now(),
            ),
        )
        .await
        .expect("a loading model must not hold the dispatch call");
        assert_eq!(
            dispatcher.batch_semaphore.available_permits(),
            default_max_concurrent_batches(),
            "a parked group must not hold a batch permit"
        );

        tokio::time::timeout(
            Duration::from_secs(1),
            dispatcher.dispatch_decoded(
                local_group("warm-req", "warm", 3..4, &tx),
                1,
                Instant::now(),
            ),
        )
        .await
        .expect("a loaded model must dispatch while another model loads");
        assert_eq!(backend.encoded_models(), vec!["warm".to_string()]);

        backend.loaded.store(true, Ordering::SeqCst);
        dispatcher.join_parked_groups(Duration::from_secs(60)).await;
        assert_eq!(
            backend.encoded_models(),
            vec!["warm".to_string(), "cold".to_string()],
            "the parked group dispatches once its model is ready"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn parked_group_is_naked_when_its_model_never_becomes_ready() {
        let backend = LoadingModelBackend::new("cold");
        let dispatcher = dispatcher_with_backend(backend.clone());
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();

        dispatcher
            .dispatch_decoded(
                local_group("cold-req", "cold", 0..2, &tx),
                2,
                Instant::now(),
            )
            .await;
        dispatcher
            .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)
            .await;

        let mut retried = Vec::new();
        while let Ok(event) = rx.try_recv() {
            match event {
                crate::delivery::LocalDeliveryEvent::Retry { slot, delay_ms, .. } => {
                    retried.push((slot, delay_ms));
                }
                crate::delivery::LocalDeliveryEvent::Result { slot, .. } => {
                    panic!("slot {slot} settled with a result instead of a retry")
                }
            }
        }
        retried.sort_unstable();
        assert_eq!(
            retried,
            vec![(0, base_nak_delay_ms()), (1, base_nak_delay_ms())]
        );
        assert!(backend.encoded_models().is_empty());
    }

    /// Every model is ready; every encode item comes back as `NakRetry`
    /// carrying `outcome`'s error code, retry hint and delay.
    struct NakingBackend {
        error_code: Option<&'static str>,
        retry_after_s: Option<u32>,
        nak_delay_ms: Option<u64>,
        encoded: std::sync::atomic::AtomicUsize,
    }

    #[async_trait::async_trait]
    impl crate::backend::InferenceBackend for NakingBackend {
        fn name(&self) -> &'static str {
            "naking"
        }

        fn supports(&self, _model_id: &str) -> bool {
            true
        }

        async fn ensure_model_ready(
            &self,
            _model_id: &str,
        ) -> Result<crate::ipc_types::EnsureModelReadyResponse, BackendError> {
            Ok(crate::ipc_types::EnsureModelReadyResponse {
                state: ReadinessState::Ready,
                batch_budget: None,
                descriptor: None,
                max_batch_tokens: None,
            })
        }

        async fn process_encode_batch(
            &self,
            req: ProcessEncodeBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            self.encoded.fetch_add(req.items.len(), Ordering::SeqCst);
            let outcomes = req
                .items
                .iter()
                .map(|item| ItemOutcome {
                    nak_delay_ms: self.nak_delay_ms,
                    error_code: self.error_code.map(str::to_string),
                    retry_after_s: self.retry_after_s,
                    ..outcome(
                        &item.request_id,
                        item.item_index,
                        Disposition::NakRetry,
                        None,
                        None,
                    )
                })
                .collect();
            Ok(BatchOutcome {
                outcomes,
                batched_f16_multivectors: Vec::new(),
            })
        }

        async fn process_score_batch(
            &self,
            _req: ProcessScoreBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            Err(BackendError::UnsupportedModel("score".into()))
        }

        async fn process_extract_batch(
            &self,
            _req: ProcessExtractBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            Err(BackendError::UnsupportedModel("extract".into()))
        }
    }

    fn naking_backend(
        error_code: Option<&'static str>,
        retry_after_s: Option<u32>,
        nak_delay_ms: Option<u64>,
    ) -> Arc<NakingBackend> {
        Arc::new(NakingBackend {
            error_code,
            retry_after_s,
            nak_delay_ms,
            encoded: std::sync::atomic::AtomicUsize::new(0),
        })
    }

    async fn settle_one(
        dispatcher: &Arc<Dispatcher>,
        work: WorkItem,
    ) -> Vec<crate::delivery::LocalDeliveryEvent> {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        dispatcher
            .dispatch_decoded(
                vec![(work, Delivery::Local(LocalDelivery::new(0, 0, tx)))],
                1,
                Instant::now(),
            )
            .await;
        dispatcher.join_parked_groups(Duration::from_secs(5)).await;
        let mut events = Vec::new();
        while let Ok(event) = rx.try_recv() {
            events.push(event);
        }
        events
    }

    fn fallback_attempt(model: &str) -> WorkItem {
        WorkItem {
            fallback_reason: Some("model_loading".to_string()),
            ..wi("bridge", 0, model, "encode")
        }
    }

    #[tokio::test]
    async fn a_fallback_attempt_is_answered_at_once_where_other_work_is_redelivered() {
        let dispatcher = dispatcher_with_backend(naking_backend(None, None, Some(2_500)));

        let ordinary = settle_one(&dispatcher, wi("plain", 0, "acme/model:remote", "encode")).await;
        let bridged = settle_one(&dispatcher, fallback_attempt("acme/model:remote")).await;

        assert!(
            matches!(
                ordinary.as_slice(),
                [crate::delivery::LocalDeliveryEvent::Retry {
                    slot: 0,
                    delay_ms: 2_500,
                    ..
                }]
            ),
            "{ordinary:?}"
        );
        let [crate::delivery::LocalDeliveryEvent::Result { slot: 0, result }] = bridged.as_slice()
        else {
            panic!("a fallback attempt must settle with a result: {bridged:?}");
        };
        assert!(!result.success);
        assert_eq!(result.error_code.as_deref(), Some(QUEUE_FULL_ERROR_CODE));
        assert_eq!(
            result.retry_after_s,
            Some(3),
            "the NAK delay, rounded up to seconds"
        );
        assert_eq!(result.error.as_deref(), Some(FALLBACK_REFUSAL_MESSAGE));
    }

    #[tokio::test]
    async fn an_admitted_item_is_answered_at_once_even_without_a_held_refusal() {
        let dispatcher = dispatcher_with_backend(naking_backend(None, None, None));
        let admitted = WorkItem {
            numerical_admission_sha256: Some("a".repeat(64)),
            ..wi("admitted", 0, "acme/model:remote", "encode")
        };
        let refusal = ItemOutcome {
            nak_delay_ms: Some(1_000),
            error_code: Some(INFERENCE_ERROR_CODE.to_string()),
            ..outcome("admitted", 0, Disposition::NakRetry, None, None)
        };
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();

        dispatcher
            .apply_outcome(
                &admitted,
                &Delivery::Local(LocalDelivery::new(0, 0, tx)),
                &refusal,
                0.0,
                None,
            )
            .await;

        let Ok(crate::delivery::LocalDeliveryEvent::Result { slot: 0, result }) = rx.try_recv()
        else {
            panic!("an admitted item must settle with a result");
        };
        assert!(!result.success);
        assert_eq!(result.error_code.as_deref(), Some(INFERENCE_ERROR_CODE));
        assert_eq!(result.retry_after_s, Some(1));
    }

    #[tokio::test]
    async fn the_scheduler_less_path_answers_admitted_items_without_the_backend() {
        for op in ["encode", "score"] {
            let backend = naking_backend(None, None, Some(2_500));
            let mut dispatcher = dispatcher_with_backend(backend.clone());
            Arc::get_mut(&mut dispatcher).unwrap().config_apply_state =
                Some(Arc::new(ConfigApplyState::new("fresh".into())));

            let events = settle_one(
                &dispatcher,
                WorkItem {
                    numerical_admission_sha256: Some("a".repeat(64)),
                    bundle_config_hash: "fresh".into(),
                    ..wi("admitted", 0, "acme/model:remote", op)
                },
            )
            .await;

            let [crate::delivery::LocalDeliveryEvent::Result { slot: 0, result }] =
                events.as_slice()
            else {
                panic!("{op}: an admitted item must settle with a result: {events:?}");
            };
            assert!(!result.success, "{op}");
            assert_eq!(
                result.error_code.as_deref(),
                Some(INFERENCE_ERROR_CODE),
                "{op}"
            );
            assert_eq!(result.retry_after_s, Some(1), "{op}");
            assert_eq!(backend.encoded.load(Ordering::SeqCst), 0, "{op}");
        }
    }

    #[tokio::test]
    async fn a_fallback_refusal_keeps_the_engines_code_and_retry_hint() {
        let dispatcher =
            dispatcher_with_backend(naking_backend(Some("MODEL_LOADING"), Some(7), None));

        let bridged = settle_one(&dispatcher, fallback_attempt("acme/model:remote")).await;

        let [crate::delivery::LocalDeliveryEvent::Result { result, .. }] = bridged.as_slice()
        else {
            panic!("a fallback attempt must settle with a result: {bridged:?}");
        };
        assert_eq!(result.error_code.as_deref(), Some("MODEL_LOADING"));
        assert_eq!(result.retry_after_s, Some(7));
    }

    #[tokio::test]
    async fn a_gateway_bridge_whose_upstream_refuses_is_answered_with_the_upstreams_wait() {
        let fixture: serde_json::Value =
            serde_json::from_str(include_str!("../../wire-fixtures/serving_disclosure.json"))
                .unwrap();
        let dispatcher = dispatcher_with_backend(naking_backend(
            Some(QUEUE_FULL_ERROR_CODE),
            Some(7),
            Some(base_nak_delay_ms()),
        ));
        for trigger in fixture["response_headers"]["fallback_reason"]["values"]
            .as_array()
            .unwrap()
        {
            let mut wire: rmpv::Value = rmp_serde::from_slice(
                &rmp_serde::to_vec_named(&wi("bridge", 0, "acme/model:remote", "encode")).unwrap(),
            )
            .unwrap();
            let rmpv::Value::Map(fields) = &mut wire else {
                unreachable!("a work item is a msgpack map")
            };
            fields.push(("fallback_reason".into(), trigger.as_str().unwrap().into()));
            let work: WorkItem =
                rmp_serde::from_slice(&rmp_serde::to_vec_named(&wire).unwrap()).unwrap();

            let events = settle_one(&dispatcher, work).await;

            let [crate::delivery::LocalDeliveryEvent::Result { result, .. }] = events.as_slice()
            else {
                panic!("{trigger}: a bridged item must settle with a result: {events:?}");
            };
            assert!(!result.success);
            assert_eq!(result.error_code.as_deref(), Some(QUEUE_FULL_ERROR_CODE));
            assert_eq!(result.retry_after_s, Some(7), "{trigger}");
        }
    }

    #[tokio::test]
    async fn a_load_only_work_item_settles_once_its_model_is_ready_without_running() {
        let backend = naking_backend(None, None, None);
        let dispatcher = dispatcher_with_backend(backend.clone());

        let events = settle_one(
            &dispatcher,
            WorkItem {
                item: None,
                ..wi("load", 0, "acme/model", LOAD_OPERATION)
            },
        )
        .await;

        assert!(events.is_empty(), "a load publishes nothing: {events:?}");
        assert_eq!(backend.encoded.load(Ordering::SeqCst), 0);
    }

    fn dispatcher_listing_unsupported(
        backend: SharedBackend,
        unsupported: &[&str],
    ) -> (Arc<Dispatcher>, Arc<ConfigApplyState>) {
        let state = Arc::new(ConfigApplyState::new(String::new()));
        assert!(state.mark_export_reconciled(
            1,
            Some("hash-1".into()),
            unsupported.iter().map(|m| (*m).to_string()).collect(),
            false
        ));
        let runtime_state = Arc::new(RuntimeState::new());
        let dispatcher = Arc::new(Dispatcher::new(
            backend,
            adapter_pool_with_runtime_state(Arc::clone(&runtime_state)),
            Arc::new(crate::payload_store::LocalPayloadStore::new(
                None::<PathBuf>,
            )),
            None,
            "worker-test".into(),
            runtime_state,
            Arc::new(Mutex::new(LatencyTracker::new(200, 10))),
            TokenizerRegistry::empty(),
            None,
            None,
            Some(Arc::clone(&state)),
            None,
            BatchCancelState::default(),
            RequestCancelState::new(Duration::from_secs(60)),
        ));
        (dispatcher, state)
    }

    #[tokio::test]
    async fn readiness_rechecks_a_model_listed_after_intake() {
        let backend = LoadingModelBackend::new("org/new-family");
        let (dispatcher, state) = dispatcher_listing_unsupported(backend.clone(), &[]);
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let items = local_group("new-req", "org/new-family", 0..2, &tx);

        assert!(state.mark_export_reconciled(
            2,
            Some("hash-2".into()),
            vec!["org/new-family".into()],
            false
        ));
        let readiness = dispatcher
            .ensure_model_ready_by("org/new-family", &items, None)
            .await;

        assert!(readiness.is_none());
        assert_eq!(backend.probes.load(Ordering::SeqCst), 0);
        assert_eq!(retried_slots(&mut rx), [0, 1]);
    }

    #[tokio::test]
    async fn unsupported_model_group_is_naked_before_readiness_or_backend_ipc() {
        let backend = LoadingModelBackend::new("org/new-family");
        let state = Arc::new(ConfigApplyState::new(String::new()));
        assert!(state.mark_export_reconciled(
            1,
            Some("hash-1".into()),
            vec!["org/new-family".into()],
            false
        ));
        let runtime_state = Arc::new(RuntimeState::new());
        let dispatcher = Arc::new(Dispatcher::new(
            backend.clone(),
            adapter_pool_with_runtime_state(Arc::clone(&runtime_state)),
            Arc::new(crate::payload_store::LocalPayloadStore::new(
                None::<PathBuf>,
            )),
            None,
            "worker-test".into(),
            runtime_state,
            Arc::new(Mutex::new(LatencyTracker::new(200, 10))),
            TokenizerRegistry::empty(),
            None,
            None,
            Some(state),
            None,
            BatchCancelState::default(),
            RequestCancelState::new(Duration::from_secs(60)),
        ));
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let mut items = local_group("new-req", "org/new-family", 0..2, &tx);
        items.extend(local_group("kept-req", "org/kept", 5..6, &tx));
        for (wi, _) in &mut items {
            wi.bundle_config_hash = "hash-1".into();
        }

        dispatcher.dispatch_decoded(items, 3, Instant::now()).await;
        dispatcher
            .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)
            .await;

        let retried = retried_slots(&mut rx);
        assert!(retried.contains(&0) && retried.contains(&1));
        assert_eq!(backend.probes.load(Ordering::SeqCst), 0);
        assert_eq!(backend.encoded_models(), ["org/kept"]);
    }

    fn retried_slots(
        rx: &mut tokio::sync::mpsc::UnboundedReceiver<crate::delivery::LocalDeliveryEvent>,
    ) -> Vec<usize> {
        let mut slots = Vec::new();
        while let Ok(event) = rx.try_recv() {
            if let crate::delivery::LocalDeliveryEvent::Retry { slot, .. } = event {
                slots.push(slot);
            }
        }
        slots.sort_unstable();
        slots
    }

    /// Far longer than any readiness deadline the tests use.
    const STALLED_PROBE: Duration = Duration::from_secs(1_000_000);

    #[tokio::test]
    async fn generation_publish_to_a_subject_other_than_the_work_item_reply_is_refused() {
        let client = async_nats::ConnectOptions::new()
            .retry_on_initial_connect()
            .connect("nats://127.0.0.1:1")
            .await
            .expect("an offline client needs no server");
        let telemetry = crate::observability::metrics::SidecarTelemetry::default();
        let publisher = Arc::new(WorkPublisher::new(
            client.clone(),
            "worker-test",
            telemetry.clone(),
        ));
        let message = Message {
            message: async_nats::Message {
                subject: "sie.work.test".into(),
                reply: None,
                payload: Default::default(),
                headers: None,
                status: None,
                description: None,
                length: 0,
            },
            context: async_nats::jetstream::new(client),
        };
        let delivery = DeliveryContext::from_message(&message);
        let delivery_log = Arc::new(GenerateDeliveryLogContext {
            work_item_id: "wi-1".to_string(),
            request_id: "req-1".to_string(),
            model_id: "model".to_string(),
            reply_subject: "_INBOX.router.req-1".to_string(),
            delivery,
        });
        for subject in ["$JS.API.STREAM.CREATE.X", "sie.config.models._all", ""] {
            let result = handle_generate_event(
                GenerateEvent {
                    kind: "publish".to_string(),
                    reply_subject: subject.to_string(),
                    payload: Vec::new(),
                    delay_ms: None,
                    error: None,
                },
                Arc::clone(&publisher),
                telemetry.clone(),
                Arc::new(AtomicBool::new(false)),
                Arc::new(QueuedMessage::new(message.clone(), None)),
                Arc::clone(&delivery_log),
                "",
            )
            .await;
            let error = result.expect_err(subject).to_string();
            assert!(
                error.contains("reply_subject mismatch"),
                "{subject}: {error}"
            );
        }
    }

    /// A NATS delivery whose ACK, NAK and progress calls fail: it has no
    /// reply subject and its client never reaches a server.
    async fn unacknowledgeable_nats_delivery() -> Delivery {
        let client = async_nats::ConnectOptions::new()
            .retry_on_initial_connect()
            .connect("nats://127.0.0.1:1")
            .await
            .expect("an offline client needs no server");
        let message = Message {
            message: async_nats::Message {
                subject: "sie.work.test".into(),
                reply: None,
                payload: Default::default(),
                headers: None,
                status: None,
                description: None,
                length: 0,
            },
            context: async_nats::jetstream::new(client),
        };
        Delivery::Nats(message, None, None)
    }

    async fn authority_test_delivery() -> Delivery {
        let mut delivery = unacknowledgeable_nats_delivery().await;
        if let Delivery::Nats(message, ..) = &mut delivery {
            message.message.subject =
                "sie.work.test.machine.bundle.cold.worker.execution-authority-v1".into();
        }
        delivery
    }

    async fn admission_test_delivery() -> Delivery {
        let mut delivery = unacknowledgeable_nats_delivery().await;
        if let Delivery::Nats(message, ..) = &mut delivery {
            message.message.subject =
                "sie.work.test.machine.bundle.cold.worker.numerical-admission-v1".into();
        }
        delivery
    }

    #[tokio::test]
    async fn stale_authority_generation_refuses_before_readiness_or_payload_fetch() {
        let backend = LoadingModelBackend::new("cold");
        let mut dispatcher = dispatcher_with_backend(backend.clone());
        Arc::get_mut(&mut dispatcher).unwrap().config_apply_state =
            Some(Arc::new(ConfigApplyState::new("fresh".into())));
        dispatcher
            .worker_pool
            .execution_authority_v1()
            .store(true, Ordering::Release);
        let mut work = wi("verified", 0, "cold", "generate");
        work.bundle_config_hash = "stale".into();
        work.payload_ref = Some("must-not-fetch".into());
        let Delivery::Nats(message, permit, _) = authority_test_delivery().await else {
            unreachable!()
        };
        dispatcher
            .handle_generate_item(work, QueuedMessage::new(message, permit))
            .await;
        assert_eq!(backend.probes.load(Ordering::SeqCst), 0);
        assert!(backend.encoded_models().is_empty());
    }

    #[tokio::test]
    async fn mismatched_authority_generation_refuses_before_readiness_or_payload_fetch() {
        let backend = LoadingModelBackend::new("cold");
        let mut dispatcher = dispatcher_with_backend(backend.clone());
        Arc::get_mut(&mut dispatcher).unwrap().config_apply_state =
            Some(Arc::new(ConfigApplyState::new("fresh".into())));
        dispatcher
            .worker_pool
            .execution_authority_v1()
            .store(true, Ordering::Release);
        let mut work = wi("verified", 0, "another", "generate");
        work.bundle_config_hash = "fresh".into();
        work.payload_ref = Some("must-not-fetch".into());
        let Delivery::Nats(message, permit, _) = authority_test_delivery().await else {
            unreachable!()
        };
        dispatcher
            .handle_generate_item(work, QueuedMessage::new(message, permit))
            .await;
        assert_eq!(backend.probes.load(Ordering::SeqCst), 0);
        assert!(backend.encoded_models().is_empty());
    }

    /// Ready backend whose descriptor reports `width`. Holds every
    /// `RunBatch` until `release` has a permit for it, recording each
    /// batch's size and the most batches in flight at once.
    struct EngineBatchedBackend {
        width: std::sync::Mutex<Option<u32>>,
        sizes: std::sync::Mutex<Vec<usize>>,
        active: std::sync::atomic::AtomicUsize,
        peak: std::sync::atomic::AtomicUsize,
        release: Semaphore,
    }

    impl EngineBatchedBackend {
        fn new(width: Option<u32>) -> Arc<Self> {
            Arc::new(Self {
                width: std::sync::Mutex::new(width),
                sizes: std::sync::Mutex::new(Vec::new()),
                active: std::sync::atomic::AtomicUsize::new(0),
                peak: std::sync::atomic::AtomicUsize::new(0),
                release: Semaphore::new(0),
            })
        }

        /// Batch sizes and peak in flight since the last call.
        fn take_observations(&self) -> (Vec<usize>, usize) {
            let sizes = std::mem::take(&mut *self.sizes.lock().unwrap());
            (sizes, self.peak.swap(0, Ordering::SeqCst))
        }
    }

    #[async_trait::async_trait]
    impl crate::backend::InferenceBackend for EngineBatchedBackend {
        fn name(&self) -> &'static str {
            "engine-batched"
        }

        fn supports(&self, _model_id: &str) -> bool {
            true
        }

        async fn ensure_model_ready(
            &self,
            _model_id: &str,
        ) -> Result<crate::ipc_types::EnsureModelReadyResponse, BackendError> {
            Ok(crate::ipc_types::EnsureModelReadyResponse {
                state: ReadinessState::Ready,
                batch_budget: None,
                descriptor: Some(ModelDescriptor {
                    supports_run_batch: true,
                    max_concurrent_dispatch: *self.width.lock().unwrap(),
                    ..Default::default()
                }),
                max_batch_tokens: None,
            })
        }

        async fn process_encode_batch(
            &self,
            _req: ProcessEncodeBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            Err(BackendError::UnsupportedModel("encode".into()))
        }

        async fn process_score_batch(
            &self,
            _req: ProcessScoreBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            Err(BackendError::UnsupportedModel("score".into()))
        }

        async fn process_extract_batch(
            &self,
            _req: ProcessExtractBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            Err(BackendError::UnsupportedModel("extract".into()))
        }

        async fn run_batch(&self, req: RunBatchRequest) -> Result<BatchOutcome, BackendError> {
            self.sizes.lock().unwrap().push(req.items.len());
            let now = self.active.fetch_add(1, Ordering::SeqCst) + 1;
            self.peak.fetch_max(now, Ordering::SeqCst);
            self.release
                .acquire()
                .await
                .expect("release stays open")
                .forget();
            self.active.fetch_sub(1, Ordering::SeqCst);
            let outcomes = req
                .items
                .iter()
                .map(|item| {
                    outcome(
                        &item.request_id,
                        item.item_index,
                        Disposition::NakRetry,
                        None,
                        None,
                    )
                })
                .collect();
            Ok(BatchOutcome {
                outcomes,
                batched_f16_multivectors: Vec::new(),
            })
        }
    }

    /// A dispatcher with the production scheduler wired in.
    fn scheduled_dispatcher(
        backend: Arc<EngineBatchedBackend>,
    ) -> (Arc<Dispatcher>, Arc<Shutdown>) {
        let mut dispatcher = dispatcher_with_backend(backend);
        let shutdown = Arc::new(Shutdown::new());
        let mutable = Arc::get_mut(&mut dispatcher).unwrap();
        mutable.scheduler_registry = Some(Arc::new(ProductionSchedulerRegistry::new(
            crate::scheduler::BatchConfig::default(),
        )));
        mutable.shutdown = Some(Arc::clone(&shutdown));
        (dispatcher, shutdown)
    }

    /// Send `slots` one-page extract requests for model "ocr", then give the
    /// scheduler time to send all it will while the backend holds them.
    async fn send_extract_pages(
        dispatcher: &Arc<Dispatcher>,
        prefix: &str,
        slots: std::ops::Range<u32>,
        tx: &tokio::sync::mpsc::UnboundedSender<crate::delivery::LocalDeliveryEvent>,
    ) {
        let count = slots.len();
        let group = slots
            .map(|slot| {
                (
                    wi(&format!("{prefix}-{slot}"), 0, "ocr", "extract"),
                    Delivery::Local(LocalDelivery::new(slot as usize, 0, tx.clone())),
                )
            })
            .collect();
        dispatcher
            .dispatch_decoded(group, count, Instant::now())
            .await;
        tokio::time::sleep(Duration::from_secs(1)).await;
    }

    async fn stop_scheduled(dispatcher: &Arc<Dispatcher>, shutdown: &Shutdown) {
        shutdown.fire();
        for handle in dispatcher.take_scheduler_drain_handles().await {
            handle.abort();
        }
    }

    /// Dispatch `items` single-page extract requests for one model and
    /// return the `RunBatch` sizes, the peak in flight before any batch
    /// finished, and the model's pipeline depth.
    async fn run_extract_group(width: Option<u32>, items: u32) -> (Vec<usize>, usize, usize) {
        let backend = EngineBatchedBackend::new(width);
        let (dispatcher, shutdown) = scheduled_dispatcher(backend.clone());
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        send_extract_pages(&dispatcher, "page", 0..items, &tx).await;
        let (sizes, peak) = backend.take_observations();
        let depth = dispatcher.model_pipeline("ocr").depth();
        backend.release.add_permits(items as usize);
        tokio::time::sleep(Duration::from_secs(1)).await;
        stop_scheduled(&dispatcher, &shutdown).await;
        (sizes, peak, depth)
    }

    #[tokio::test(start_paused = true)]
    async fn engine_batched_extract_items_run_alone_and_all_at_once() {
        let (sizes, peak, depth) = run_extract_group(Some(8), 6).await;
        assert_eq!(depth, 8, "the model's pipeline depth follows its width");
        assert_eq!(sizes, vec![1; 6], "each page is its own RunBatch");
        assert_eq!(peak, 6, "every page is in flight before any finishes");
    }

    #[tokio::test(start_paused = true)]
    async fn extract_items_still_share_batches_without_a_dispatch_width() {
        let (sizes, peak, depth) = run_extract_group(None, 6).await;
        assert_eq!(depth, pipeline_depth());
        assert_eq!(sizes.iter().sum::<usize>(), 6);
        assert!(sizes.iter().any(|&size| size > 1), "sizes {sizes:?}");
        assert!(peak <= pipeline_depth(), "peak {peak}");
    }

    #[tokio::test(start_paused = true)]
    async fn a_larger_width_reported_later_widens_the_running_pipeline() {
        let backend = EngineBatchedBackend::new(None);
        let (dispatcher, shutdown) = scheduled_dispatcher(backend.clone());
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();

        // First traffic starts the drain loop at the default depth. One page
        // keeps the loop idle afterwards, so the next group flushes at once
        // instead of on the batch former's wall-clock windows.
        send_extract_pages(&dispatcher, "before", 0..1, &tx).await;
        backend.release.add_permits(1);
        tokio::time::sleep(Duration::from_secs(1)).await;
        assert_eq!(dispatcher.model_pipeline("ocr").depth(), pipeline_depth());
        backend.take_observations();

        // A reload reports width 8: the same loop now runs every page at once.
        *backend.width.lock().unwrap() = Some(8);
        send_extract_pages(&dispatcher, "after", 1..7, &tx).await;
        let (sizes, peak) = backend.take_observations();
        assert_eq!(dispatcher.model_pipeline("ocr").depth(), 8);
        assert_eq!(sizes, vec![1; 6]);
        assert_eq!(peak, 6);

        backend.release.add_permits(6);
        tokio::time::sleep(Duration::from_secs(1)).await;
        stop_scheduled(&dispatcher, &shutdown).await;
    }

    /// One-page extract requests `slots` for model "ocr", each its own
    /// request, submitted together.
    async fn send_extract_requests(
        dispatcher: &Arc<Dispatcher>,
        prefix: &str,
        slots: std::ops::Range<u32>,
        tx: &tokio::sync::mpsc::UnboundedSender<crate::delivery::LocalDeliveryEvent>,
    ) {
        send_extract_pages(dispatcher, prefix, slots, tx).await;
    }

    #[tokio::test(start_paused = true)]
    async fn requests_arriving_during_a_forward_leave_as_one_batch_when_it_returns() {
        // An engine that runs one batch at a time (no dispatch width).
        let backend = EngineBatchedBackend::new(None);
        let (dispatcher, shutdown) = scheduled_dispatcher(backend.clone());
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();

        // A request on an idle lane goes out alone, at once.
        send_extract_requests(&dispatcher, "first", 0..1, &tx).await;
        assert_eq!(backend.take_observations(), (vec![1], 1));

        // Four more arrive, one after another, while it is with the engine.
        // Nothing is sent behind it, though the pipeline has a second slot
        // and every flush window has long passed.
        for slot in 1..5 {
            send_extract_requests(&dispatcher, "during", slot..slot + 1, &tx).await;
        }
        assert_eq!(backend.take_observations(), (vec![], 0));

        // The first returns: the four leave together.
        backend.release.add_permits(1);
        tokio::time::sleep(Duration::from_secs(1)).await;
        assert_eq!(backend.take_observations(), (vec![4], 1));

        backend.release.add_permits(1);
        tokio::time::sleep(Duration::from_secs(1)).await;
        stop_scheduled(&dispatcher, &shutdown).await;
    }

    #[tokio::test(start_paused = true)]
    async fn a_full_batch_is_sent_ahead_of_the_return() {
        let backend = EngineBatchedBackend::new(None);
        let (dispatcher, shutdown) = scheduled_dispatcher(backend.clone());
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();

        send_extract_requests(&dispatcher, "first", 0..1, &tx).await;
        // Twelve requests fill the default item cap: holding them cannot
        // improve the batch, so it takes the second pipeline slot.
        send_extract_requests(&dispatcher, "burst", 1..13, &tx).await;
        // One more is held: both slots are taken.
        send_extract_requests(&dispatcher, "late", 13..14, &tx).await;
        assert_eq!(backend.take_observations(), (vec![1, 12], 2));

        backend.release.add_permits(3);
        tokio::time::sleep(Duration::from_secs(1)).await;
        assert_eq!(backend.take_observations().0, vec![1]);
        stop_scheduled(&dispatcher, &shutdown).await;
    }

    #[tokio::test(start_paused = true)]
    async fn a_request_cut_by_the_item_cap_leaves_as_full_batches_then_its_remainder() {
        let backend = EngineBatchedBackend::new(None);
        let (dispatcher, shutdown) = scheduled_dispatcher(backend.clone());
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();

        // Default caps: 12 items a batch. One request of 32 items: two full
        // batches take the two pipeline slots and the last 8 follow as soon
        // as one frees, as they always did. The caller is waiting on the
        // earlier parts, so the rest is neither held nor gathered for.
        let group = (0..32u32)
            .map(|index| {
                let mut item = wi("states", index, "ocr", "extract");
                item.total_items = 32;
                (
                    item,
                    Delivery::Local(LocalDelivery::new(index as usize, 0, tx.clone())),
                )
            })
            .collect();
        dispatcher.dispatch_decoded(group, 32, Instant::now()).await;
        tokio::time::sleep(Duration::from_secs(1)).await;
        assert_eq!(backend.take_observations(), (vec![12, 12], 2));

        backend.release.add_permits(1);
        tokio::time::sleep(Duration::from_secs(1)).await;
        assert_eq!(backend.take_observations(), (vec![8], 2));

        backend.release.add_permits(2);
        tokio::time::sleep(Duration::from_secs(1)).await;
        stop_scheduled(&dispatcher, &shutdown).await;
    }

    #[test]
    fn only_extract_on_an_engine_batched_model_dispatches_alone() {
        let dispatcher = dispatcher_with_backend(EngineBatchedBackend::new(None));
        let wide = ModelDescriptor {
            max_concurrent_dispatch: Some(128),
            ..Default::default()
        };
        dispatcher.record_dispatch_width("ocr", Some(&wide));
        assert_eq!(dispatcher.dispatch_width("ocr"), 128);
        assert!(dispatcher.dispatches_items_alone("ocr", SchedOp::Extract));
        assert!(!dispatcher.dispatches_items_alone("ocr", SchedOp::Encode));
        assert!(!dispatcher.dispatches_items_alone("other", SchedOp::Extract));

        // A reload that no longer reports a width restores batching.
        dispatcher.record_dispatch_width("ocr", Some(&ModelDescriptor::default()));
        assert_eq!(dispatcher.dispatch_width("ocr"), 1);
        assert!(!dispatcher.dispatches_items_alone("ocr", SchedOp::Extract));
        assert_eq!(dispatcher.pipeline_depth_for("ocr"), pipeline_depth());
    }

    #[tokio::test]
    async fn half_wired_scheduler_cannot_downgrade_verified_numeric_work() {
        let backend = LoadingModelBackend::new("cold");
        let mut dispatcher = dispatcher_with_backend(backend.clone());
        let mutable = Arc::get_mut(&mut dispatcher).unwrap();
        mutable.config_apply_state = Some(Arc::new(ConfigApplyState::new("fresh".into())));
        mutable.scheduler_registry = Some(Arc::new(ProductionSchedulerRegistry::new(
            crate::scheduler::BatchConfig::from_env_or_default(),
        )));
        mutable.shutdown = None;
        dispatcher
            .worker_pool
            .execution_authority_v1()
            .store(true, Ordering::Release);
        let mut work = wi("verified", 0, "cold", "encode");
        work.bundle_config_hash = "fresh".into();
        dispatcher
            .dispatch_decoded(
                vec![(work, authority_test_delivery().await)],
                1,
                Instant::now(),
            )
            .await;
        assert_eq!(backend.probes.load(Ordering::SeqCst), 0);
        assert!(backend.encoded_models().is_empty());
    }

    #[test]
    fn the_admission_subject_carries_exactly_the_admitted_numerical_work() {
        let admission = "sie.work.p.m.b.model.worker.numerical-admission-v1";
        let authority = "sie.work.p.m.b.model.worker.execution-authority-v1";
        let direct = "sie.work.p.m.b.model.worker";
        let pooled = "sie.work.p.m.b.model";
        let off = Some("admitted_work_off_the_admission_subject");
        let unadmitted = Some("unadmitted_work_on_the_admission_subject");
        let not_numerical = Some("admitted_work_is_not_encode_or_score");
        let bridge = Some("numerical_fallback_without_admission");
        for (subject, model, op, token, fallback, violation) in [
            (admission, "model", "encode", true, true, None),
            (admission, "model", "score", true, false, None),
            (admission, "model", "extract", true, false, not_numerical),
            (admission, "model", "generate", true, true, not_numerical),
            (
                admission,
                "other",
                "encode",
                true,
                false,
                Some("admitted_work_names_another_model"),
            ),
            (admission, "model", "encode", false, false, unadmitted),
            (admission, "model", "generate", false, false, unadmitted),
            (authority, "model", "encode", true, true, off),
            (direct, "model", "score", true, false, off),
            (pooled, "model", "encode", true, false, off),
            (pooled, "model", "encode", false, true, bridge),
            (authority, "model", "score", false, true, bridge),
            (pooled, "model", "generate", false, true, None),
            (authority, "model", "encode", false, false, None),
            (pooled, "model", "extract", false, true, None),
        ] {
            let mut work = wi("req", 0, model, op);
            work.numerical_admission_sha256 = token.then(|| "a".repeat(64));
            work.fallback_reason = fallback.then(|| "provisioning".to_string());
            work.bundle_config_hash = "fresh".into();
            assert_eq!(
                numerical_admission_violation(subject, &work),
                violation,
                "{subject} {model} {op} {token} {fallback}"
            );
        }
        let mut unpinned = wi("req", 0, "model", "encode");
        unpinned.numerical_admission_sha256 = Some("a".repeat(64));
        assert_eq!(
            numerical_admission_violation(admission, &unpinned),
            Some("admitted_work_names_no_configuration")
        );
    }

    #[tokio::test]
    async fn an_admitted_item_with_a_configuration_this_worker_no_longer_holds_is_answered() {
        let backend = naking_backend(None, None, Some(2_500));
        let mut dispatcher = dispatcher_with_backend(backend.clone());
        Arc::get_mut(&mut dispatcher).unwrap().config_apply_state =
            Some(Arc::new(ConfigApplyState::new("fresh".into())));
        let admitted = |hash: &str| WorkItem {
            numerical_admission_sha256: Some("a".repeat(64)),
            bundle_config_hash: hash.into(),
            ..wi("admitted", 0, "acme/model:remote", "encode")
        };

        let stale = settle_one(&dispatcher, admitted("stale")).await;
        let [crate::delivery::LocalDeliveryEvent::Result { slot: 0, result }] = stale.as_slice()
        else {
            panic!("a stale admitted item must settle with a result: {stale:?}");
        };
        assert_eq!(result.error_code.as_deref(), Some(INFERENCE_ERROR_CODE));
        assert_eq!(result.retry_after_s, Some(1));
        assert_eq!(backend.encoded.load(Ordering::SeqCst), 0);

        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let ordinary = WorkItem {
            bundle_config_hash: "stale".into(),
            ..wi("plain", 0, "acme/model:remote", "encode")
        };
        let kept = dispatcher
            .answer_stale_admissions(vec![
                (
                    admitted("fresh"),
                    Delivery::Local(LocalDelivery::new(0, 0, tx.clone())),
                ),
                (ordinary, Delivery::Local(LocalDelivery::new(1, 0, tx))),
            ])
            .await;
        assert_eq!(
            kept.len(),
            2,
            "a current admission and ordinary work are kept"
        );
        assert!(rx.try_recv().is_err());
    }

    #[tokio::test(start_paused = true)]
    async fn an_admission_that_goes_stale_while_its_model_loads_is_answered() {
        let backend = LoadingModelBackend::new("cold");
        let mut dispatcher = dispatcher_with_backend(backend.clone());
        let state = Arc::new(ConfigApplyState::new("fresh".into()));
        Arc::get_mut(&mut dispatcher).unwrap().config_apply_state = Some(Arc::clone(&state));
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let admitted = WorkItem {
            numerical_admission_sha256: Some("a".repeat(64)),
            bundle_config_hash: "fresh".into(),
            ..wi("admitted", 0, "cold", "encode")
        };

        dispatcher
            .dispatch_decoded(
                vec![(admitted, Delivery::Local(LocalDelivery::new(0, 0, tx)))],
                1,
                Instant::now(),
            )
            .await;
        // The second probe comes from the parked group's readiness loop.
        while backend.probes.load(Ordering::SeqCst) < 2 {
            tokio::task::yield_now().await;
        }
        state.set_bundle_hash("next".into());
        dispatcher
            .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)
            .await;

        let Ok(crate::delivery::LocalDeliveryEvent::Result { slot: 0, result }) = rx.try_recv()
        else {
            panic!("an admission that went stale must settle with a result");
        };
        assert_eq!(result.error_code.as_deref(), Some(INFERENCE_ERROR_CODE));
        assert!(backend.encoded_models().is_empty());
    }

    #[tokio::test]
    async fn admitted_work_past_its_deadline_is_dropped_whatever_the_enforcement_flag() {
        let dispatcher = dispatcher_with_backend(naking_backend(None, None, None));
        assert!(!dispatcher.work_deadline.enforce);
        let now = unix_now_s();
        let expired = |token: Option<String>| WorkItem {
            numerical_admission_sha256: token,
            timestamp: now - 180.0,
            deadline: Some(now - 60.0),
            ..wi("late", 0, "acme/model:remote", "encode")
        };
        let delivery = admission_test_delivery().await;
        assert!(
            dispatcher
                .settle_if_expired(&expired(Some("a".repeat(64))), &delivery, "before_ipc")
                .await
        );
        assert!(
            !dispatcher
                .settle_if_expired(&expired(None), &delivery, "before_ipc")
                .await,
            "ordinary work still runs without enforcement"
        );
    }

    #[tokio::test]
    async fn work_breaking_the_admission_contract_never_reaches_the_backend() {
        let admitted = Some("a".repeat(64));
        for (subject, token, fallback_reason) in [
            ("sie.work.pool.machine.bundle.cold", admitted.clone(), None),
            (
                "sie.work.pool.machine.bundle.cold.worker.execution-authority-v1",
                admitted.clone(),
                None,
            ),
            (
                "sie.work.pool.machine.bundle.cold.worker.numerical-admission-v1",
                None,
                None,
            ),
            (
                "sie.work.pool.machine.bundle.cold",
                None,
                Some("provisioning".to_string()),
            ),
        ] {
            let backend = LoadingModelBackend::new("cold");
            let dispatcher = dispatcher_with_backend(backend.clone());
            let mut work = wi("refused", 0, "cold", "encode");
            work.numerical_admission_sha256 = token;
            work.fallback_reason = fallback_reason;
            let Delivery::Nats(mut message, permit, _) = unacknowledgeable_nats_delivery().await
            else {
                unreachable!()
            };
            message.message.subject = subject.into();
            message.message.payload = rmp_serde::to_vec_named(&work).unwrap().into();
            dispatcher
                .handle_batch(vec![QueuedMessage::new(message, permit)])
                .await;
            dispatcher.join_parked_groups(Duration::from_secs(1)).await;
            assert_eq!(backend.probes.load(Ordering::SeqCst), 0, "{subject}");
            assert!(backend.encoded_models().is_empty(), "{subject}");
        }
    }

    #[tokio::test]
    async fn admitted_work_never_reaches_a_backend_without_the_admission_method() {
        let backend = LoadingModelBackend::new("cold");
        let mut dispatcher = dispatcher_with_backend(backend.clone());
        let mutable = Arc::get_mut(&mut dispatcher).unwrap();
        mutable.config_apply_state = Some(Arc::new(ConfigApplyState::new("fresh".into())));
        mutable.scheduler_registry = Some(Arc::new(ProductionSchedulerRegistry::new(
            crate::scheduler::BatchConfig::from_env_or_default(),
        )));
        mutable.shutdown = Some(Arc::new(Shutdown::new()));
        dispatcher
            .worker_pool
            .execution_authority_v1()
            .store(true, Ordering::Release);
        let mut work = wi("admitted", 0, "cold", "encode");
        work.bundle_config_hash = "fresh".into();
        work.numerical_admission_sha256 = Some("a".repeat(64));
        assert!(!dispatcher.execution_authority_is_available(&work, true));
        dispatcher
            .dispatch_decoded(
                vec![(work.clone(), admission_test_delivery().await)],
                1,
                Instant::now(),
            )
            .await;
        assert_eq!(backend.probes.load(Ordering::SeqCst), 0);
        assert!(backend.encoded_models().is_empty());

        dispatcher
            .worker_pool
            .numerical_admission_v1()
            .store(true, Ordering::Release);
        assert!(dispatcher.execution_authority_is_available(&work, true));
    }

    #[tokio::test]
    async fn admitted_verified_and_legacy_work_split_into_separate_methods() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let mut admitted = wi("admitted", 0, "model", "encode");
        admitted.numerical_admission_sha256 = Some("a".repeat(64));
        let verified = wi("verified", 0, "model", "encode");
        let legacy = wi("legacy", 0, "model", "encode");
        let entries = [
            (
                legacy,
                Delivery::Local(LocalDelivery::new(0, 0, tx.clone())),
            ),
            (admitted, admission_test_delivery().await),
            (verified, authority_test_delivery().await),
        ];
        let mut batch = crate::scheduler::FormattedBatch {
            items: Vec::new(),
            metadata: Vec::new(),
            total_cost: 0,
            flush_reason: crate::scheduler::FlushReason::CountCap,
        };
        for (work, delivery) in entries {
            let item = encode_scheduler_item(&work);
            batch.total_cost += item.cost();
            batch.items.push(item);
            batch.metadata.push(SchedulerMeta::new_with_worker_direct(
                work, delivery, 0.0, true,
            ));
        }
        assert_eq!(
            BatchContract::of(&batch.metadata),
            BatchContract::NumericalAdmission
        );

        let partitions = split_by_contract(batch);

        let requests = partitions
            .iter()
            .map(|partition| {
                partition
                    .metadata
                    .iter()
                    .map(|meta| meta.wi.request_id.as_str())
                    .collect::<Vec<_>>()
            })
            .collect::<Vec<_>>();
        assert_eq!(requests, [["admitted"], ["verified"], ["legacy"]]);
        assert_eq!(
            partitions
                .iter()
                .map(|partition| BatchContract::of(&partition.metadata))
                .collect::<Vec<_>>(),
            [
                BatchContract::NumericalAdmission,
                BatchContract::ExecutionAuthority,
                BatchContract::Legacy,
            ]
        );
        assert!(partitions
            .iter()
            .all(|partition| partition.items.len() == partition.metadata.len()));
    }

    #[tokio::test(start_paused = true)]
    async fn a_newly_loaded_model_is_rechecked_within_one_second() {
        for state in [
            ReadinessState::LoadingStarted,
            ReadinessState::LoadingInProgress,
        ] {
            let mut backend = LoadingModelBackend::new("cold");
            Arc::get_mut(&mut backend).unwrap().loading_state = state;
            let dispatcher = dispatcher_with_backend(backend.clone());
            let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
            dispatcher
                .dispatch_decoded(
                    local_group("cold-req", "cold", 0..1, &tx),
                    1,
                    Instant::now(),
                )
                .await;
            while backend.probes.load(Ordering::SeqCst) < 2 {
                tokio::task::yield_now().await;
            }
            let started = tokio::time::Instant::now();
            tokio::time::advance(Duration::from_millis(1)).await;
            backend.loaded.store(true, Ordering::SeqCst);
            dispatcher.join_parked_groups(Duration::from_secs(2)).await;

            assert_eq!(backend.encoded_models(), ["cold"]);
            assert_eq!(backend.probes.load(Ordering::SeqCst), 3);
            assert!(started.elapsed() <= MODEL_READINESS_POLL_INTERVAL);
        }
    }

    #[tokio::test(start_paused = true)]
    async fn readiness_polling_preserves_one_progress_clock_across_calls_and_sleeps() {
        async fn drive_io<T>(operation: impl Future<Output = T>) -> T {
            tokio::pin!(operation);
            let deadline = Instant::now() + Duration::from_secs(5);
            loop {
                assert!(Instant::now() < deadline, "loopback NATS I/O timed out");
                tokio::select! {
                    biased;
                    result = &mut operation => return result,
                    () = tokio::task::yield_now() => {}
                }
            }
        }

        let backend = LoadingModelBackend::new("cold");
        let dispatcher = dispatcher_with_backend(backend.clone());
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (count_tx, mut count_rx) = tokio::sync::mpsc::unbounded_channel();
        let server = tokio::spawn(async move {
            let mut progress_count = 0;
            let (stream, _) = listener.accept().await.unwrap();
            let (read, mut write) = stream.into_split();
            write.write_all(b"INFO {\"server_id\":\"test\",\"version\":\"2.10.0\",\"proto\":1,\"max_payload\":1048576}\r\n").await.unwrap();
            let mut lines = BufReader::new(read).lines();
            while let Some(line) = lines.next_line().await.unwrap() {
                if line == "PING" {
                    write.write_all(b"PONG\r\n").await.unwrap();
                } else if line.starts_with("PUB ") {
                    let payload = lines.next_line().await.unwrap();
                    if line == "PUB _INBOX.readiness-progress 4" {
                        assert_eq!(payload.as_deref(), Some("+WPI"));
                        progress_count += 1;
                    } else {
                        assert_eq!(line, "PUB _INBOX.progress-count 0");
                        assert_eq!(payload.as_deref(), Some(""));
                        count_tx.send(progress_count).unwrap();
                    }
                } else {
                    assert!(line.starts_with("CONNECT "), "unexpected command: {line}");
                }
            }
        });
        let client = drive_io(async_nats::connect(format!("nats://{address}")))
            .await
            .unwrap();
        let message = Message {
            message: async_nats::Message {
                subject: "sie.work.test".into(),
                reply: Some("_INBOX.readiness-progress".into()),
                payload: Default::default(),
                headers: None,
                status: None,
                description: None,
                length: 0,
            },
            context: async_nats::jetstream::new(client.clone()),
        };
        let items = vec![(
            wi("cold-req", 0, "cold", "encode"),
            Delivery::Nats(message, None, None),
        )];
        let started = tokio::time::Instant::now();
        let mut wait = ModelReadinessWait::new(started + Duration::from_secs(60));

        for second in 1..=25 {
            let response = dispatcher
                .ensure_model_ready_by("cold", &items, Some(&mut wait))
                .await
                .unwrap()
                .unwrap();
            assert_eq!(response.state, ReadinessState::LoadingInProgress);
            assert!(dispatcher
                .wait_during_model_loading(
                    "cold",
                    &items,
                    &mut wait,
                    tokio::time::sleep(MODEL_READINESS_POLL_INTERVAL),
                )
                .await
                .is_some());
            assert_eq!(started.elapsed(), Duration::from_secs(second));
            assert_eq!(
                wait.next_progress,
                started + Duration::from_secs((second / 10 + 1) * 10)
            );
            client
                .publish("_INBOX.progress-count", Default::default())
                .await
                .unwrap();
            assert_eq!(drive_io(count_rx.recv()).await, Some(second / 10 + 1));
        }
        assert_eq!(backend.probes.load(Ordering::SeqCst), 25);
        assert!(backend.encoded_models().is_empty());
        assert!(dispatcher
            .wait_during_model_loading(
                "cold",
                &items,
                &mut wait,
                tokio::time::sleep(Duration::from_secs(16)),
            )
            .await
            .is_some());
        assert_eq!(wait.next_progress, started + Duration::from_secs(50));
        client
            .publish("_INBOX.progress-count", Default::default())
            .await
            .unwrap();
        assert_eq!(drive_io(count_rx.recv()).await, Some(5));
        server.abort();
    }

    #[tokio::test(start_paused = true)]
    async fn parked_readiness_deadline_bounds_a_poll_sleep_for_every_local_operation() {
        for operation in ["encode", "score", "extract", LOAD_OPERATION] {
            let backend = LoadingModelBackend::new("cold");
            let dispatcher = dispatcher_with_backend(backend.clone());
            let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
            let mut items = local_group("cold-req", "cold", 0..1, &tx);
            items[0].0.operation = operation.into();
            let started = tokio::time::Instant::now();
            let budget = Duration::from_millis(125);

            dispatcher
                .handle_model_group("cold", items, Some(started + budget))
                .await
                .unwrap();

            assert_eq!(started.elapsed(), budget, "{operation}");
            assert_eq!(retried_slots(&mut rx), [0], "{operation}");
            assert_eq!(backend.probes.load(Ordering::SeqCst), 1);
            assert!(backend.encoded_models().is_empty());
        }
    }

    #[tokio::test(start_paused = true)]
    async fn expired_parked_deadline_wins_over_an_immediately_ready_model() {
        for offset in [Duration::ZERO, Duration::from_millis(1)] {
            let backend = LoadingModelBackend::new("cold");
            backend.loaded.store(true, Ordering::SeqCst);
            let dispatcher = dispatcher_with_backend(backend.clone());
            let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
            let now = tokio::time::Instant::now();

            dispatcher
                .handle_model_group(
                    "cold",
                    local_group("cold-req", "cold", 0..1, &tx),
                    Some(now - offset),
                )
                .await
                .unwrap();

            assert_eq!(retried_slots(&mut rx), [0]);
            assert_eq!(backend.probes.load(Ordering::SeqCst), 0);
            assert!(backend.encoded_models().is_empty());
        }
    }

    #[tokio::test(start_paused = true)]
    async fn parked_deadline_wins_when_a_pending_readiness_call_completes_at_expiry() {
        let backend =
            LoadingModelBackend::with_later_probe_delay("cold", Some(Duration::from_secs(1)));
        backend.probes.store(1, Ordering::SeqCst);
        backend.loaded.store(true, Ordering::SeqCst);
        let dispatcher = dispatcher_with_backend(backend.clone());
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let started = tokio::time::Instant::now();

        dispatcher
            .handle_model_group(
                "cold",
                local_group("cold-req", "cold", 0..1, &tx),
                Some(started + Duration::from_secs(1)),
            )
            .await
            .unwrap();

        assert_eq!(started.elapsed(), Duration::from_secs(1));
        assert_eq!(retried_slots(&mut rx), [0]);
        assert!(backend.encoded_models().is_empty());
    }

    #[tokio::test(start_paused = true)]
    async fn shutdown_interrupts_a_readiness_poll_sleep() {
        let backend = LoadingModelBackend::new("cold");
        let shutdown = Arc::new(Shutdown::new());
        let mut dispatcher = dispatcher_with_backend(backend.clone());
        Arc::get_mut(&mut dispatcher).unwrap().shutdown = Some(Arc::clone(&shutdown));
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        dispatcher
            .dispatch_decoded(
                local_group("cold-req", "cold", 0..1, &tx),
                1,
                Instant::now(),
            )
            .await;
        while backend.probes.load(Ordering::SeqCst) < 2 {
            tokio::task::yield_now().await;
        }
        let started = tokio::time::Instant::now();
        shutdown.fire();
        dispatcher.join_parked_groups(Duration::from_secs(1)).await;

        assert_eq!(started.elapsed(), Duration::ZERO);
        let Some(crate::delivery::LocalDeliveryEvent::Retry {
            slot: 0, delay_ms, ..
        }) = rx.try_recv().ok()
        else {
            panic!("shutdown must retry the parked item");
        };
        assert_eq!(delay_ms, NAK_DELAY_DRAINING_MS);
        assert!(backend.encoded_models().is_empty());
    }

    #[tokio::test(start_paused = true)]
    async fn cancellation_during_a_readiness_poll_prevents_another_probe() {
        for operation in ["encode", "score", "extract", LOAD_OPERATION] {
            let backend = LoadingModelBackend::new("cold");
            let dispatcher = dispatcher_with_backend(backend.clone());
            let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
            let mut items = local_group("cold-req", "cold", 0..1, &tx);
            items[0].0.operation = operation.into();
            dispatcher.dispatch_decoded(items, 1, Instant::now()).await;
            while backend.probes.load(Ordering::SeqCst) < 2 {
                tokio::task::yield_now().await;
            }
            dispatcher
                .request_cancel_state
                .cancel(String::new(), "cold-req".into());
            backend.loaded.store(true, Ordering::SeqCst);
            dispatcher.join_parked_groups(Duration::from_secs(2)).await;

            assert_eq!(backend.probes.load(Ordering::SeqCst), 2, "{operation}");
            assert!(backend.encoded_models().is_empty());
            assert!(rx.try_recv().is_err());
        }
    }

    #[tokio::test(start_paused = true)]
    async fn terminal_and_retry_later_readiness_do_not_enter_the_poll_loop() {
        for state in [ReadinessState::Failed, ReadinessState::RetryLater] {
            let mut backend = LoadingModelBackend::new("cold");
            Arc::get_mut(&mut backend).unwrap().loading_state = state.clone();
            let dispatcher = dispatcher_with_backend(backend.clone());
            let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
            let started = tokio::time::Instant::now();
            dispatcher
                .handle_model_group(
                    "cold",
                    local_group("cold-req", "cold", 0..1, &tx),
                    Some(started + Duration::from_secs(60)),
                )
                .await
                .unwrap();

            assert_eq!(started.elapsed(), Duration::ZERO);
            assert_eq!(backend.probes.load(Ordering::SeqCst), 1);
            assert!(backend.encoded_models().is_empty());
            match rx.try_recv().unwrap() {
                crate::delivery::LocalDeliveryEvent::Result { result, .. } => {
                    assert_eq!(state, ReadinessState::Failed);
                    assert_eq!(
                        result.error_code.as_deref(),
                        Some(MODEL_LOAD_FAILED_ERROR_CODE)
                    );
                }
                crate::delivery::LocalDeliveryEvent::Retry { delay_ms, .. } => {
                    assert_eq!(state, ReadinessState::RetryLater);
                    assert_eq!(delay_ms, base_nak_delay_ms());
                }
            }
        }
    }

    #[tokio::test(start_paused = true)]
    async fn a_failed_progress_ack_ends_the_parked_wait() {
        let slow_probe = Duration::from_secs(crate::nats_consumer::ACK_WAIT_SECS * 3);
        let backend = LoadingModelBackend::with_later_probe_delay("cold", Some(slow_probe));
        let dispatcher = dispatcher_with_backend(backend.clone());
        let group = vec![(
            wi("cold-req", 0, "cold", "encode"),
            unacknowledgeable_nats_delivery().await,
        )];

        dispatcher.dispatch_decoded(group, 1, Instant::now()).await;
        backend.loaded.store(true, Ordering::SeqCst);
        let started = tokio::time::Instant::now();
        dispatcher
            .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)
            .await;

        assert!(
            started.elapsed() < slow_probe,
            "the wait must end at the first failed progress ACK, not when readiness returns"
        );
        assert!(backend.encoded_models().is_empty());
    }

    #[tokio::test(start_paused = true)]
    async fn a_parked_readiness_call_slower_than_the_ack_wait_still_dispatches() {
        let slow_probe = Duration::from_secs(crate::nats_consumer::ACK_WAIT_SECS * 3);
        let backend = LoadingModelBackend::with_later_probe_delay("cold", Some(slow_probe));
        let dispatcher = dispatcher_with_backend(backend.clone());
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();

        dispatcher
            .dispatch_decoded(
                local_group("cold-req", "cold", 0..2, &tx),
                2,
                Instant::now(),
            )
            .await;
        backend.loaded.store(true, Ordering::SeqCst);
        dispatcher
            .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)
            .await;

        assert_eq!(backend.encoded_models(), vec!["cold".to_string()]);
    }

    #[tokio::test(start_paused = true)]
    async fn a_stalled_readiness_call_does_not_outlive_the_parked_wait() {
        let backend = LoadingModelBackend::with_later_probe_delay("cold", Some(STALLED_PROBE));
        let dispatcher = dispatcher_with_backend(backend.clone());
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();

        dispatcher
            .dispatch_decoded(
                local_group("cold-req", "cold", 0..2, &tx),
                2,
                Instant::now(),
            )
            .await;
        dispatcher
            .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)
            .await;

        assert_eq!(retried_slots(&mut rx), vec![0, 1]);
    }

    #[tokio::test(start_paused = true)]
    async fn shutdown_settles_a_parked_group_during_stalled_readiness() {
        let backend = LoadingModelBackend::with_later_probe_delay("cold", Some(STALLED_PROBE));
        let shutdown = Arc::new(Shutdown::new());
        let mut dispatcher = dispatcher_with_backend(backend.clone());
        Arc::get_mut(&mut dispatcher).unwrap().shutdown = Some(Arc::clone(&shutdown));
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();

        dispatcher
            .dispatch_decoded(
                local_group("cold-req", "cold", 0..2, &tx),
                2,
                Instant::now(),
            )
            .await;
        for _ in 0..20 {
            if backend.probes.load(Ordering::SeqCst) >= 2 {
                break;
            }
            tokio::task::yield_now().await;
        }
        assert!(backend.probes.load(Ordering::SeqCst) >= 2);

        let started = tokio::time::Instant::now();
        shutdown.fire();
        dispatcher.join_parked_groups(Duration::from_secs(1)).await;

        assert!(started.elapsed() < Duration::from_secs(1));
        let mut retries = Vec::new();
        while let Ok(event) = rx.try_recv() {
            match event {
                crate::delivery::LocalDeliveryEvent::Retry { slot, delay_ms, .. } => {
                    retries.push((slot, delay_ms));
                }
                other => panic!("unexpected settlement: {other:?}"),
            }
        }
        retries.sort_unstable();
        assert_eq!(
            retries,
            vec![(0, NAK_DELAY_DRAINING_MS), (1, NAK_DELAY_DRAINING_MS)]
        );
        assert!(backend.encoded_models().is_empty());
        assert_eq!(Arc::strong_count(&dispatcher), 1);
    }

    #[tokio::test(start_paused = true)]
    async fn shutdown_wins_when_parked_readiness_is_already_ready() {
        // Exercise repeated ties so randomized select ordering cannot hide dispatch
        // after shutdown. Neither signal yields before the parked task resumes.
        for _ in 0..32 {
            let backend = LoadingModelBackend::new("cold");
            let shutdown = Arc::new(Shutdown::new());
            let mut dispatcher = dispatcher_with_backend(backend.clone());
            Arc::get_mut(&mut dispatcher).unwrap().shutdown = Some(Arc::clone(&shutdown));
            let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();

            dispatcher
                .dispatch_decoded(
                    local_group("cold-req", "cold", 0..2, &tx),
                    2,
                    Instant::now(),
                )
                .await;
            assert_eq!(backend.probes.load(Ordering::SeqCst), 1);
            backend.loaded.store(true, Ordering::SeqCst);
            shutdown.fire();
            dispatcher.join_parked_groups(Duration::from_secs(1)).await;

            assert!(backend.encoded_models().is_empty());
            let mut retries = Vec::new();
            while let Ok(event) = rx.try_recv() {
                match event {
                    crate::delivery::LocalDeliveryEvent::Retry { slot, delay_ms, .. } => {
                        retries.push((slot, delay_ms));
                    }
                    other => panic!("unexpected settlement: {other:?}"),
                }
            }
            retries.sort_unstable();
            assert_eq!(
                retries,
                vec![(0, NAK_DELAY_DRAINING_MS), (1, NAK_DELAY_DRAINING_MS)]
            );
            assert_eq!(Arc::strong_count(&dispatcher), 1);
        }
    }

    #[tokio::test(start_paused = true)]
    async fn shutdown_aborts_a_parked_group_that_does_not_settle_in_time() {
        let backend = LoadingModelBackend::with_later_probe_delay("cold", Some(STALLED_PROBE));
        let dispatcher = dispatcher_with_backend(backend.clone());
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();

        dispatcher
            .dispatch_decoded(
                local_group("cold-req", "cold", 0..2, &tx),
                2,
                Instant::now(),
            )
            .await;
        dispatcher.join_parked_groups(Duration::from_secs(1)).await;

        assert_eq!(
            Arc::strong_count(&dispatcher),
            1,
            "the aborted parked task must have released the dispatcher"
        );
        assert!(retried_slots(&mut rx).is_empty());
    }

    #[tokio::test]
    async fn scheduler_takes_the_cost_budget_the_backend_reports_for_its_model() {
        for (reported, expected) in [(Some(720_000), 720_000), (None, 16_384)] {
            let backend = LoadingModelBackend::with_max_batch_tokens("cold", reported);
            let registry = Arc::new(ProductionSchedulerRegistry::new(
                crate::scheduler::BatchConfig::default(),
            ));
            let shutdown = Arc::new(Shutdown::new());
            let mut dispatcher = dispatcher_with_backend(backend.clone());
            let mutable = Arc::get_mut(&mut dispatcher).unwrap();
            mutable.scheduler_registry = Some(Arc::clone(&registry));
            mutable.shutdown = Some(Arc::clone(&shutdown));
            let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();

            dispatcher
                .dispatch_decoded(local_group("req", "warm", 0..2, &tx), 2, Instant::now())
                .await;

            let (sched, created) = registry.get_or_create("warm", None).await;
            assert!(!created, "the group created the model's scheduler");
            assert_eq!(sched.cost_budget(), expected, "reported {reported:?}");
            assert_eq!(
                sched.config().await.max_batch_cost,
                expected,
                "reported {reported:?}"
            );
            shutdown.fire();
            for handle in dispatcher.take_scheduler_drain_handles().await {
                handle.abort();
            }
        }
    }

    #[test]
    fn releasing_cancelled_scheduled_item_clears_global_and_child_pressure() {
        let runtime_state = Arc::new(RuntimeState::new());
        let worker_pool = adapter_pool_with_runtime_state(Arc::clone(&runtime_state));
        let work = wi("req-cancel", 0, "model-a", "encode");
        let item = encode_scheduler_item(&work);
        let child_index = worker_pool.record_model_pending_enqueue(&work.model_id, item.cost());
        runtime_state
            .telemetry
            .queue_enqueued("encode", &work.model_id, None);
        runtime_state.worker_queue_depth.inc();
        runtime_state
            .worker_pending_cost
            .add(clamp_u64_to_i64(item.cost()));

        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let meta = SchedulerMeta::new_with_worker_direct(
            work.clone(),
            Delivery::Local(LocalDelivery::new(0, 0, tx)),
            0.0,
            true,
        )
        .with_worker_child_index(child_index);

        release_scheduler_pressure(
            &runtime_state,
            &worker_pool,
            &work.model_id,
            std::slice::from_ref(&item),
            std::slice::from_ref(&meta),
        );

        assert_eq!(runtime_state.worker_queue_depth.get(), 0);
        assert_eq!(runtime_state.worker_pending_cost.get(), 0);
        assert_eq!(
            runtime_state
                .telemetry
                .queue_depth_for_tests("encode", &work.model_id),
            0,
            "canonical queue depth must balance on the cancellation release path"
        );
    }

    #[test]
    fn generate_terminal_error_chunk_uses_streaming_wire_shape() {
        #[derive(serde::Deserialize)]
        struct DecodedChunk {
            kind: String,
            request_id: String,
            attempt_id: String,
            seq: u32,
            text_delta: String,
            done: bool,
            finish_reason: String,
            error: DecodedError,
        }

        #[derive(serde::Deserialize)]
        struct DecodedError {
            code: String,
            message: String,
        }

        let work = wi("req-load", 0, "Qwen/Qwen3-4B-Instruct-2507", "generate");
        for (code, message) in [
            (MODEL_LOADING_ERROR_CODE, "loading"),
            (MODEL_LOAD_FAILED_ERROR_CODE, "load failed"),
        ] {
            let bytes =
                encode_generate_terminal_error_chunk(&work, code, message).expect("chunk encodes");
            let decoded: DecodedChunk = rmp_serde::from_slice(&bytes).expect("chunk decodes");

            assert_eq!(decoded.kind, "chunk");
            assert_eq!(decoded.request_id, "req-load");
            assert_eq!(decoded.attempt_id, "req-load.0:model-loading");
            assert_eq!(decoded.seq, 0);
            assert_eq!(decoded.text_delta, "");
            assert!(decoded.done);
            assert_eq!(decoded.finish_reason, "error");
            assert_eq!(decoded.error.code, code);
            assert_eq!(decoded.error.message, message);
        }
    }

    #[test]
    fn generation_chunk_is_stamped_with_stable_execution_hash() {
        let original = rmp_serde::to_vec_named(&serde_json::json!({
            "kind": "chunk",
            "request_id": "req-1",
            "attempt_id": "attempt-1",
            "seq": 1,
            "text_delta": "done",
            "done": true
        }))
        .unwrap();

        let stamped = stamp_generate_execution_hash(original, "hash-a").unwrap();
        let decoded: serde_json::Value = rmp_serde::from_slice(&stamped).unwrap();
        assert_eq!(decoded["executed_bundle_config_hash"], "hash-a");
        assert_eq!(decoded["text_delta"], "done");
    }

    fn local_chunk(request_id: &str, attempt_id: &str, seq: u32, done: bool) -> Vec<u8> {
        rmp_serde::to_vec_named(&serde_json::json!({
            "kind": "chunk",
            "request_id": request_id,
            "attempt_id": attempt_id,
            "seq": seq,
            "text_delta": "x",
            "done": done
        }))
        .unwrap()
    }

    fn local_nak(request_id: &str, attempt_id: &str, reason: &str) -> Vec<u8> {
        rmp_serde::to_vec_named(&serde_json::json!({
            "kind": "nak",
            "request_id": request_id,
            "attempt_id": attempt_id,
            "reason": reason
        }))
        .unwrap()
    }

    #[test]
    fn local_generation_chunk_validation_requires_exact_order_and_terminal() {
        let mut state = LocalGenerateState::default();
        validate_local_generate_chunk(
            &local_chunk("req-1", "attempt-1", 0, false),
            "req-1",
            &mut state,
        )
        .unwrap();
        validate_local_generate_chunk(
            &local_chunk("req-1", "attempt-1", 1, true),
            "req-1",
            &mut state,
        )
        .unwrap();
        assert!(matches!(state.phase, LocalGeneratePhase::AwaitingChunkAck));
        assert_eq!(state.next_seq, 2);

        let error = validate_local_generate_chunk(
            &local_chunk("req-1", "attempt-1", 2, false),
            "req-1",
            &mut state,
        )
        .unwrap_err();
        assert!(error.contains("after terminal"));
    }

    #[test]
    fn local_generation_semantic_nak_is_a_retry_terminal_after_ack() {
        let mut state = LocalGenerateState::default();
        let publication = validate_local_generate_publication(
            local_nak("req-1", "attempt-1", "kv_budget"),
            "req-1",
            "hash-a",
            &mut state,
        )
        .unwrap();
        assert!(matches!(publication, LocalGeneratePublication::Retry));
        assert!(matches!(
            state.phase,
            LocalGeneratePhase::AwaitingRetryAck { ref reason } if reason == "kv_budget"
        ));
        assert!(state.observe_progress().is_err());
        assert!(state.observe_transport_nak().is_err());
        state.observe_ack().unwrap();
        assert!(matches!(
            state.phase,
            LocalGeneratePhase::Retry { ref reason } if reason == "kv_budget"
        ));
        assert!(state.observe_ack().is_err());
    }

    #[test]
    fn local_generation_semantic_nak_rejects_partial_output_and_bad_identity() {
        let mut after_output = LocalGenerateState::default();
        validate_local_generate_chunk(
            &local_chunk("req-1", "attempt-1", 0, false),
            "req-1",
            &mut after_output,
        )
        .unwrap();
        let error = validate_local_generate_publication(
            local_nak("req-1", "attempt-1", "model_not_loaded"),
            "req-1",
            "",
            &mut after_output,
        )
        .unwrap_err();
        assert!(error.contains("after output"));

        let error = validate_local_generate_publication(
            local_nak("other", "attempt-1", "model_not_loaded"),
            "req-1",
            "",
            &mut LocalGenerateState::default(),
        )
        .unwrap_err();
        assert!(error.contains("request_id mismatch"));
    }

    #[test]
    fn local_generation_terminal_requires_one_ack_and_rejects_late_progress() {
        let mut state = LocalGenerateState::default();
        validate_local_generate_chunk(
            &local_chunk("req-1", "attempt-1", 0, true),
            "req-1",
            &mut state,
        )
        .unwrap();
        assert!(state.observe_progress().is_err());
        assert!(state.observe_transport_nak().is_err());
        state.observe_ack().unwrap();
        assert!(matches!(state.phase, LocalGeneratePhase::Complete));
        assert!(state.observe_ack().is_err());
        assert!(state.observe_progress().is_err());
    }

    #[test]
    fn local_generation_chunk_validation_rejects_identity_gap_and_duplicates() {
        let mut state = LocalGenerateState::default();
        assert!(validate_local_generate_chunk(
            &local_chunk("other", "attempt-1", 0, false),
            "req-1",
            &mut state,
        )
        .unwrap_err()
        .contains("request_id mismatch"));
        assert!(validate_local_generate_chunk(
            &local_chunk("req-1", "attempt-1", 1, false),
            "req-1",
            &mut state,
        )
        .unwrap_err()
        .contains("seq gap"));

        let duplicate = MsgValue::Map(vec![
            (MsgValue::from("kind"), MsgValue::from("chunk")),
            (MsgValue::from("request_id"), MsgValue::from("req-1")),
            (MsgValue::from("request_id"), MsgValue::from("req-1")),
            (MsgValue::from("attempt_id"), MsgValue::from("attempt-1")),
            (MsgValue::from("seq"), MsgValue::from(0)),
            (MsgValue::from("done"), MsgValue::from(false)),
        ]);
        let bytes = rmp_serde::to_vec_named(&duplicate).unwrap();
        assert!(
            validate_local_generate_chunk(&bytes, "req-1", &mut LocalGenerateState::default(),)
                .unwrap_err()
                .contains("duplicate")
        );
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn offloaded_generate_blob_with_base64_images_resolves_via_object_store() {
        use crate::payload_store::LocalPayloadStore;

        // Gateway offload shape: `generate` params with base64-STRING image data.
        let generate = serde_json::json!({
            "messages": [{
                "role": "user",
                "content": "what is this?",
                "images": [{"data": "aGVsbG8=", "format": "png"}], // base64 of b"hello"
            }],
            "max_new_tokens": 8,
        });
        let blob = rmp_serde::to_vec_named(&generate).unwrap();

        // Real object store (filesystem), the gateway's `{request_id}_0.bin` key.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("req-1_0.bin"), &blob).unwrap();
        let store = LocalPayloadStore::new(Some(dir.path()));

        // The exact sidecar resolution ops: fetch from the object store + decode.
        let bytes = store
            .get("req-1_0.bin")
            .await
            .expect("blob fetched from object store");
        let mut decoded =
            decode_offloaded_generate(&bytes).expect("base64-image generate blob must decode");
        assert_eq!(
            decoded["messages"][0]["images"][0]["data"],
            MsgValue::from("aGVsbG8=")
        );
        crate::prep::media::normalize_generate_media(&mut decoded)
            .expect("sidecar normalizes generation media");
        assert_eq!(
            decoded["messages"][0]["images"][0]["data"],
            MsgValue::Binary(b"hello".to_vec())
        );

        // Inline into a WorkItem and re-encode → decode (the sidecar → Python
        // worker hop): the base64 image survives the full round trip.
        let mut work = wi("req-1", 0, "Qwen/Qwen3.5-4B", "generate");
        work.item = None;
        work.generate = Some(decoded);
        let reencoded = rmp_serde::to_vec_named(&work).unwrap();
        let back: WorkItem = rmp_serde::from_slice(&reencoded).unwrap();
        let g = back.generate.expect("generate inlined onto the work item");
        assert_eq!(
            g["messages"][0]["images"][0]["data"],
            MsgValue::Binary(b"hello".to_vec())
        );
    }

    #[test]
    fn bin_generate_blob_decodes_for_rolling_prepared_media() {
        // Newer producers may send image bytes as msgpack `bin`; the
        // sidecar's wire-native generation value must preserve them.
        #[derive(serde::Serialize)]
        struct BinImage {
            #[serde(with = "serde_bytes")]
            data: Vec<u8>,
        }
        #[derive(serde::Serialize)]
        struct BinGenerate {
            images: Vec<BinImage>,
        }
        let blob = rmp_serde::to_vec_named(&BinGenerate {
            images: vec![BinImage {
                data: vec![0xFF, 0xD8, 0xFF, 0xE0],
            }],
        })
        .unwrap();
        let decoded = decode_offloaded_generate(&blob).expect("msgpack binary must decode");
        assert_eq!(
            decoded["images"][0]["data"],
            MsgValue::Binary(vec![0xFF, 0xD8, 0xFF, 0xE0])
        );
    }

    #[test]
    fn invalid_audio_uses_gateway_client_error_contract() {
        let work = wi("req", 0, "openai/whisper-large-v3-turbo", "extract");
        let outcome = synthetic_error_outcome(&work, "invalid_request", "bad audio");
        assert_eq!(outcome.error_code.as_deref(), Some("invalid_request"));
        assert_eq!(outcome.disposition, Disposition::PublishErrorAndAck);
    }

    #[test]
    fn groups_by_model_and_operation() {
        let items = vec![
            (wi("r1", 0, "A", "encode"), ()),
            (wi("r1", 1, "A", "encode"), ()),
            (wi("r2", 0, "B", "encode"), ()),
            (wi("r3", 0, "A", "score"), ()),
        ];
        let groups = group_by_model(items);
        assert_eq!(groups[&("A".to_string(), "encode".to_string())].len(), 2);
        assert_eq!(groups[&("A".to_string(), "score".to_string())].len(), 1);
        assert_eq!(groups[&("B".to_string(), "encode".to_string())].len(), 1);
        assert_eq!(groups.len(), 3);
    }

    #[test]
    fn group_by_model_only_collapses_ops() {
        // For the hot path: all ops for a single model should land together
        // so they can be dispatched concurrently within the group.
        let items = vec![
            (wi("r1", 0, "A", "encode"), ()),
            (wi("r1", 1, "A", "score"), ()),
            (wi("r2", 0, "A", "extract"), ()),
            (wi("r3", 0, "B", "encode"), ()),
        ];
        let groups = group_by_model_only(items);
        assert_eq!(groups["A"].len(), 3);
        assert_eq!(groups["B"].len(), 1);
        assert_eq!(groups.len(), 2);
    }

    #[test]
    fn opt_non_empty_maps_empty_to_none() {
        assert_eq!(opt_non_empty(""), None);
        assert_eq!(opt_non_empty("x"), Some("x".to_string()));
    }

    #[test]
    fn unknown_bundle_config_hash_accepts_only_current_and_empty_hashes() {
        let state = ConfigApplyState::new("hash-1".into());
        state.set_bundle_hash("hash-2".into());

        let mut current = wi("r1", 0, "A", "encode");
        current.bundle_config_hash = "hash-2".into();
        let legacy = wi("r1", 2, "A", "encode");

        let items = [current, legacy];
        let unknown = unknown_bundle_config_hash(items.iter(), Some(&state));
        assert!(unknown.is_none());

        let mut stale = wi("r1", 1, "A", "encode");
        stale.bundle_config_hash = "hash-1".into();
        assert_eq!(
            unknown_bundle_config_hash([&stale], Some(&state)),
            Some(("hash-1", 1))
        );
    }

    #[test]
    fn unknown_bundle_config_hash_refuses_pinned_work_without_authority() {
        let mut pinned = wi("r1", 0, "A", "encode");
        pinned.bundle_config_hash = "hash-1".into();
        let legacy = wi("r1", 1, "A", "encode");
        assert_eq!(unknown_bundle_config_hash([&legacy], None), None);
        assert_eq!(
            unknown_bundle_config_hash([&legacy, &pinned], None),
            Some(("hash-1", 1))
        );
    }

    #[tokio::test]
    async fn pinned_work_never_reaches_a_backend_without_config_authority() {
        let backend = naking_backend(None, None, None);
        let dispatcher = dispatcher_with_backend(backend.clone());
        let mut work = wi("pinned", 0, "A", "encode");
        work.bundle_config_hash = "hash-1".into();
        let events = settle_one(&dispatcher, work).await;
        assert_eq!(backend.encoded.load(Ordering::SeqCst), 0);
        assert!(matches!(
            events.as_slice(),
            [crate::delivery::LocalDeliveryEvent::Retry { .. }]
        ));

        let mut work = wi("pinned-gen", 0, "A", "generate");
        work.bundle_config_hash = "hash-1".into();
        work.generate = Some(MsgValue::Map(Vec::new()));
        let error = dispatcher
            .process_local_generate(work, |_| async { Ok(()) })
            .await
            .unwrap_err();
        assert_eq!(error.code, "BUNDLE_CONFIG_MISMATCH");
    }

    #[test]
    fn unknown_bundle_config_hash_reports_first_unknown_and_count() {
        let state = ConfigApplyState::new("hash-1".into());

        let mut first = wi("r1", 0, "A", "encode");
        first.bundle_config_hash = "missing-a".into();
        let mut accepted = wi("r1", 1, "A", "encode");
        accepted.bundle_config_hash = "hash-1".into();
        let mut second = wi("r1", 2, "A", "encode");
        second.bundle_config_hash = "missing-b".into();

        let items = [first, accepted, second];
        let unknown = unknown_bundle_config_hash(items.iter(), Some(&state));
        assert_eq!(unknown, Some(("missing-a", 2)));
    }

    #[test]
    fn barrier_naks_count_unsupported_models_as_model_unsupported() {
        let state = ConfigApplyState::new(String::new());
        assert!(state.mark_export_reconciled(1, Some("hash-1".into()), vec!["B".into()], false));

        assert_eq!(barrier_nak_reason(Some(&state), "B"), "model_unsupported");
        assert_eq!(barrier_nak_reason(Some(&state), "b"), "model_unsupported");
        // A supported model refused at the barrier carries an old bundle hash.
        assert_eq!(barrier_nak_reason(Some(&state), "A"), "retry");
        assert_eq!(barrier_nak_reason(None, "B"), "retry");
    }

    /// The architecture guide counts NAKs for a model in `unsupported_models`
    /// as `model_unsupported` at intake, before readiness and at the config
    /// execution barrier. A barrier that NAKs through the plain `retry`
    /// helpers would count a model that turned unsupported after intake as a
    /// retry. Checked structurally, like the barrier ordering above, so a
    /// future barrier that NAKs the old way fails here.
    #[test]
    fn config_execution_barriers_nak_with_their_reason() {
        let source = include_str!("dispatcher.rs");
        let production = source
            .split("\nmod tests {")
            .next()
            .expect("dispatcher.rs must have a production section");
        let barrier = concat!("lock_execution", "().await");
        let mut naking = 0;
        for (site, _) in production.match_indices(barrier) {
            let rest = &production[site..];
            let refusal = &rest[..rest
                .find("return")
                .expect("a barrier refuses before execution")];
            if !refusal.contains("nak") {
                continue; // local-ingest generate answers with an error, not a NAK
            }
            naking += 1;
            assert!(
                !refusal.contains(concat!("nak_all", "("))
                    && !refusal.contains(concat!("nak_msg", "(")),
                "the barrier at byte {site} NAKs with the plain retry reason"
            );
            assert!(
                refusal.contains("nak_all_at_barrier") || refusal.contains("barrier_nak_reason"),
                "the barrier at byte {site} does not attribute its NAK reason"
            );
        }
        // Generate, encode, score, extract and the scheduler batch.
        assert_eq!(naking, 5, "expected five NAKing config execution barriers");
    }

    #[test]
    fn unknown_bundle_config_hash_flags_models_the_worker_cannot_serve() {
        let state = ConfigApplyState::new(String::new());
        assert!(state.mark_export_reconciled(1, Some("hash-1".into()), vec!["B".into()], false));

        let mut served = wi("r1", 0, "A", "encode");
        served.bundle_config_hash = "hash-1".into();
        assert!(unknown_bundle_config_hash([&served], Some(&state)).is_none());

        let mut unsupported = wi("r1", 1, "B", "encode");
        unsupported.bundle_config_hash = "hash-1".into();
        assert_eq!(
            unknown_bundle_config_hash([&served, &unsupported], Some(&state)),
            Some(("hash-1", 1))
        );
    }

    #[test]
    fn unexpected_work_header_allows_only_the_gateway_message_id() {
        assert_eq!(unexpected_work_header(None), None);
        let mut gateway = async_nats::HeaderMap::new();
        gateway.insert("Nats-Msg-Id", "req-1");
        gateway.insert("traceparent", "00-abc-def-01");
        assert_eq!(unexpected_work_header(Some(&gateway)), None);
        for name in ["Nats-Stream", "Nats-Stream-Source", "nats-subject"] {
            let mut copied = async_nats::HeaderMap::new();
            copied.insert(name, "x");
            assert_eq!(
                unexpected_work_header(Some(&copied)).as_deref(),
                Some(name),
                "{name}"
            );
        }
    }

    #[test]
    fn reply_subject_is_safe_rules() {
        assert!(reply_subject_is_safe(""));
        assert!(reply_subject_is_safe("_INBOX.ab"));
        assert!(reply_subject_is_safe("_INBOX.a.b.c"));
        assert!(!reply_subject_is_safe("sie.work.foo.l4"));
        assert!(!reply_subject_is_safe("something.evil"));
        assert!(!reply_subject_is_safe("_INBOX")); // no trailing dot
    }

    #[test]
    fn caller_item_id_is_extracted_from_resolved_item_only_when_string() {
        let item = MsgValue::Map(vec![
            (MsgValue::from("id"), MsgValue::from("doc-42")),
            (MsgValue::from("text"), MsgValue::from("hello")),
        ]);
        assert_eq!(caller_item_id_from_value(&item).as_deref(), Some("doc-42"));

        let invalid = MsgValue::Map(vec![(MsgValue::from("id"), MsgValue::from(42))]);
        assert!(caller_item_id_from_value(&invalid).is_none());
        assert!(caller_item_id_from_value(&MsgValue::Nil).is_none());
    }

    #[test]
    fn truncate_respects_char_boundaries() {
        assert_eq!(truncate("hello", 3), "hel");
        assert_eq!(truncate("hi", 10), "hi");
        // 'é' is two bytes — truncate should not split it.
        assert_eq!(truncate("café", 3), "caf");
        assert_eq!(truncate("café", 4), "café");
    }

    /// Every point that hands work to the backend must record work-item age.
    ///
    /// This is a tripwire for a real defect, not a style rule: the first
    /// version of `sie.worker.work_item.age` recorded only at the batch result
    /// publish, so generation — which streams from its own task and never
    /// reaches `apply_outcome` — was entirely absent from the distribution.
    /// The metric exists to size how much work runs after its client gave up,
    /// and generation is the most expensive case of exactly that, so the
    /// omission biased the number toward zero precisely where it mattered.
    ///
    /// Only production code is counted — the test module below calls the
    /// recorder too — and the needle is assembled at compile time so this test
    /// does not match itself.
    #[test]
    fn every_execution_commit_point_records_work_item_age() {
        let source = include_str!("dispatcher.rs");
        let production = source
            .split("\nmod tests {")
            .next()
            .expect("dispatcher.rs must have a production section");
        let needle = concat!("record_work_item_ages", "(");
        assert_eq!(
            production.matches(needle).count(),
            6,
            "expected exactly six execution-commit call sites (encode, score, extract, \
             scheduler drain, NATS generate, local-ingest generate). If you added a path that \
             hands work to the backend, record the age there too and update this count — a \
             missing path silently biases sie.worker.work_item.age toward zero for that \
             operation."
        );
    }

    /// Every recording site must sit AFTER its bundle-config execution
    /// barrier, because a hash mismatch NAKs the batch without ever calling the
    /// backend. Recording first would count redelivered work as executed, and
    /// hash changes land during config rollouts — exactly when backlog builds
    /// and the number has to be trustworthy.
    ///
    /// Checked structurally rather than by driving each handler: the ordering
    /// is the invariant, and a positional assertion catches a future
    /// reordering that a behavioural test on one handler would miss.
    #[test]
    fn work_item_age_is_recorded_after_every_config_execution_barrier() {
        let source = include_str!("dispatcher.rs");
        let production = source
            .split("\nmod tests {")
            .next()
            .expect("dispatcher.rs must have a production section");
        let record = concat!("record_work_item_ages", "(");
        let barrier = concat!("unknown_bundle_config_hash", "(");
        let accepts = concat!("accepts_work", "(");

        // Pair each barrier with the next recording site and require that the
        // barrier comes first. Five of the six sites sit behind a barrier; the
        // sixth (local-ingest generate) uses the `accepts_` spelling.
        let mut barriers: Vec<usize> = production.match_indices(barrier).map(|(i, _)| i).collect();
        barriers.extend(production.match_indices(accepts).map(|(i, _)| i));
        barriers.sort_unstable();
        let records: Vec<usize> = production.match_indices(record).map(|(i, _)| i).collect();
        assert_eq!(records.len(), 6, "expected six recording sites");

        for &site in &records {
            let preceding_barrier = barriers.iter().rev().find(|&&b| b < site);
            assert!(
                preceding_barrier.is_some(),
                "a recording site at byte {site} has no config barrier before it — \
                 a bundle-hash NAK would be counted as executed work"
            );
            // No recording site may be the first thing after a barrier's own
            // NAK-and-return: require the barrier and the record to be in the
            // same neighbourhood rather than separated by another record.
            let intervening = records
                .iter()
                .filter(|&&r| r > *preceding_barrier.unwrap() && r < site)
                .count();
            assert_eq!(
                intervening, 0,
                "recording site at byte {site} does not pair 1:1 with its barrier"
            );
        }
    }

    /// Hostile envelope timestamps must cost a dropped observation, never a
    /// panic on the execution path. A disabled facade must not even look.
    #[test]
    fn recording_work_item_ages_tolerates_absent_and_skewed_timestamps() {
        let telemetry = crate::observability::metrics::SidecarTelemetry::default();
        assert!(!telemetry.is_enabled());
        let far_future = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs_f64()
            + 86_400.0;
        let mut absent = wi("r", 0, "m", "encode");
        absent.timestamp = 0.0;
        let mut negative = wi("r", 1, "m", "generate");
        negative.timestamp = -1.0;
        let mut skewed = wi("r", 2, "m", "encode");
        skewed.timestamp = far_future;
        let items = [absent, negative, skewed];
        record_work_item_ages(&telemetry, items.iter());
    }

    #[test]
    fn queue_ms_from_zero_timestamp_is_zero() {
        assert_eq!(queue_ms_from(0.0), 0.0);
        assert_eq!(queue_ms_from(-1.0), 0.0);
    }

    #[test]
    fn queue_ms_from_past_timestamp_is_positive() {
        let one_second_ago = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs_f64()
            - 1.0;
        let ms = queue_ms_from(one_second_ago);
        // Allow ±200ms wobble for test scheduling; we mostly want to verify
        // "not zero, not negative, in the right ballpark".
        assert!((800.0..=1200.0).contains(&ms), "expected ~1000ms, got {ms}");
    }

    #[test]
    fn split_by_budget_under_limit_passes_through() {
        let items = vec![
            (wi("r", 0, "m", "encode"), ()),
            (wi("r", 1, "m", "encode"), ()),
        ];
        let (dispatch, overflow) = split_by_budget(items, 5);
        assert_eq!(dispatch.len(), 2);
        assert!(overflow.is_empty());
    }

    #[test]
    fn split_by_budget_over_limit_splits() {
        let items: Vec<(WorkItem, ())> = (0..10).map(|i| (wi("r", i, "m", "encode"), ())).collect();
        let (dispatch, overflow) = split_by_budget(items, 3);
        assert_eq!(dispatch.len(), 3);
        assert_eq!(overflow.len(), 7);
        // Original order preserved across the split.
        assert_eq!(dispatch[0].0.item_index, 0);
        assert_eq!(dispatch[2].0.item_index, 2);
        assert_eq!(overflow[0].0.item_index, 3);
        assert_eq!(overflow[6].0.item_index, 9);
    }

    #[test]
    fn split_by_budget_zero_sends_all_to_overflow() {
        let items: Vec<(WorkItem, ())> = (0..3).map(|i| (wi("r", i, "m", "encode"), ())).collect();
        let (dispatch, overflow) = split_by_budget(items, 0);
        assert!(dispatch.is_empty());
        assert_eq!(overflow.len(), 3);
    }

    #[test]
    fn default_max_concurrent_batches_env_parsing() {
        // Avoid mutating process-global env in a parallel test.
        assert!(default_max_concurrent_batches() >= 1);
    }

    #[test]
    fn default_audio_prep_permits_is_positive() {
        // Invalid and absent operator values both fall back to one in production.
        assert!(default_audio_prep_permits() >= 1);
    }

    #[test]
    fn pipeline_depth_default_is_two() {
        // Env-free assertion only. We can't safely mutate env vars
        // in unit tests without polluting other tests running in
        // the same process.
        if std::env::var("SIE_RUST_PIPELINE_DEPTH").is_err() {
            assert_eq!(pipeline_depth(), 2);
        }
    }

    #[tokio::test]
    async fn saturated_pipeline_keeps_tail_mutable_until_a_slot_opens() {
        let scheduler = Scheduler::<PipelineTestItem, usize>::new(BatchConfig {
            max_batch_cost: 16,
            max_batch_requests: 16,
            max_batch_wait_ms: 100.0,
            coalesce_ms: 100.0,
            coalesce_ratio: 1.0,
            ..BatchConfig::default()
        });
        let pipeline_sem = Arc::new(Semaphore::new(1));
        let active_batch = pipeline_sem
            .clone()
            .acquire_owned()
            .await
            .expect("test pipeline is open");

        scheduler
            .submit(
                SchedOp::Encode,
                LoraKey::base(),
                PipelineTestItem { idx: 1 },
                1,
            )
            .await;

        // Poll the permit reservation once. With the only slot occupied, the
        // dispatcher must stop before extracting item 1 from the scheduler.
        let shutdown = Shutdown::new();
        let mut continuation = Box::pin(reserve_continuation_slot_and_snapshot(
            &scheduler,
            &pipeline_sem,
            &shutdown,
            SchedOp::Encode,
            LoraKey::base(),
        ));
        assert!(futures_util::poll!(&mut continuation).is_pending());
        assert_eq!(scheduler.total_pending_count().await, 1);

        // This arrival occurs while the pipeline is saturated. Because item 1
        // remained mutable in the BatchFormer, both items form the next batch
        // after the active dispatch releases its slot.
        scheduler
            .submit(
                SchedOp::Encode,
                LoraKey::base(),
                PipelineTestItem { idx: 2 },
                2,
            )
            .await;
        drop(active_batch);

        let (next_permit, drain_budget) = continuation
            .await
            .expect("pending reservation succeeds after a slot opens");
        let batch = scheduler
            .try_drain_same_up_to(SchedOp::Encode, LoraKey::base(), drain_budget)
            .await
            .expect("tail accumulated during saturation should drain together");
        assert_eq!(drain_budget, 2, "snapshot happens after the slot opens");
        assert_eq!(batch.metadata, vec![1, 2]);
        assert_eq!(batch.items.len(), 2);
        assert_eq!(scheduler.total_pending_count().await, 0);
        drop(next_permit);
    }

    /// Holds actual RunBatch calls until the test completes them. The real
    /// scheduler/drain/settlement paths decide which requests reach it.
    struct HeldScoreBackend {
        started: tokio::sync::mpsc::UnboundedSender<(String, tokio::sync::oneshot::Sender<()>)>,
    }

    #[async_trait::async_trait]
    impl crate::backend::InferenceBackend for HeldScoreBackend {
        fn name(&self) -> &'static str {
            "held-score"
        }

        fn supports(&self, _model_id: &str) -> bool {
            true
        }

        async fn ensure_model_ready(
            &self,
            _model_id: &str,
        ) -> Result<crate::ipc_types::EnsureModelReadyResponse, BackendError> {
            Ok(crate::ipc_types::EnsureModelReadyResponse {
                state: ReadinessState::Ready,
                batch_budget: None,
                descriptor: None,
                max_batch_tokens: None,
            })
        }

        async fn process_encode_batch(
            &self,
            _req: ProcessEncodeBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            Err(BackendError::UnsupportedModel("encode".into()))
        }

        async fn process_score_batch(
            &self,
            _req: ProcessScoreBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            Err(BackendError::UnsupportedModel("score".into()))
        }

        async fn process_extract_batch(
            &self,
            _req: ProcessExtractBatchRequest,
        ) -> Result<BatchOutcome, BackendError> {
            Err(BackendError::UnsupportedModel("extract".into()))
        }

        async fn run_batch(&self, req: RunBatchRequest) -> Result<BatchOutcome, BackendError> {
            // Every short item costs 9 against a cap of 16, so these batches
            // must be singletons even with an eight-item count limit.
            assert_eq!(req.items.len(), 1);
            let item = &req.items[0];
            assert_eq!(item.op, "score");
            let (release, held) = tokio::sync::oneshot::channel();
            self.started
                .send((item.request_id.clone(), release))
                .unwrap();
            held.await.expect("the test releases every backend call");
            let mut result = outcome(
                &item.request_id,
                item.item_index,
                Disposition::PublishAndAck,
                Some(1.0),
                None,
            );
            result.result_msgpack = rmp_serde::to_vec_named(&item.request_id).unwrap();
            Ok(BatchOutcome {
                outcomes: vec![result],
                batched_f16_multivectors: Vec::new(),
            })
        }
    }

    fn score_client_work(
        slot: usize,
        cost: usize,
        tx: &tokio::sync::mpsc::UnboundedSender<crate::delivery::LocalDeliveryEvent>,
    ) -> (WorkItem, Delivery) {
        let mut work = wi(&format!("score-{slot}"), 0, "reranker", "score");
        work.query_item = Some(text_item("q"));
        work.score_items = Some(vec![text_item(&"x".repeat(cost - 1))]);
        (
            work,
            Delivery::Local(LocalDelivery::new(slot, 0, tx.clone())),
        )
    }

    #[tokio::test]
    async fn aged_score_requests_progress_under_closed_loop_c8_replenishment() {
        // Both an in-cap large request and a single oversize request must
        // progress. Eight clients each submit their next request only after
        // the previous one settles; the seven cheap clients replenish demand.
        for large_cost in [12, 24] {
            let (started_tx, mut started_rx) = tokio::sync::mpsc::unbounded_channel();
            let dispatcher = dispatcher_with_backend(Arc::new(HeldScoreBackend {
                started: started_tx,
            }));
            // Pin the production pipeline without changing process-global env.
            dispatcher
                .pipelines
                .lock()
                .unwrap()
                .insert("reranker".into(), Arc::new(ModelPipeline::new(2)));
            let controller = crate::scheduler::AdaptiveBatchController::builder()
                .target_p50_ms(Some(100.0))
                .min_wait_ms(20.0)
                .max_wait_ms(20.0)
                .initial_wait_ms(20.0)
                .min_batch_cost(16)
                .max_batch_cost(16)
                .initial_batch_cost(16)
                .starvation_recovery_enabled(false)
                .build();
            let scheduler = Arc::new(
                ProductionScheduler::builder()
                    .config(BatchConfig {
                        max_batch_cost: 16,
                        max_batch_requests: 8,
                        max_batch_wait_ms: 20.0,
                        ..BatchConfig::default()
                    })
                    .controller(controller)
                    .build(),
            );
            let shutdown = Arc::new(Shutdown::new());
            let drain = tokio::spawn(scheduler_drain_loop(
                "reranker".into(),
                dispatcher.clone(),
                scheduler.clone(),
                shutdown.clone(),
            ));
            let streams: Vec<_> = (0..8)
                .map(|_| tokio::sync::mpsc::unbounded_channel())
                .collect();

            // Occupy the first slot before atomically queuing the large item
            // and six cheap ones. A second dispatch can overtake it while
            // unaged, then both pipeline slots remain held during aging.
            dispatcher
                .enqueue_score_into_scheduler(
                    "reranker",
                    &scheduler,
                    vec![score_client_work(0, 9, &streams[0].0)],
                )
                .await;
            let first = tokio::time::timeout(Duration::from_secs(2), started_rx.recv())
                .await
                .unwrap()
                .unwrap();
            assert_eq!(first.0, "score-0");
            dispatcher
                .enqueue_score_into_scheduler(
                    "reranker",
                    &scheduler,
                    (1..8)
                        .map(|client| {
                            let cost = if client == 1 { large_cost } else { 9 };
                            score_client_work(client, cost, &streams[client].0)
                        })
                        .collect(),
                )
                .await;
            let second = tokio::time::timeout(Duration::from_secs(2), started_rx.recv())
                .await
                .unwrap()
                .unwrap();

            let mut clients = tokio::task::JoinSet::new();
            for (client, (tx, mut rx)) in streams.into_iter().enumerate() {
                let dispatcher = dispatcher.clone();
                let scheduler = scheduler.clone();
                clients.spawn(async move {
                    let mut settled = Vec::new();
                    for round in 0..8 {
                        let expected_slot = round * 8 + client;
                        let event = tokio::time::timeout(Duration::from_secs(2), rx.recv())
                            .await
                            .expect("every submitted request must settle")
                            .unwrap();
                        let crate::delivery::LocalDeliveryEvent::Result { slot, result } = event
                        else {
                            panic!("fake backend must not cause redelivery");
                        };
                        assert_eq!(slot, expected_slot, "once-only settlement in client order");
                        assert!(result.success);
                        assert_eq!(result.request_id, format!("score-{slot}"));
                        assert_eq!(
                            rmp_serde::from_slice::<String>(&result.result_msgpack).unwrap(),
                            result.request_id,
                            "backend output stays paired with its request"
                        );
                        settled.push(slot);
                        if round < 7 {
                            dispatcher
                                .enqueue_score_into_scheduler(
                                    "reranker",
                                    &scheduler,
                                    vec![score_client_work(expected_slot + 8, 9, &tx)],
                                )
                                .await;
                        }
                    }
                    (settled, rx)
                });
            }

            // This is real wall time: BatchFormer uses std::Instant. Nothing
            // can be extracted while both actual pipeline permits are held.
            tokio::time::sleep(Duration::from_millis(30)).await;
            let mut dispatched = vec![first.0, second.0];
            first.1.send(()).unwrap();
            let third = tokio::time::timeout(Duration::from_secs(2), started_rx.recv())
                .await
                .unwrap()
                .unwrap();
            if dispatched[1] != "score-1" {
                assert_eq!(third.0, "score-1", "aged request gets the next open slot");
            }
            dispatched.push(third.0);
            second.1.send(()).unwrap();
            third.1.send(()).unwrap();
            for _ in 3..64 {
                let (request, release) =
                    tokio::time::timeout(Duration::from_secs(2), started_rx.recv())
                        .await
                        .unwrap()
                        .unwrap();
                dispatched.push(request);
                release.send(()).unwrap();
            }

            let mut settled = Vec::new();
            let mut receivers = Vec::new();
            while let Some(client) = clients.join_next().await {
                let (slots, rx) = client.unwrap();
                settled.extend(slots);
                receivers.push(rx);
            }
            settled.sort_unstable();
            assert_eq!(settled, (0..64).collect::<Vec<_>>());
            dispatched.sort();
            let mut expected: Vec<_> = (0..64).map(|slot| format!("score-{slot}")).collect();
            expected.sort();
            assert_eq!(dispatched, expected, "every request runs exactly once");
            assert_eq!(scheduler.total_pending_count().await, 0);
            shutdown.fire();
            tokio::time::timeout(Duration::from_secs(2), drain)
                .await
                .expect("owned drain loop exits after all work settles")
                .unwrap();
            assert!(started_rx.try_recv().is_err());
            for mut rx in receivers {
                assert!(rx.try_recv().is_err(), "no duplicate terminal result");
            }
            assert_eq!(dispatcher.runtime_state.inflight_batches.get(), 0);
        }
    }

    #[tokio::test]
    async fn shutdown_cancels_pipeline_wait_without_extracting_pending_tail() {
        let scheduler = Scheduler::<PipelineTestItem, usize>::new(BatchConfig::default());
        scheduler
            .submit(
                SchedOp::Encode,
                LoraKey::base(),
                PipelineTestItem { idx: 1 },
                1,
            )
            .await;
        let pipeline_sem = Arc::new(Semaphore::new(1));
        let active_batch = pipeline_sem
            .clone()
            .acquire_owned()
            .await
            .expect("test pipeline is open");
        let shutdown = Shutdown::new();
        let mut waiting = Box::pin(reserve_pipeline_slot(&pipeline_sem, &shutdown));
        assert!(futures_util::poll!(&mut waiting).is_pending());

        shutdown.fire();
        assert!(waiting.await.is_none());
        assert_eq!(
            scheduler.total_pending_count().await,
            1,
            "shutdown before permit acquisition must not freeze or drop queued work"
        );
        drop(active_batch);
    }

    #[test]
    fn scheduler_idle_bypass_enabled_default_is_true() {
        // Env-free assertion only. The function caches its first
        // result, so tests must not mutate the env var in-process.
        if std::env::var("SIE_BATCHER_IDLE_BYPASS_ENABLED").is_err() {
            assert!(
                scheduler_idle_bypass_enabled(),
                "idle bypass must default on for low-load latency parity"
            );
        }
    }

    #[test]
    fn queue_ms_from_future_timestamp_clamps_to_zero() {
        let in_the_future = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs_f64()
            + 60.0;
        assert_eq!(queue_ms_from(in_the_future), 0.0);
    }

    #[test]
    fn base_nak_delay_ms_env_free_default() {
        // Env-free default must match Python's `_NAK_DELAY_S = 5.0` (5000ms)
        // so Rust and Python adapter processes produce the same JetStream delivery
        // pressure under back-off. We don't mutate the environment here to
        // avoid cross-test flakiness; we just assert the lower bound.
        //
        // If `SIE_NAK_DELAY_S` is set in the surrounding environment the
        // value may differ, but the function must always yield a positive
        // delay.
        let v = base_nak_delay_ms();
        assert!(v >= 1, "base_nak_delay_ms must be > 0, got {v}");
    }

    #[test]
    fn nak_delay_for_draining_is_short_not_base() {
        // Draining must NOT use the generic base delay (~5s). Another
        // worker needs the redelivery now; a long NAK would starve
        // throughput while the draining pod walks through shutdown.
        let delay = nak_delay_for_backend_error(&BackendError::Draining);
        assert_eq!(delay, NAK_DELAY_DRAINING_MS);
        assert!(
            delay < base_nak_delay_ms(),
            "draining delay ({delay}ms) must be tighter than base ({}ms)",
            base_nak_delay_ms()
        );
    }

    #[test]
    fn nak_delay_for_transient_and_inference_uses_base() {
        // Everything except Draining shares the base delay so Rust and
        // Python adapter processes throttle retries identically.
        assert_eq!(
            nak_delay_for_backend_error(&BackendError::Transient("x".into())),
            base_nak_delay_ms()
        );
        assert_eq!(
            nak_delay_for_backend_error(&BackendError::Inference("y".into())),
            base_nak_delay_ms()
        );
        assert_eq!(
            nak_delay_for_backend_error(&BackendError::UnsupportedModel("z".into())),
            base_nak_delay_ms()
        );
    }

    #[test]
    fn readiness_progress_delay_only_covers_local_loading_states() {
        assert_eq!(
            readiness_progress_delay_ms(&ReadinessState::LoadingStarted, 5_000),
            Some(5_000)
        );
        assert_eq!(
            readiness_progress_delay_ms(&ReadinessState::LoadingInProgress, 5_000),
            Some(10_000)
        );
        assert_eq!(
            readiness_progress_delay_ms(&ReadinessState::Ready, 5_000),
            None
        );
        assert_eq!(
            readiness_progress_delay_ms(&ReadinessState::RetryLater, 5_000),
            None
        );
        // Terminal failure is NOT a loading state — no progress-ACK re-drive;
        // the caller dead-letters instead.
        assert_eq!(
            readiness_progress_delay_ms(&ReadinessState::Failed, 5_000),
            None
        );
    }

    #[test]
    fn readiness_progress_delay_is_clamped_below_pool_ack_wait() {
        let max_progress_delay_ms =
            crate::nats_consumer::ACK_WAIT_SECS * 1_000 / READINESS_PROGRESS_ACK_WAIT_FRACTION;
        assert_eq!(
            readiness_progress_delay_ms(&ReadinessState::LoadingStarted, 20_000),
            Some(max_progress_delay_ms)
        );
        assert_eq!(
            readiness_progress_delay_ms(&ReadinessState::LoadingInProgress, 20_000),
            Some(max_progress_delay_ms)
        );
    }

    #[test]
    fn resolve_outcome_indices_matches_by_wiid_in_arrival_order() {
        // Happy path: every outcome lines up with exactly one resolved
        // row, same order.
        let resolved = vec!["a", "b", "c"];
        let outcomes = ["a", "b", "c"];
        let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
        assert_eq!(bindings, vec![Some(0), Some(1), Some(2)]);
    }

    #[test]
    fn resolve_outcome_indices_handles_out_of_order_outcomes() {
        // The executor may reorder outcomes within a batch (adapter
        // dedup / parallelism). Binding is by wiid, not slot.
        let resolved = vec!["a", "b", "c"];
        let outcomes = ["c", "a", "b"];
        let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
        assert_eq!(bindings, vec![Some(2), Some(0), Some(1)]);
    }

    #[test]
    fn batched_f16_multivector_index_exposes_the_requested_slice() {
        let batches = vec![BatchedF16MultivectorOutput {
            values_f16: crate::ipc_types::F16Values(vec![
                f16::from_bits(0x3c00),
                f16::from_bits(0x4000),
                f16::from_bits(0x4200),
            ]),
            items: vec![crate::ipc_types::BatchedF16MultivectorItem {
                work_item_id: "wi-0".to_string(),
                byte_offset: 2,
                byte_len: 4,
                num_tokens: 1,
                token_dims: 2,
            }],
        }];

        let indexed = index_batched_f16_multivectors(&batches);
        let multivector = indexed["wi-0"].as_ref().expect("valid f16 range");

        assert_eq!(
            multivector
                .values_f16
                .iter()
                .map(|value| value.to_bits())
                .collect::<Vec<_>>(),
            vec![0x4000, 0x4200]
        );
        assert_eq!(multivector.num_tokens, 1);
        assert_eq!(multivector.token_dims, 2);
    }

    #[test]
    fn batched_f16_multivector_index_rejects_an_out_of_bounds_slice() {
        let batches = vec![BatchedF16MultivectorOutput {
            values_f16: crate::ipc_types::F16Values(vec![f16::from_bits(0x3c00)]),
            items: vec![crate::ipc_types::BatchedF16MultivectorItem {
                work_item_id: "wi-0".to_string(),
                byte_offset: 2,
                byte_len: 2,
                num_tokens: 1,
                token_dims: 1,
            }],
        }];

        let indexed = index_batched_f16_multivectors(&batches);

        assert!(indexed["wi-0"].is_err());
    }

    #[test]
    fn resolve_outcome_indices_handles_duplicate_wiids_fifo() {
        // Two messages with the same wiid (pathological redelivery or
        // upstream bug) must each bind to a *different* resolved slot
        // in arrival order, so neither is silently dropped.
        let resolved = vec!["dup", "dup", "uniq"];
        let outcomes = ["dup", "uniq", "dup"];
        let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
        assert_eq!(
            bindings,
            vec![Some(0), Some(2), Some(1)],
            "duplicate 'dup' outcomes must consume resolved slots 0 then 1"
        );
    }

    #[test]
    fn resolve_outcome_indices_extra_outcome_is_ghost() {
        // Executor emitted more outcomes than items. The surplus must
        // be flagged (`None`) so the caller can log + drop it instead
        // of silently ACKing a phantom item.
        let resolved = vec!["a"];
        let outcomes = ["a", "ghost"];
        let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
        assert_eq!(bindings, vec![Some(0), None]);
    }

    #[test]
    fn resolve_outcome_indices_missing_outcome_leaves_orphan() {
        // Executor dropped an outcome. Returned bindings cover just
        // what was supplied; the caller walks `resolved` to NAK any
        // index not present in any `Some(idx)` binding.
        let resolved = vec!["a", "b", "c"];
        let outcomes = ["a", "c"];
        let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
        assert_eq!(bindings, vec![Some(0), Some(2)]);
        // Verifying the orphan-detection contract at the call site:
        let used: std::collections::HashSet<usize> = bindings.iter().filter_map(|o| *o).collect();
        let orphans: Vec<usize> = (0..resolved.len()).filter(|i| !used.contains(i)).collect();
        assert_eq!(orphans, vec![1], "index 1 ('b') should be the sole orphan");
    }

    #[test]
    fn resolve_outcome_indices_unknown_wiid_is_ghost() {
        // Outcome for a wiid that isn't in the batch at all.
        let resolved = vec!["a"];
        let outcomes = ["unknown"];
        let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
        assert_eq!(bindings, vec![None]);
    }

    // ----- dedupe_per_batch_request_latencies -------------------------------

    fn outcome(
        request_id: &str,
        item_index: u32,
        disposition: Disposition,
        inference_ms: Option<f64>,
        post_ms: Option<f64>,
    ) -> ItemOutcome {
        ItemOutcome {
            work_item_id: format!("{request_id}.{item_index}"),
            request_id: request_id.into(),
            item_index,
            disposition,
            nak_delay_ms: None,
            result_msgpack: Vec::new(),
            error: None,
            error_code: None,
            inference_ms,
            tokenization_ms: None,
            postprocessing_ms: post_ms,
            raw_output: None,
            units: None,
            retry_after_s: None,
        }
    }

    #[test]
    fn dedupe_collapses_multiple_items_of_same_request() {
        // Three NATS work-items for `req-A` (multi-item /encode) plus
        // one solo `req-B` land in the same batch. Python's
        // `_complete_requests` records 2 latency samples (one per
        // unique `id(metadata)`); Rust must do the same so a 10-item
        // request doesn't pull `observed_p50_ms` 10× harder than ten
        // 1-item requests at matched throughput.
        let now = Instant::now();
        let t0 = now - std::time::Duration::from_millis(50);
        let oa0 = outcome(
            "req-A",
            0,
            Disposition::PublishAndAck,
            Some(20.0),
            Some(2.0),
        );
        let oa1 = outcome(
            "req-A",
            1,
            Disposition::PublishAndAck,
            Some(20.0),
            Some(2.0),
        );
        let oa2 = outcome(
            "req-A",
            2,
            Disposition::PublishAndAck,
            Some(20.0),
            Some(2.0),
        );
        let ob0 = outcome(
            "req-B",
            0,
            Disposition::PublishAndAck,
            Some(20.0),
            Some(2.0),
        );

        let latencies = dedupe_per_batch_request_latencies(
            [
                ("req-A", t0, &oa0),
                ("req-A", t0, &oa1),
                ("req-A", t0, &oa2),
                ("req-B", t0, &ob0),
            ],
            now - std::time::Duration::from_millis(20),
            now,
        );

        assert_eq!(
            latencies.len(),
            2,
            "one sample per unique request_id within this batch"
        );
        // The 50 ms wall interval already contains the reported
        // inference and postprocessing phases; they must not be added.
        for sample in &latencies {
            let s = sample.total.as_secs_f64() * 1_000.0;
            assert!(
                (45.0..=60.0).contains(&s),
                "sample {s} should reflect the ~50ms scheduler-to-reply interval"
            );
            let wait_ms = sample.dispatch_wait.as_secs_f64() * 1_000.0;
            assert!(
                (25.0..=35.0).contains(&wait_ms),
                "sample {wait_ms} should split enqueue-to-dispatch wait from total"
            );
        }
    }

    #[test]
    fn dedupe_total_does_not_double_count_backend_phases() {
        let completed_at = Instant::now();
        let submitted_at = completed_at - std::time::Duration::from_millis(50);
        let small_phases = outcome(
            "req-small",
            0,
            Disposition::PublishAndAck,
            Some(1.0),
            Some(0.5),
        );
        let large_phases = outcome(
            "req-large",
            0,
            Disposition::PublishAndAck,
            Some(40.0),
            Some(8.0),
        );

        let latencies = dedupe_per_batch_request_latencies(
            [
                ("req-small", submitted_at, &small_phases),
                ("req-large", submitted_at, &large_phases),
            ],
            completed_at - std::time::Duration::from_millis(20),
            completed_at,
        );

        assert_eq!(latencies.len(), 2);
        assert_eq!(latencies[0].total, latencies[1].total);
        assert!((45.0..=60.0).contains(&(latencies[0].total.as_secs_f64() * 1_000.0)));
    }

    #[test]
    fn dedupe_skips_non_publish_dispositions() {
        // Errors / NAK paths must not bias the controller toward fast
        // no-op replies (they often have inference_ms = 0). Mirrors
        // Python's per-item `if not metadata.future.done()` gate.
        let now = Instant::now();
        let t0 = now - std::time::Duration::from_millis(10);
        let nak = outcome("req-X", 0, Disposition::NakRetry, Some(20.0), Some(0.0));
        let err = outcome(
            "req-Y",
            0,
            Disposition::PublishErrorAndAck,
            Some(20.0),
            Some(0.0),
        );
        let ok = outcome(
            "req-Z",
            0,
            Disposition::PublishAndAck,
            Some(20.0),
            Some(0.0),
        );

        let latencies = dedupe_per_batch_request_latencies(
            [("req-X", t0, &nak), ("req-Y", t0, &err), ("req-Z", t0, &ok)],
            now,
            now,
        );

        assert_eq!(latencies.len(), 1, "only PublishAndAck contributes");
    }

    #[test]
    fn dedupe_partial_request_contributes_when_one_item_succeeds() {
        let now = Instant::now();
        let submitted_at = now - std::time::Duration::from_millis(10);
        let nak = outcome("req-A", 0, Disposition::NakRetry, None, None);
        let ok = outcome("req-A", 1, Disposition::PublishAndAck, None, None);

        let latencies = dedupe_per_batch_request_latencies(
            [("req-A", submitted_at, &nak), ("req-A", submitted_at, &ok)],
            now,
            now,
        );

        assert_eq!(latencies.len(), 1);
    }

    #[test]
    fn request_spanning_backend_batches_contributes_once_per_batch() {
        let now = Instant::now();
        let submitted_at = now - std::time::Duration::from_millis(10);
        let first = outcome("req-A", 0, Disposition::PublishAndAck, None, None);
        let second = outcome("req-A", 12, Disposition::PublishAndAck, None, None);

        let batch_one =
            dedupe_per_batch_request_latencies([("req-A", submitted_at, &first)], now, now);
        let batch_two =
            dedupe_per_batch_request_latencies([("req-A", submitted_at, &second)], now, now);

        assert_eq!(batch_one.len() + batch_two.len(), 2);
    }

    #[test]
    fn dedupe_skips_zero_or_negative_totals() {
        // IPC failure with no timing fields populated — both `inf` and
        // `post` default to 0 and `submitted_at == now` makes the wait
        // 0 too. A zero sample would pin `observed_p50_ms` at the
        // floor and starve the wait knob.
        let now = Instant::now();
        let zero = outcome("req-zero", 0, Disposition::PublishAndAck, None, None);
        let latencies = dedupe_per_batch_request_latencies([("req-zero", now, &zero)], now, now);
        assert!(latencies.is_empty(), "zero-total samples must be dropped");
    }

    #[test]
    fn dedupe_keeps_first_occurrence_submitted_at() {
        // BatchFormer sorts items by cost so the first item we see for
        // a given request_id may not be `item_index == 0`. The dedup
        // should latch onto whichever submitted_at appears first in
        // iteration order (parity with Python, which uses the
        // request-level _start_time set once at request entry).
        let now = Instant::now();
        let early = now - std::time::Duration::from_millis(100);
        let late = now - std::time::Duration::from_millis(10);
        let o_late = outcome("req-A", 5, Disposition::PublishAndAck, Some(0.0), Some(0.0));
        let o_early = outcome("req-A", 0, Disposition::PublishAndAck, Some(0.0), Some(0.0));

        // Late item appears first (BatchFormer sorted by cost).
        let latencies = dedupe_per_batch_request_latencies(
            [("req-A", late, &o_late), ("req-A", early, &o_early)],
            now,
            now,
        );

        assert_eq!(latencies.len(), 1);
        let s = latencies[0].total.as_secs_f64() * 1_000.0;
        assert!(
            (5.0..=20.0).contains(&s),
            "sample {s} should reflect the first-seen submitted_at (~10ms wait)"
        );
    }

    #[test]
    fn dedupe_empty_input_yields_empty_output() {
        let now = Instant::now();
        let latencies = dedupe_per_batch_request_latencies(std::iter::empty(), now, now);
        assert!(latencies.is_empty());
    }
}