Skip to content

armgit / sie

Public Imported from GitHub
0

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

81.9 KB
Raw Blame
//! [`Scheduler`] — the per-model scheduler glue that ties
//! [`BatchFormer`], [`AdaptiveBatchController`],
//! [`BatchEfficiencyTracker`], and [`LatencyTracker`] together.
//!
//! Ported from `sie_server/core/worker/model_worker.py::ModelWorker`
//! but **only the scheduling half** — admission, per-LoRA batch
//! formation, FCFS fairness, and the adaptive-controller step after
//! each batch. The forward pass + adapter I/O still happen
//! backend-side; this module decides *which batch* to dispatch and
//! *when*, then hands it off.
//!
//! ## Routing
//!
//! Matches Python's asymmetric policy exactly:
//!
//! * **Encode / Extract** route by `options["lora"]` → per-LoRA batcher.
//!   `None` (or the empty-string normalisation, see [`LoraKey`]) means
//!   the base model.
//! * **Score** always goes to the base batcher regardless of
//!   `options["lora"]`. Keeping score on the base queue avoids a
//!   head-of-line-blocking class of incidents that fired the last
//!   time this was unified — comment is in
//!   `model_worker.py::_submit_score`.
//!
//! ## Fairness
//!
//! A batcher's head age is the arrival time of its oldest still-pending
//! item. Each [`BatchFormer`] owns a lock-free head timestamp (nanos
//! since the scheduler's epoch; `0` means empty) that it refreshes
//! while holding the same lock as queue mutation. `pick_oldest` scans
//! every entry with one atomic load, while submit/extract cannot race
//! the head into an invisible-pending or stale-head state.
//!
//! Partial cost-sorted extracts refresh the timestamp to the oldest
//! item that actually remains. That is the fairness primitive the
//! scheduler needs: "how long has the oldest pending item in this
//! LoRA been waiting". A hot key therefore cannot retain the timestamp
//! of already-dispatched work and repeatedly jump ahead of a sibling.

use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use tokio::sync::{Mutex, Notify, RwLock};

use crate::latency::LatencyTracker;

use super::adaptive::AdaptiveBatchController;
use super::batch_config::{process_env, BatchConfig, EnvLookup};
use super::batch_former::{BatchFormer, FormattedBatch, HasCost};
use super::lane::{Lane, Verdict};
use super::trackers::BatchEfficiencyTracker;

/// Snapshot returned by [`Scheduler::record_completion`] for the
/// caller to inspect or report after a batch
/// completes. Mirrors the post-step block in Python's
/// `model_worker.py::_step_adaptive_controller` (~lines 752-765)
/// where `ADAPTIVE_BATCH_WAIT`, `ADAPTIVE_BATCH_COST`,
/// `ADAPTIVE_P50`, `ADAPTIVE_HEADROOM`, `ADAPTIVE_FILL_RATIO`,
/// `ADAPTIVE_STARVATION_STREAK`, and `ADAPTIVE_STARVATION_RESETS`
/// are pushed.
///
/// Returning the snapshot rather than exporting inside the scheduler keeps the
/// controller independently testable and lets the canonical facade choose the
/// declared observations.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RecordCompletionOutcome {
    /// New `max_batch_wait_ms` cap after the controller step.
    pub new_wait_ms: f64,
    /// New `max_batch_cost` cap after the controller step.
    pub new_batch_cost: u64,
    /// p50 of the latency tracker at step time, if enough samples
    /// have accumulated. `None` during warm-up.
    pub observed_p50_ms: Option<f64>,
    /// Controller's current target p50, either explicit or
    /// auto-calibrated. `None` until calibration completes.
    pub target_p50_ms: Option<f64>,
    /// Mean fill ratio reported by the efficiency tracker.
    pub fill_ratio: Option<f64>,
    /// Consecutive sub-`starvation_batch_size` batches as of this
    /// step. Reset to 0 when recovery fires.
    pub starvation_streak: u32,
    /// Increase in `AdaptiveBatchController::starvation_resets()`
    /// since the previous `record_completion` call. Callers
    /// `inc_by` their starvation-reset counter by this delta — the
    /// underlying counter is monotonic so a delta is the right shape.
    pub starvation_resets_delta: u32,
    /// Size of the batch whose completion drove this step. Echoed
    /// back so callers don't have to re-thread it through.
    pub batch_size: usize,
}

/// A batch the lane released, from [`Scheduler::next_dispatch`].
#[derive(Debug)]
pub struct Dispatch<I: HasCost, T> {
    pub op: Op,
    pub lora: LoraKey,
    pub batch: FormattedBatch<I, T>,
    /// Requests this batch completes: those with no item left in the queue.
    /// These are the callers that can come back when the batch returns; a
    /// request cut by a cap is still waiting for its later batches. Pass it
    /// to [`Scheduler::note_return`].
    pub completes: usize,
}

/// Operation class of a submitted item.
///
/// Kept separate from `work_types::WorkItem::op` so the scheduler
/// module has no dependency on the NATS-facing wire types. The
/// dispatcher translates at the call site.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Op {
    Encode,
    Score,
    Extract,
}

/// LoRA routing key. Normalises both `None` and `Some("")` to the
/// single canonical base key so the map doesn't fragment on empty
/// strings coming off the wire.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LoraKey(Option<String>);

impl LoraKey {
    /// The base model key — used explicitly by score submits and by
    /// encode/extract submits with no `options["lora"]`.
    #[must_use]
    pub fn base() -> Self {
        Self(None)
    }

    /// Build from a raw string; empty strings normalise to `base()`.
    ///
    /// Named `from_name` rather than `from_str` so it doesn't collide
    /// with [`std::str::FromStr`]'s convention (which expects a
    /// `Result` return + an associated error type). This cannot fail,
    /// and adding a bogus infallible error type just to satisfy the
    /// trait would be churn for no caller benefit.
    #[must_use]
    pub fn from_name(s: &str) -> Self {
        if s.is_empty() {
            Self::base()
        } else {
            Self(Some(s.to_owned()))
        }
    }

    /// Build from `Option<String>`, normalising `Some("")` to `None`.
    #[must_use]
    pub fn from_option(o: Option<String>) -> Self {
        match o {
            Some(s) if s.is_empty() => Self::base(),
            other => Self(other),
        }
    }

    /// `true` when this key refers to the base model (no LoRA).
    #[must_use]
    pub fn is_base(&self) -> bool {
        self.0.is_none()
    }

    /// Borrow the LoRA name, or `None` if this is the base key.
    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        self.0.as_deref()
    }
}

/// Map key for the scheduler's batcher registry. Named alias keeps
/// signatures readable and silences `clippy::type_complexity` on the
/// `RwLock<HashMap<...>>` field of [`Scheduler`].
type BatcherKey = (Op, LoraKey);

/// Map of live batchers keyed by `(op, lora)`. See
/// [`BatcherEntry`] for what each value holds.
type BatcherMap<I, T> = HashMap<BatcherKey, Arc<BatcherEntry<I, T>>>;

/// One entry in the scheduler's (op, lora) → batcher map. Holds the
/// [`BatchFormer`] plus a lock-free head-age atomic the FCFS scan
/// reads.
#[derive(Debug)]
struct BatcherEntry<I: HasCost, T> {
    op: Op,
    lora: LoraKey,
    former: Arc<BatchFormer<I, T>>,
}

/// The per-model scheduler.
///
/// Generic over the item type `I` (must implement [`HasCost`]) and
/// the caller-supplied per-item metadata `T`. Production wires this as
/// `Scheduler<SchedulerItem, WorkMeta>` at the dispatcher boundary;
/// tests use simple stubs.
pub struct Scheduler<I: HasCost, T> {
    batchers: RwLock<BatcherMap<I, T>>,
    controller: Mutex<AdaptiveBatchController>,
    latency: Mutex<LatencyTracker>,
    efficiency: Mutex<BatchEfficiencyTracker>,
    /// Current caps used for *newly created* batchers. Existing
    /// batchers receive updates via [`Scheduler::record_completion`]
    /// after each controller step. Kept behind an async `RwLock`
    /// because readers are rare (new-batcher creation only).
    config: RwLock<BatchConfig>,
    /// Caps the scheduler was built with, before any controller step.
    /// [`Scheduler::adopt_cost_budget`] re-bases from these so a new
    /// budget starts from the configured wait, not a stepped one.
    initial_config: BatchConfig,
    /// The batch cost budget (`max_batch_tokens`) the static cost cap and
    /// the adaptive cost range currently derive from. Written only while
    /// the controller lock is held; read lock-free on the hot path.
    cost_budget: AtomicU64,
    /// Where the `SIE_ADAPTIVE_BATCH_*` overrides are read when the
    /// controller is derived from a budget, at build time and on re-base.
    env: EnvLookup,
    /// Fired on every submit, and on every batch return reported through
    /// [`Scheduler::note_return`]. [`Scheduler::consume_next`] and
    /// [`Scheduler::next_dispatch`] use this to wake without polling.
    new_item: Notify,
    /// When the next batch leaves for the engine (see [`super::lane`]).
    /// One lane for the whole scheduler: its queues share the engine. A
    /// plain mutex, never held across an await.
    lane: std::sync::Mutex<Lane>,
    /// The coalesce window and the batch wait in microseconds, as the
    /// lane's gather limits. They mirror `config` so
    /// [`Scheduler::note_return`] can run from a drop guard without
    /// awaiting the config lock.
    gather_quiet_us: AtomicU64,
    gather_longest_us: AtomicU64,
    /// Monotonic origin shared by per-batcher FCFS head timestamps so
    /// comparisons are unaffected by wall-clock jumps.
    epoch: Instant,
}

impl<I, T> Scheduler<I, T>
where
    I: HasCost + Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    /// Construct a scheduler with the given initial caps and a
    /// default [`AdaptiveBatchController`] (auto-calibrating target,
    /// Python-parity defaults elsewhere).
    ///
    /// Most callers want [`Scheduler::builder`] to customise the
    /// controller / tracker windows.
    #[must_use]
    pub fn new(config: BatchConfig) -> Self {
        Self::builder().config(config).build()
    }

    /// Fluent builder. See [`SchedulerBuilder`].
    #[must_use]
    pub fn builder() -> SchedulerBuilder<I, T> {
        SchedulerBuilder::default()
    }

    // ---- Introspection helpers (used by `consume_next` and tests) ----

    /// Current snapshot of the batch caps. Held by value — callers
    /// always get a consistent view even if another task is in the
    /// middle of [`Scheduler::record_completion`].
    pub async fn config(&self) -> BatchConfig {
        *self.config.read().await
    }

    /// The batch cost budget (`max_batch_tokens`) the static cost cap and
    /// the adaptive cost range currently derive from.
    pub fn cost_budget(&self) -> u64 {
        self.cost_budget.load(Ordering::Acquire)
    }

    /// Re-base the cost cap and the adaptive cost range on a new model
    /// batch cost budget (`max_batch_tokens`).
    ///
    /// A no-op returning `false` when the budget is unchanged, which is
    /// every call after the first in steady state. Otherwise the adaptive
    /// controller is rebuilt from `max_batch_tokens` exactly as
    /// [`SchedulerBuilder::build`] builds one (Python's production range
    /// plus `SIE_ADAPTIVE_BATCH_*` overrides), the static cost cap becomes
    /// the rebuilt controller's starting cost (the budget, unless an
    /// override clamps it), the fill-ratio window restarts, and every live
    /// batcher gets the new caps. The rebuilt controller re-calibrates its
    /// latency target.
    ///
    /// This runs when the backend reports a different budget for a model
    /// whose scheduler already exists, for example after the engine
    /// restarted with a newer image or applied a changed model config.
    pub async fn adopt_cost_budget(&self, max_batch_tokens: u64) -> bool {
        if self.cost_budget() == max_batch_tokens {
            return false;
        }
        // Same lock order as `record_completion` (controller, then config),
        // so a concurrent controller step cannot publish caps derived from
        // the old budget after this re-base.
        let mut controller = self.controller.lock().await;
        if self.cost_budget() == max_batch_tokens {
            return false;
        }
        let budget_cfg = BatchConfig {
            max_batch_cost: max_batch_tokens,
            ..self.initial_config
        };
        *controller =
            AdaptiveBatchController::from_batch_config_and_lookup(&budget_cfg, &*self.env);
        // Batches formed before the first controller step already honour
        // the operator's `SIE_ADAPTIVE_BATCH_*_COST` range.
        let new_cfg = BatchConfig {
            max_batch_cost: controller.current_batch_cost(),
            ..budget_cfg
        };
        *self.config.write().await = new_cfg;
        self.efficiency.lock().await.reset();
        self.cost_budget.store(max_batch_tokens, Ordering::Release);
        self.propagate_config(new_cfg).await;
        true
    }

    /// Sum of pending items across every (op, lora) batcher.
    pub async fn total_pending_count(&self) -> usize {
        let map = self.batchers.read().await;
        let mut total = 0usize;
        for e in map.values() {
            total += e.former.pending_count().await;
        }
        total
    }

    /// Snapshot the pending item count for one routed `(op, lora)` batcher.
    ///
    /// The dispatcher uses this as a continuous-drain count budget. Arrivals
    /// may still participate after cost sorting, but cannot increase the
    /// number of items dispatched before the next FCFS selection.
    pub async fn pending_count_same(&self, op: Op, lora: LoraKey) -> usize {
        let key = Self::route_key(op, lora);
        let entry = self.batchers.read().await.get(&key).cloned();
        match entry {
            Some(entry) => entry.former.pending_count().await,
            None => 0,
        }
    }

    /// Sum of pending cost across every (op, lora) batcher.
    pub async fn total_pending_cost(&self) -> u64 {
        let map = self.batchers.read().await;
        let mut total = 0u64;
        for e in map.values() {
            total += e.former.pending_cost().await;
        }
        total
    }

    /// Snapshot of the adaptive controller's observable state. Useful
    /// for dashboards / readiness probes.
    pub async fn controller_snapshot(&self) -> super::adaptive::AdaptiveBatchState {
        let ctrl = self.controller.lock().await;
        let observed = self.latency.lock().await.p50();
        let fill = self.efficiency.lock().await.mean_fill_ratio();
        ctrl.snapshot(observed, fill)
    }

    // ---- Submit path ----

    /// Enqueue a single item. Routing rules: encode/extract go to
    /// `(op, lora)`; score always forces `lora = base` regardless of
    /// what the caller passed.
    pub async fn submit(&self, op: Op, lora: LoraKey, item: I, metadata: T) {
        let key = Self::route_key(op, lora);
        let entry = self.get_or_create(&key).await;
        entry.former.submit(item, metadata).await;
        self.lane().on_arrival(Instant::now(), 1);
        self.new_item.notify_one();
    }

    /// Bulk submit under a single BatchFormer-lock. Use this for
    /// multi-item requests (SDK batches of ≤ 64 are common).
    pub async fn submit_many(&self, op: Op, lora: LoraKey, items: Vec<(I, T)>) {
        if items.is_empty() {
            return;
        }
        let key = Self::route_key(op, lora);
        let entry = self.get_or_create(&key).await;
        let requests = distinct_requests(items.iter().map(|(item, _)| item));
        entry.former.submit_many(items).await;
        self.lane().on_arrival(Instant::now(), requests);
        self.new_item.notify_one();
    }

    // ---- Consume path ----

    /// Block until some batcher has pending items, FCFS-pick the one
    /// whose oldest-head is oldest, and return its flushed batch.
    ///
    /// `immediate = true` forwards directly to
    /// [`BatchFormer::get_batch`] so a single pending item flushes at
    /// once without the `max_batch_wait_ms` wait — used when the
    /// caller was idle and knows no further arrivals are likely.
    pub async fn consume_next(&self, immediate: bool) -> (Op, LoraKey, FormattedBatch<I, T>) {
        loop {
            // Arm the notification *before* scanning: a submit that
            // fires between scan and await is captured in the
            // Notified's permit slot (see `Notified::enable` docs).
            let notified = self.new_item.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();

            if let Some(entry) = self.pick_oldest().await {
                let batch = entry.former.get_batch(immediate).await;
                return (entry.op, entry.lora.clone(), batch);
            }
            notified.await;
        }
    }

    /// Block until the lane's rule says the next batch leaves, then return
    /// it. This is the consume path of an engine that runs one batch at a
    /// time; [`Self::consume_next`] and the drain calls below remain for
    /// engines that batch by themselves and for the shutdown drain.
    ///
    /// The rule is [`super::lane`]'s: at once on an idle lane, held while a
    /// batch is with the engine unless the pending work is already full,
    /// and together after the batch returns. It is applied to the queue
    /// whose head is oldest, as [`Self::consume_next`] picks it: fairness
    /// across `(op, lora)` queues stays first come, first served, so a
    /// younger queue's full batch waits behind an older queue's held one
    /// rather than taking the free slot ahead of it. The caller must hold a free
    /// pipeline slot, report every batch it got from here back through
    /// [`Self::note_return`], and not mix this with the other consume
    /// calls while such a batch is out.
    ///
    /// `idle_bypass = false` is the operator's choice to wait on an idle
    /// lane: the classic triggers (caps, batch wait, coalesce window since
    /// the last arrival) then decide there, as they always did.
    pub async fn next_dispatch(&self, idle_bypass: bool) -> Dispatch<I, T> {
        loop {
            // Arm before reading any state: an arrival or a return between
            // the read and the await leaves its permit here.
            let notified = self.new_item.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();

            let Some(entry) = self.pick_oldest().await else {
                notified.await;
                continue;
            };
            let view = entry.former.gate_view().await;
            let now = Instant::now();
            let verdict = {
                let mut lane = self.lane();
                if !idle_bypass && view.full.is_none() && lane.is_idle(now) {
                    match (view.classic, view.classic_wait) {
                        (Some(reason), _) => Verdict::Send(reason),
                        (None, Some(wait)) => now
                            .checked_add(wait)
                            .map_or(Verdict::Hold, Verdict::WaitUntil),
                        (None, None) => Verdict::Hold,
                    }
                } else {
                    lane.verdict(now, view.full)
                }
            };
            match verdict {
                Verdict::Send(reason) => {
                    // Empty only if another consumer raced us to it.
                    if let Some((batch, completes)) = entry.former.take(reason).await {
                        self.lane().on_dispatch(batch.request_count() > completes);
                        return Dispatch {
                            op: entry.op,
                            lora: entry.lora.clone(),
                            batch,
                            completes,
                        };
                    }
                }
                Verdict::WaitUntil(deadline) => {
                    tokio::select! {
                        biased;
                        () = &mut notified => {}
                        () = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)) => {}
                    }
                }
                Verdict::Hold => notified.await,
            }
        }
    }

    /// Report that a batch returned by [`Self::next_dispatch`] is back from
    /// the engine: it answered `answered` requests ([`Dispatch::completes`])
    /// and was out for `round_trip`. Wakes the consumer, which may now send
    /// what was held.
    ///
    /// Synchronous so the caller can report from a drop guard: a batch
    /// that is never reported would hold the lane for good.
    pub fn note_return(&self, answered: usize, round_trip: Duration) {
        let quiet = Duration::from_micros(self.gather_quiet_us.load(Ordering::Acquire));
        let longest = Duration::from_micros(self.gather_longest_us.load(Ordering::Acquire));
        self.lane()
            .on_return(Instant::now(), answered, round_trip, quiet, longest);
        self.new_item.notify_one();
    }

    /// Whether a returned batch is currently followed by a gather. For
    /// logs and tests.
    pub fn lane_gathers(&self) -> bool {
        self.lane().gathers()
    }

    /// Non-blocking variant of [`Self::consume_next`]. Returns `None`
    /// if no batcher has pending items *or* if the FCFS-picked batcher
    /// isn't yet ready to flush (flush triggers haven't fired).
    pub async fn try_consume_next(&self) -> Option<(Op, LoraKey, FormattedBatch<I, T>)> {
        let entry = self.pick_oldest().await?;
        let batch = entry.former.try_get_batch().await?;
        Some((entry.op, entry.lora.clone(), batch))
    }

    /// Continuous-batching tail: drain whatever's left in `(op, lora)`'s
    /// batcher immediately, bypassing flush triggers. Returns `None`
    /// when the batcher has no pending items (or doesn't exist).
    ///
    /// Matches the Python adapter process's `try_drain` call after each forward
    /// pass. Expected usage: after `consume_next` returns a batch for
    /// `(op, lora)`, snapshot [`Self::pending_count_same`] and repeatedly call
    /// [`Self::try_drain_same_up_to`] with the remaining snapshot budget.
    pub async fn try_drain_same(&self, op: Op, lora: LoraKey) -> Option<FormattedBatch<I, T>> {
        self.try_drain_same_up_to(op, lora, usize::MAX).await
    }

    /// Drain at most `max_items` from one routed `(op, lora)` batcher.
    ///
    /// This is the bounded form used by the dispatch loop so arrivals during a
    /// saturated wave cannot increase that wave's item count indefinitely.
    /// After the wave, refreshed FCFS heads arbitrate any remaining work across
    /// sibling LoRAs and operations. A zero budget is a no-op.
    pub async fn try_drain_same_up_to(
        &self,
        op: Op,
        lora: LoraKey,
        max_items: usize,
    ) -> Option<FormattedBatch<I, T>> {
        if max_items == 0 {
            return None;
        }
        let key = Self::route_key(op, lora);
        let entry = self.batchers.read().await.get(&key).cloned()?;
        let batch = entry.former.try_drain_up_to(max_items).await?;
        Some(batch)
    }

    // ---- Controller step + efficiency / latency plumbing ----

    /// Feed the auto-calibration tracker with an inference-only
    /// sample (GPU forward pass, no queue / no postprocess).
    ///
    /// Python's ModelWorker calls this with `RequestTiming.inference_ms`;
    /// once the controller is calibrated this is a cheap no-op.
    pub async fn record_inference_sample(&self, inference_ms: f64) {
        let mut ctrl = self.controller.lock().await;
        ctrl.record_inference_sample(inference_ms);
    }

    /// Record one request-ID occurrence's scheduler-local total latency
    /// (batch wait + backend roundtrip).
    ///
    /// Mirrors Python's `_check_partial_results` block at
    /// `model_worker.py:1004` which calls
    /// `_latency_tracker.record(metadata.timing.total_ms)` for every
    /// completed request inside one backend batch. The dispatcher deduplicates
    /// by request ID within that batch; a request split across backend batches
    /// contributes once in each. This avoids item-count weighting inside a
    /// batch without feeding per-batch MAX values, which would bias
    /// `observed_p50_ms` toward the underlying request tail and drive
    /// `max_batch_wait_ms` to its floor under concurrent load.
    pub async fn record_latency_sample(&self, total_ms: f64) {
        self.latency.lock().await.record(total_ms);
    }

    /// Bulk variant of [`Self::record_latency_sample`] — pushes
    /// every value in `samples` under a single mutex acquire. Use
    /// when the caller already has the per-request totals collected
    /// (e.g. the dispatcher's request-id-deduped zip over `outcomes` x
    /// `metadata`); avoids N lock acquires for typical batches of
    /// 16–32 items.
    pub async fn record_latency_samples(&self, samples: &[f64]) {
        if samples.is_empty() {
            return;
        }
        let mut t = self.latency.lock().await;
        for s in samples {
            t.record(*s);
        }
    }

    /// Record a batch's completion metrics (efficiency + controller
    /// step) and propagate the new caps to every live batcher.
    ///
    /// **Latency samples must be fed beforehand** via
    /// [`Self::record_latency_sample`] / [`Self::record_latency_samples`].
    /// This call only consumes the *current* tracker p50 — it does
    /// not record any latency itself. Splitting the surface that
    /// way keeps the per-item-vs-per-batch sample-rate question
    /// purely a caller concern.
    ///
    /// `batch_cost` = total cost of the batch that just completed
    /// (used by the efficiency tracker → fill_ratio knob). `batch_size`
    /// = item count (used by the starvation detector).
    ///
    /// Returns a [`RecordCompletionOutcome`] for the caller. Mirrors Python's
    /// `model_worker.py:752-765`.
    pub async fn record_completion(
        &self,
        batch_cost: u64,
        batch_size: usize,
    ) -> RecordCompletionOutcome {
        // The whole step runs under the controller lock, taken first, so it
        // cannot interleave with `adopt_cost_budget`: caps derived from a
        // replaced budget are never published after the re-base. Lock order
        // is controller, then config, then the batcher map; no path takes
        // the controller while holding one of the others.
        let mut ctrl = self.controller.lock().await;

        let current_cap = self.config.read().await.max_batch_cost;
        self.efficiency.lock().await.record(batch_cost, current_cap);

        // Snapshot the trackers *before* the controller step so the
        // returned outcome reflects the same observation the
        // controller acted on (Python's `_step_adaptive_controller`
        // does the same — it reads `observed_p50` once and reuses
        // the value for both the step and the metric push).
        let observed_p50 = self.latency.lock().await.p50();
        let fill = self.efficiency.lock().await.mean_fill_ratio();

        let prev_resets = ctrl.starvation_resets();
        let (new_wait, new_cost) = ctrl.step(observed_p50, fill, Some(batch_size));
        let target_p50 = ctrl.target_p50_ms();
        let starvation_streak = ctrl.starvation_streak();
        let starvation_resets_delta = ctrl.starvation_resets().saturating_sub(prev_resets);

        // Update the shared snapshot. Short critical section under
        // the write lock — we only mutate two fields.
        let new_cfg = {
            let mut cfg = self.config.write().await;
            cfg.max_batch_wait_ms = new_wait;
            cfg.max_batch_cost = new_cost;
            *cfg
        };
        self.propagate_config(new_cfg).await;
        drop(ctrl);

        RecordCompletionOutcome {
            new_wait_ms: new_wait,
            new_batch_cost: new_cost,
            observed_p50_ms: observed_p50,
            target_p50_ms: target_p50,
            fill_ratio: fill,
            starvation_streak,
            starvation_resets_delta,
            batch_size,
        }
    }

    /// Push `cfg` to every live batcher, and to the gather windows the lane
    /// waits on after a return.
    ///
    /// We snapshot the Vec of Arcs under the read lock and drop it
    /// before the async `update_config` calls so a concurrent submit
    /// that creates a new batcher doesn't deadlock. A batcher created
    /// *after* this snapshot sees `cfg` via `config.read()` in
    /// `get_or_create`, so we don't lose the update. Callers write
    /// `self.config` before calling this.
    async fn propagate_config(&self, cfg: BatchConfig) {
        self.gather_quiet_us
            .store(whole_micros(cfg.effective_coalesce_ms()), Ordering::Release);
        self.gather_longest_us
            .store(whole_micros(cfg.max_batch_wait_ms), Ordering::Release);
        let entries: Vec<Arc<BatcherEntry<I, T>>> = {
            let map = self.batchers.read().await;
            map.values().cloned().collect()
        };
        for entry in entries {
            entry.former.update_config(cfg).await;
        }
    }

    // ---- Internal helpers ----

    fn lane(&self) -> std::sync::MutexGuard<'_, Lane> {
        // The lane holds counters only, so a panic elsewhere cannot leave
        // it half-updated.
        self.lane
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    fn route_key(op: Op, lora: LoraKey) -> BatcherKey {
        match op {
            // Score always lives on the base queue, regardless of
            // what the caller asked for. Matches Python's
            // `_submit_score` behaviour; see the module-level
            // doc-comment for why this is load-bearing.
            Op::Score => (Op::Score, LoraKey::base()),
            _ => (op, lora),
        }
    }

    async fn get_or_create(&self, key: &BatcherKey) -> Arc<BatcherEntry<I, T>> {
        // Fast path: read lock, return existing.
        if let Some(e) = self.batchers.read().await.get(key) {
            return Arc::clone(e);
        }
        // Slow path: take the write lock and double-check — another
        // task may have inserted concurrently.
        let mut map = self.batchers.write().await;
        if let Some(e) = map.get(key) {
            return Arc::clone(e);
        }
        let cfg = *self.config.read().await;
        let entry = Arc::new(BatcherEntry {
            op: key.0,
            lora: key.1.clone(),
            former: Arc::new(BatchFormer::with_epoch(cfg, self.epoch)),
        });
        map.insert(key.clone(), Arc::clone(&entry));
        entry
    }

    async fn pick_oldest(&self) -> Option<Arc<BatcherEntry<I, T>>> {
        let map = self.batchers.read().await;
        let mut best: Option<(u64, Arc<BatcherEntry<I, T>>)> = None;
        for entry in map.values() {
            let head = entry.former.fcfs_head_ns();
            if head == 0 {
                continue;
            }
            match &best {
                None => best = Some((head, Arc::clone(entry))),
                Some((ts, _)) if head < *ts => {
                    best = Some((head, Arc::clone(entry)));
                }
                _ => {}
            }
        }
        best.map(|(_, e)| e)
    }
}

// `Scheduler` intentionally doesn't derive `Clone`; the expected
// pattern is `Arc<Scheduler<...>>`. Making it clonable would hide
// the aliasing and let a test accidentally fork the adaptive
// controller state.
impl<I: HasCost, T> std::fmt::Debug for Scheduler<I, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Scheduler")
            .field("epoch", &self.epoch)
            .finish_non_exhaustive()
    }
}

// ---- Builder ----

/// Builder for [`Scheduler`]. Separated from the plain `new` path so
/// operators can tune the controller / tracker windows per model
/// without the `new` signature growing indefinitely.
pub struct SchedulerBuilder<I: HasCost, T> {
    config: BatchConfig,
    controller: Option<AdaptiveBatchController>,
    env: Option<EnvLookup>,
    latency_window: usize,
    latency_min_samples: usize,
    efficiency_window: usize,
    _phantom: std::marker::PhantomData<(I, T)>,
}

impl<I: HasCost, T> Default for SchedulerBuilder<I, T> {
    fn default() -> Self {
        Self {
            config: BatchConfig::default(),
            controller: None,
            env: None,
            // Python's `LatencyTracker(window_size=200, min_samples=10)`.
            latency_window: 200,
            latency_min_samples: 10,
            efficiency_window: 50,
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<I, T> SchedulerBuilder<I, T>
where
    I: HasCost + Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    /// Override the initial batch caps.
    #[must_use]
    pub fn config(mut self, config: BatchConfig) -> Self {
        self.config = config;
        self
    }

    /// Supply a pre-configured adaptive controller. If omitted the
    /// scheduler uses [`AdaptiveBatchController::default`].
    #[must_use]
    pub fn controller(mut self, ctrl: AdaptiveBatchController) -> Self {
        self.controller = Some(ctrl);
        self
    }

    /// Read the `SIE_ADAPTIVE_BATCH_*` overrides through `env` instead of
    /// the process environment. They apply when the builder derives the
    /// controller (no [`Self::controller`] supplied) and when the scheduler
    /// re-bases on a new budget.
    #[must_use]
    pub fn env_lookup(mut self, env: EnvLookup) -> Self {
        self.env = Some(env);
        self
    }

    /// Override the latency tracker window. Default 200 samples,
    /// 10-sample warm-up.
    #[must_use]
    pub fn latency_window(mut self, window: usize, min_samples: usize) -> Self {
        self.latency_window = window;
        self.latency_min_samples = min_samples;
        self
    }

    /// Override the efficiency tracker window. Default 50.
    #[must_use]
    pub fn efficiency_window(mut self, window: usize) -> Self {
        self.efficiency_window = window;
        self
    }

    #[must_use]
    pub fn build(self) -> Scheduler<I, T> {
        // Default controller mirrors Python's
        // `ModelWorker.__init__` *production* wiring against the
        // current `BatchConfig` (model `max_batch_tokens` =
        // `cfg.max_batch_cost`, which the registry sets to the model's
        // own budget; initial wait = `cfg.max_batch_wait_ms`,
        // cost floor / ceiling = `max_batch_tokens // 4` ..
        // `max_batch_tokens * 4`, `cost_gain = gain * 0.5`,
        // `min_wait_ms = 15.0`). The bare `default()` / module-level
        // dataclass values are test-only floors — `SchedulerBuilder`
        // is the production entry point and matches what the Python
        // worker has been deploying.
        //
        // `SIE_ADAPTIVE_BATCH_*` env vars override on top, so
        // operators can pin individual knobs without a recompile, and
        // the static cost cap starts at the derived controller's starting
        // cost, so batches formed before the first controller step honour
        // an overridden range too. Without overrides that is the configured
        // cost cap itself.
        // Tests using `.controller(...)` continue to bypass both env
        // and BatchConfig derivation entirely (deterministic).
        let env = self.env.unwrap_or_else(process_env);
        let mut config = self.config;
        let controller = match self.controller {
            Some(controller) => controller,
            None => {
                let derived =
                    AdaptiveBatchController::from_batch_config_and_lookup(&self.config, &*env);
                config.max_batch_cost = derived.current_batch_cost();
                derived
            }
        };
        Scheduler {
            batchers: RwLock::new(HashMap::new()),
            controller: Mutex::new(controller),
            latency: Mutex::new(LatencyTracker::new(
                self.latency_window,
                self.latency_min_samples,
            )),
            efficiency: Mutex::new(BatchEfficiencyTracker::new(self.efficiency_window)),
            config: RwLock::new(config),
            initial_config: self.config,
            cost_budget: AtomicU64::new(self.config.max_batch_cost),
            env,
            new_item: Notify::new(),
            lane: std::sync::Mutex::new(Lane::default()),
            gather_quiet_us: AtomicU64::new(whole_micros(self.config.effective_coalesce_ms())),
            gather_longest_us: AtomicU64::new(whole_micros(self.config.max_batch_wait_ms)),
            epoch: Instant::now(),
        }
    }
}

/// A window in milliseconds as whole microseconds; zero for a window that
/// is not a positive number.
fn whole_micros(window_ms: f64) -> u64 {
    let micros = window_ms * 1000.0;
    if micros.is_finite() && micros > 0.0 {
        // The cast saturates: a window past u64 micros is "no limit".
        micros as u64
    } else {
        0
    }
}

/// Number of requests a set of items came from: items that share a
/// [`HasCost::request_key`] count once, an item without one counts for
/// itself.
pub(crate) fn distinct_requests<'a, I: HasCost + 'a>(items: impl Iterator<Item = &'a I>) -> usize {
    let mut keyed: HashSet<&str> = HashSet::new();
    let mut unkeyed = 0usize;
    for item in items {
        match item.request_key() {
            Some(key) => {
                keyed.insert(key);
            }
            None => unkeyed += 1,
        }
    }
    keyed.len() + unkeyed
}

#[cfg(test)]
mod tests {
    use super::super::batch_former::FlushReason;
    use super::*;
    use tokio::time::{sleep as tsleep, timeout, Duration as TDuration};

    // ---- Stub item type ----

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    struct StubItem {
        cost: u64,
        idx: usize,
    }
    impl HasCost for StubItem {
        fn cost(&self) -> u64 {
            self.cost
        }
        fn original_index(&self) -> usize {
            self.idx
        }
    }

    fn make() -> Scheduler<StubItem, u32> {
        Scheduler::builder()
            .config(BatchConfig {
                max_batch_cost: 1_000_000,
                max_batch_requests: 1000,
                max_batch_wait_ms: 10_000.0,
                coalesce_ms: 10_000.0,
                coalesce_ratio: 1.0,
                ..BatchConfig::default()
            })
            .build()
    }

    // ---- Routing ----

    #[tokio::test]
    async fn encode_routes_per_lora() {
        let s = make();
        s.submit(
            Op::Encode,
            LoraKey::from_name("a"),
            StubItem { cost: 1, idx: 0 },
            0,
        )
        .await;
        s.submit(
            Op::Encode,
            LoraKey::from_name("b"),
            StubItem { cost: 2, idx: 0 },
            1,
        )
        .await;
        assert_eq!(s.total_pending_count().await, 2);
        let map = s.batchers.read().await;
        assert!(map.contains_key(&(Op::Encode, LoraKey::from_name("a"))));
        assert!(map.contains_key(&(Op::Encode, LoraKey::from_name("b"))));
    }

    #[tokio::test]
    async fn extract_routes_per_lora() {
        let s = make();
        s.submit(
            Op::Extract,
            LoraKey::from_name("a"),
            StubItem { cost: 1, idx: 0 },
            0,
        )
        .await;
        let map = s.batchers.read().await;
        assert!(map.contains_key(&(Op::Extract, LoraKey::from_name("a"))));
    }

    #[tokio::test]
    async fn score_always_routes_to_base_even_with_lora_arg() {
        let s = make();
        s.submit(
            Op::Score,
            LoraKey::from_name("should-be-ignored"),
            StubItem { cost: 1, idx: 0 },
            0,
        )
        .await;
        let map = s.batchers.read().await;
        // Must not have created a LoRA-keyed score batcher.
        assert!(
            !map.contains_key(&(Op::Score, LoraKey::from_name("should-be-ignored"))),
            "score submit with lora arg must not fragment the score queue"
        );
        assert!(map.contains_key(&(Op::Score, LoraKey::base())));
    }

    #[tokio::test]
    async fn empty_string_lora_normalises_to_base() {
        // Empty string and `base()` are indistinguishable as keys —
        // which is the whole point of the normalisation. We verify
        // that both submits hit the *same* batcher (map size stays 1)
        // and that the surviving key is `base()`.
        let s = make();
        s.submit(
            Op::Encode,
            LoraKey::from_name(""),
            StubItem { cost: 1, idx: 0 },
            0,
        )
        .await;
        s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 1, idx: 1 }, 1)
            .await;
        let map = s.batchers.read().await;
        assert_eq!(map.len(), 1, "empty-string lora must not fragment the map");
        assert!(map.contains_key(&(Op::Encode, LoraKey::base())));
        // `LoraKey::from_name("") == LoraKey::base()` by construction —
        // pin that invariant here so a future refactor can't silently
        // break the fragment-prevention.
        assert_eq!(LoraKey::from_name(""), LoraKey::base());
    }

    #[tokio::test]
    async fn submit_many_funnels_into_one_batcher() {
        let s = make();
        let items: Vec<(StubItem, u32)> = (0..5)
            .map(|i| (StubItem { cost: 1, idx: i }, i as u32))
            .collect();
        s.submit_many(Op::Encode, LoraKey::base(), items).await;
        assert_eq!(s.total_pending_count().await, 5);
    }

    // ---- FCFS fairness ----

    #[tokio::test]
    async fn fcfs_picks_oldest_head_across_loras() {
        let s = make();
        // LoRA A arrives first.
        s.submit(
            Op::Encode,
            LoraKey::from_name("a"),
            StubItem { cost: 1, idx: 0 },
            1,
        )
        .await;
        // Tiny real delay so the head_ns values are distinguishable.
        tsleep(TDuration::from_millis(2)).await;
        s.submit(
            Op::Encode,
            LoraKey::from_name("b"),
            StubItem { cost: 1, idx: 0 },
            2,
        )
        .await;

        let (op, lora, batch) = s.consume_next(true).await;
        assert_eq!(op, Op::Encode);
        assert_eq!(lora, LoraKey::from_name("a"));
        assert_eq!(batch.size(), 1);
        assert_eq!(batch.metadata[0], 1);
    }

    #[tokio::test]
    async fn fcfs_ignores_empty_batchers() {
        let s = make();
        // Populate LoRA A first, drain it.
        s.submit(
            Op::Encode,
            LoraKey::from_name("a"),
            StubItem { cost: 1, idx: 0 },
            1,
        )
        .await;
        let (_, _, _) = s.consume_next(true).await;
        assert_eq!(s.total_pending_count().await, 0);

        // Now submit to LoRA B; FCFS must pick B (A is empty).
        s.submit(
            Op::Encode,
            LoraKey::from_name("b"),
            StubItem { cost: 1, idx: 0 },
            2,
        )
        .await;
        let (_, lora, _) = s.consume_next(true).await;
        assert_eq!(lora, LoraKey::from_name("b"));
    }

    #[tokio::test]
    async fn fcfs_head_clears_only_when_batcher_drains_to_empty() {
        let s = Scheduler::<StubItem, u32>::builder()
            .config(BatchConfig {
                max_batch_cost: 5, // small cap so extract leaves remainder
                max_batch_requests: 1000,
                max_batch_wait_ms: 10_000.0,
                coalesce_ms: 10_000.0,
                coalesce_ratio: 1.0,
                ..BatchConfig::default()
            })
            .build();
        // Two items, cost 3 each. First extract takes one (3 ≤ 5),
        // stops because 3+3 > 5.
        s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 3, idx: 0 }, 1)
            .await;
        s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 3, idx: 0 }, 2)
            .await;

        let (_, _, batch) = s.consume_next(false).await;
        assert_eq!(batch.size(), 1);
        assert_eq!(s.total_pending_count().await, 1, "one item must remain");

        // The entry's FCFS head must still be non-zero so FCFS keeps
        // honouring it on the next scan.
        let entry = {
            let map = s.batchers.read().await;
            Arc::clone(map.get(&(Op::Encode, LoraKey::base())).unwrap())
        };
        let head = entry.former.fcfs_head_ns();
        assert_ne!(
            head, 0,
            "head_ns must stay non-zero while pending items remain"
        );

        // Drain the rest; head should clear.
        let (_, _, _) = s.consume_next(true).await;
        assert_eq!(s.total_pending_count().await, 0);
        let head = entry.former.fcfs_head_ns();
        assert_eq!(head, 0, "head_ns must clear when queue empties");
    }

    #[tokio::test]
    async fn consume_next_blocks_when_empty_and_wakes_on_submit() {
        let s = Arc::new(make());
        let consumer = {
            let s = Arc::clone(&s);
            tokio::spawn(async move { s.consume_next(true).await })
        };

        // Let the consumer register.
        tsleep(TDuration::from_millis(5)).await;

        s.submit(
            Op::Encode,
            LoraKey::base(),
            StubItem { cost: 1, idx: 0 },
            42,
        )
        .await;

        let (op, lora, batch) = timeout(TDuration::from_secs(2), consumer)
            .await
            .expect("consumer must wake within 2 s")
            .unwrap();
        assert_eq!(op, Op::Encode);
        assert!(lora.is_base());
        assert_eq!(batch.metadata[0], 42);
    }

    #[tokio::test]
    async fn try_consume_next_returns_none_when_empty() {
        let s = make();
        assert!(s.try_consume_next().await.is_none());
    }

    #[tokio::test]
    async fn try_drain_same_returns_continuous_batching_tail() {
        let s = make();
        // Two separate submits so we can drain one now and the other
        // via try_drain_same.
        s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 1, idx: 0 }, 1)
            .await;
        let (_, _, _) = s.consume_next(true).await;

        s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 2, idx: 0 }, 2)
            .await;
        let drain = s
            .try_drain_same(Op::Encode, LoraKey::base())
            .await
            .expect("must drain pending tail");
        assert_eq!(drain.size(), 1);
        assert_eq!(drain.metadata[0], 2);
    }

    #[tokio::test]
    async fn bounded_same_key_drain_returns_to_fcfs_for_later_arrivals() {
        let s = Scheduler::<StubItem, u32>::builder()
            .config(BatchConfig {
                max_batch_cost: 1_000_000,
                max_batch_requests: 2,
                max_batch_wait_ms: 10_000.0,
                coalesce_ms: 10_000.0,
                coalesce_ratio: 1.0,
                ..BatchConfig::default()
            })
            .build();
        let base = LoraKey::base();
        let sibling = LoraKey::from_name("sibling");

        // Start a base-model wave and remove its primary item.
        s.submit(Op::Encode, base.clone(), StubItem { cost: 1, idx: 0 }, 1)
            .await;
        let _ = s.consume_next(true).await;

        // Base backlog accumulates first while its primary forward is active.
        s.submit_many(
            Op::Encode,
            base.clone(),
            vec![
                (StubItem { cost: 1, idx: 1 }, 2),
                (StubItem { cost: 1, idx: 2 }, 3),
                (StubItem { cost: 1, idx: 3 }, 4),
            ],
        )
        .await;
        let drain_budget = s.pending_count_same(Op::Encode, base.clone()).await;
        assert_eq!(drain_budget, 3);

        // A sibling arrives after that backlog but before a newer base item.
        // Once the bounded base drain removes its older cohort, the refreshed
        // base head must not retain that cohort's timestamp and jump ahead of
        // the sibling again.
        tsleep(TDuration::from_millis(1)).await;
        s.submit(
            Op::Encode,
            sibling.clone(),
            StubItem { cost: 1, idx: 99 },
            99,
        )
        .await;
        tsleep(TDuration::from_millis(1)).await;
        s.submit(Op::Encode, base.clone(), StubItem { cost: 1, idx: 4 }, 5)
            .await;
        let mut remaining = drain_budget;
        let mut drained_batches = Vec::new();
        while remaining > 0 {
            let drained = s
                .try_drain_same_up_to(Op::Encode, base.clone(), remaining)
                .await
                .expect("snapshot backlog should drain");
            remaining -= drained.size();
            drained_batches.push(drained.metadata);
        }
        assert_eq!(drained_batches, vec![vec![2, 3], vec![4]]);
        assert_eq!(s.total_pending_count().await, 2);

        let (_, selected_lora, selected) = s.consume_next(true).await;
        assert_eq!(selected_lora, sibling);
        assert_eq!(selected.metadata, vec![99]);
        assert_eq!(s.total_pending_count().await, 1);
    }

    // ---- The lane: when the next batch leaves ----

    /// Caps and windows that never fire by themselves, so only the lane's
    /// rule can release a batch.
    fn lane_scheduler(max_batch_requests: usize) -> Arc<Scheduler<StubItem, u32>> {
        Arc::new(
            Scheduler::builder()
                .config(BatchConfig {
                    max_batch_cost: 1_000_000,
                    max_batch_requests,
                    max_batch_wait_ms: 10_000.0,
                    coalesce_ms: 40.0,
                    coalesce_ratio: 1.0,
                    ..BatchConfig::default()
                })
                .build(),
        )
    }

    async fn submit_one(s: &Scheduler<StubItem, u32>, id: u32) {
        s.submit(
            Op::Extract,
            LoraKey::base(),
            StubItem {
                cost: 1,
                idx: id as usize,
            },
            id,
        )
        .await;
    }

    async fn dispatch_within(
        s: &Arc<Scheduler<StubItem, u32>>,
        ms: u64,
    ) -> Option<FormattedBatch<StubItem, u32>> {
        timeout(TDuration::from_millis(ms), s.next_dispatch(true))
            .await
            .ok()
            .map(|dispatch| dispatch.batch)
    }

    #[tokio::test]
    async fn a_lone_request_on_an_idle_lane_leaves_at_once() {
        let s = lane_scheduler(64);
        submit_one(&s, 1).await;
        let batch = dispatch_within(&s, 200)
            .await
            .expect("no window on an idle lane");
        assert_eq!(batch.metadata, vec![1]);
        assert_eq!(batch.flush_reason, FlushReason::IdleBypass);
    }

    #[tokio::test]
    async fn a_request_of_several_items_on_an_idle_lane_leaves_at_once_and_whole() {
        let s = lane_scheduler(64);
        // One multi-item batch, returned, and a quiet lane afterwards: the
        // earlier loop remembered "not idle" from the batch size and made
        // the next request wait the coalesce window.
        for round in 0..3u32 {
            let items: Vec<(StubItem, u32)> = (0..8)
                .map(|i| (StubItem { cost: 1, idx: i }, round * 8 + i as u32))
                .collect();
            s.submit_many(Op::Extract, LoraKey::base(), items).await;
            let batch = dispatch_within(&s, 200)
                .await
                .expect("a request of several items is not held on an idle lane");
            assert_eq!(batch.size(), 8);
            s.note_return(1, Duration::from_millis(1));
            // Longer than any gather window of that round trip.
            tsleep(TDuration::from_millis(10)).await;
        }
    }

    #[tokio::test]
    async fn arrivals_during_a_forward_are_held_and_leave_together_with_the_returning_caller() {
        let s = lane_scheduler(64);
        submit_one(&s, 0).await;
        let first = dispatch_within(&s, 200).await.unwrap();
        assert_eq!(first.metadata, vec![0]);

        // Seven more arrive while the first is with the engine.
        for id in 1..8 {
            submit_one(&s, id).await;
        }
        assert!(
            dispatch_within(&s, 60).await.is_none(),
            "nothing is sent behind a batch that is still out, however long it takes",
        );

        // The first returns. Its caller is back within the gather window:
        // all eight leave as one batch, without waiting the window out.
        s.note_return(1, Duration::from_millis(60));
        let consumer = {
            let s = Arc::clone(&s);
            tokio::spawn(async move { s.next_dispatch(true).await })
        };
        tsleep(TDuration::from_millis(3)).await;
        assert!(
            !consumer.is_finished(),
            "gathering for the caller just answered"
        );
        let sent = Instant::now();
        submit_one(&s, 8).await;
        let batch = timeout(TDuration::from_millis(200), consumer)
            .await
            .expect("the returning caller ends the gather")
            .unwrap()
            .batch;
        assert!(sent.elapsed() < Duration::from_millis(20));
        let mut ids = batch.metadata.clone();
        ids.sort_unstable();
        assert_eq!(ids, (1..=8).collect::<Vec<u32>>());
        assert_eq!(batch.flush_reason, FlushReason::Coalesce);
    }

    #[tokio::test]
    async fn the_gather_ends_at_the_window_when_the_caller_does_not_return() {
        let s = lane_scheduler(64);
        submit_one(&s, 0).await;
        let _ = dispatch_within(&s, 200).await.unwrap();
        for id in 1..4 {
            submit_one(&s, id).await;
        }
        // Round trip 20 ms: the gather is half of it, under the 40 ms
        // coalesce window.
        let returned = Instant::now();
        s.note_return(1, Duration::from_millis(20));
        let batch = dispatch_within(&s, 200)
            .await
            .expect("the window ends the gather");
        let waited = returned.elapsed();
        assert!(
            waited >= Duration::from_millis(9) && waited < Duration::from_millis(40),
            "waited {waited:?}, expected about 10 ms",
        );
        assert_eq!(batch.size(), 3);
        assert_eq!(batch.flush_reason, FlushReason::Coalesce);
    }

    #[tokio::test]
    async fn callers_that_do_not_come_back_stop_being_waited_for() {
        let s = lane_scheduler(64);
        let mut next_id = 0u32;
        // Requests at random times: one is answered, another arrived during
        // its forward, nobody returns inside the window.
        for _ in 0..3 {
            submit_one(&s, next_id).await;
            next_id += 1;
            let _ = dispatch_within(&s, 200).await.unwrap();
            submit_one(&s, next_id).await;
            next_id += 1;
            s.note_return(1, Duration::from_millis(4));
            let _ = dispatch_within(&s, 200).await.unwrap();
            s.note_return(1, Duration::from_millis(4));
            tsleep(TDuration::from_millis(6)).await;
        }
        assert!(!s.lane_gathers());

        // Now a return is followed by an immediate send of what is pending.
        submit_one(&s, next_id).await;
        let _ = dispatch_within(&s, 200).await.unwrap();
        submit_one(&s, next_id + 1).await;
        s.note_return(1, Duration::from_millis(30));
        let sent = Instant::now();
        let batch = dispatch_within(&s, 200).await.unwrap();
        assert!(
            sent.elapsed() < Duration::from_millis(8),
            "no gather: {:?}",
            sent.elapsed()
        );
        assert_eq!(batch.flush_reason, FlushReason::Drain);
    }

    #[tokio::test]
    async fn a_full_batch_goes_ahead_while_a_batch_is_out() {
        let s = lane_scheduler(4);
        submit_one(&s, 0).await;
        let _ = dispatch_within(&s, 200).await.unwrap();
        for id in 1..=3 {
            submit_one(&s, id).await;
        }
        assert!(
            dispatch_within(&s, 30).await.is_none(),
            "three of four: held"
        );
        submit_one(&s, 4).await;
        let batch = dispatch_within(&s, 200)
            .await
            .expect("a full batch is not held: waiting cannot improve it");
        assert_eq!(batch.size(), 4);
        assert_eq!(batch.flush_reason, FlushReason::CountCap);
    }

    #[tokio::test]
    async fn with_the_idle_bypass_off_an_idle_lane_waits_the_classic_window() {
        let s = lane_scheduler(64);
        submit_one(&s, 0).await;
        let started = Instant::now();
        let batch = timeout(TDuration::from_millis(500), s.next_dispatch(false))
            .await
            .expect("the coalesce window releases the batch")
            .batch;
        assert!(
            started.elapsed() >= Duration::from_millis(35),
            "sent after {:?}, before the 40 ms coalesce window",
            started.elapsed()
        );
        assert_eq!(batch.flush_reason, FlushReason::Coalesce);
    }

    #[tokio::test]
    async fn a_batch_out_on_one_queue_holds_the_other_queues_too() {
        // The queues of a model share its engine.
        let s = lane_scheduler(64);
        s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 1, idx: 0 }, 1)
            .await;
        let _ = dispatch_within(&s, 200).await.unwrap();
        s.submit(
            Op::Encode,
            LoraKey::from_name("other"),
            StubItem { cost: 1, idx: 0 },
            2,
        )
        .await;
        assert!(dispatch_within(&s, 30).await.is_none());
        s.note_return(1, Duration::ZERO);
        let batch = dispatch_within(&s, 200).await.unwrap();
        assert_eq!(batch.metadata, vec![2]);
    }

    #[tokio::test]
    async fn the_rest_of_a_cut_request_follows_at_once_and_is_not_gathered_for() {
        #[derive(Debug)]
        struct OneRequest(usize);
        impl HasCost for OneRequest {
            fn cost(&self) -> u64 {
                1
            }
            fn original_index(&self) -> usize {
                self.0
            }
            fn request_key(&self) -> Option<&str> {
                Some("a")
            }
        }
        let s: Scheduler<OneRequest, usize> = Scheduler::builder()
            .config(BatchConfig {
                max_batch_cost: 1_000_000,
                max_batch_requests: 4,
                max_batch_wait_ms: 10_000.0,
                coalesce_ms: 40.0,
                coalesce_ratio: 1.0,
                ..BatchConfig::default()
            })
            .build();
        // One request of six items under an item cap of four.
        s.submit_many(
            Op::Extract,
            LoraKey::base(),
            (0..6).map(|i| (OneRequest(i), i)).collect(),
        )
        .await;
        let first = timeout(TDuration::from_millis(200), s.next_dispatch(true))
            .await
            .expect("the full part leaves at once");
        assert_eq!(first.batch.size(), 4);
        assert_eq!(
            first.completes, 0,
            "the request still has two items pending"
        );
        // The rest is not full, but its caller is waiting on the first
        // part: it follows into the next free slot without waiting for
        // the return.
        let second = timeout(TDuration::from_millis(200), s.next_dispatch(true))
            .await
            .expect("the rest follows the first part");
        assert_eq!(second.batch.size(), 2);
        assert_eq!(second.completes, 1);

        // The first part answered nobody: its return opens no gather. A new
        // request that arrives after both are back leaves at once (a gather
        // would be 30 ms here, half the round trip).
        s.note_return(first.completes, Duration::from_millis(60));
        s.note_return(0, Duration::from_millis(60));
        s.submit(Op::Extract, LoraKey::base(), OneRequest(9), 9)
            .await;
        let sent = Instant::now();
        let third = timeout(TDuration::from_millis(200), s.next_dispatch(true))
            .await
            .expect("an idle lane sends at once");
        assert!(
            sent.elapsed() < Duration::from_millis(10),
            "waited {:?}",
            sent.elapsed()
        );
        assert_eq!(third.batch.size(), 1);
    }

    #[tokio::test]
    async fn a_full_batch_on_a_younger_queue_does_not_overtake_an_older_held_one() {
        // First come, first served across queues: while a batch is out, the
        // older queue's partial batch is held, and the younger queue's full
        // batch does not take the free slot ahead of it. If it did, the
        // older requests would wait one more forward, for the younger ones.
        let s = lane_scheduler(2);
        let older = LoraKey::from_name("older");
        let younger = LoraKey::from_name("younger");
        s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 1, idx: 0 }, 0)
            .await;
        let _ = dispatch_within(&s, 200).await.unwrap();

        s.submit(Op::Encode, older.clone(), StubItem { cost: 1, idx: 0 }, 1)
            .await;
        tsleep(TDuration::from_millis(2)).await;
        for id in [2, 3] {
            s.submit(
                Op::Encode,
                younger.clone(),
                StubItem { cost: 1, idx: 0 },
                id,
            )
            .await;
        }
        assert!(
            dispatch_within(&s, 30).await.is_none(),
            "the younger queue is full, but it is not its turn",
        );

        s.note_return(1, Duration::ZERO);
        let first = timeout(TDuration::from_millis(200), s.next_dispatch(true))
            .await
            .expect("the older queue goes when the lane is free");
        assert_eq!(first.lora, older);
        assert_eq!(first.batch.metadata, vec![1]);
        // Now the younger queue's head is the oldest, and its full batch
        // takes the second slot at once.
        let second = timeout(TDuration::from_millis(200), s.next_dispatch(true))
            .await
            .expect("a full batch whose turn has come is not held");
        assert_eq!(second.lora, younger);
        assert_eq!(second.batch.metadata, vec![2, 3]);
        assert_eq!(second.batch.flush_reason, FlushReason::CountCap);
    }

    #[test]
    fn requests_are_counted_by_key_and_unkeyed_items_one_each() {
        struct Keyed(Option<&'static str>);
        impl HasCost for Keyed {
            fn cost(&self) -> u64 {
                1
            }
            fn original_index(&self) -> usize {
                0
            }
            fn request_key(&self) -> Option<&str> {
                self.0
            }
        }
        let items = [
            Keyed(Some("a")),
            Keyed(Some("a")),
            Keyed(Some("b")),
            Keyed(None),
            Keyed(None),
        ];
        assert_eq!(distinct_requests(items.iter()), 4);
    }

    // ---- Adaptive controller wiring ----

    #[tokio::test]
    async fn record_completion_propagates_config_to_all_batchers() {
        let ctrl = AdaptiveBatchController::builder()
            .target_p50_ms(Some(50.0))
            .update_interval(1) // step on every record_completion
            .min_wait_ms(1.0)
            .max_wait_ms(100.0)
            .min_batch_cost(100)
            .max_batch_cost(100_000)
            .initial_wait_ms(20.0)
            .initial_batch_cost(5_000)
            .build();
        let s = Scheduler::<StubItem, u32>::builder()
            .config(BatchConfig {
                max_batch_cost: 5_000,
                max_batch_requests: 1000,
                max_batch_wait_ms: 20.0,
                coalesce_ms: 20.0,
                coalesce_ratio: 0.5,
                ..BatchConfig::default()
            })
            .controller(ctrl)
            // Short warm-up so a handful of completions is enough to
            // drive p50 — the default is 10 samples which would force
            // a noisier test.
            .latency_window(20, 3)
            .build();

        // Submit to two distinct LoRAs so we can observe propagation
        // to both.
        s.submit(
            Op::Encode,
            LoraKey::from_name("a"),
            StubItem { cost: 1, idx: 0 },
            0,
        )
        .await;
        s.submit(
            Op::Encode,
            LoraKey::from_name("b"),
            StubItem { cost: 1, idx: 0 },
            0,
        )
        .await;

        // Simulate several completions with observed < target so the
        // latency tracker crosses its warm-up threshold and the PI
        // loop bumps `wait_ms` upward.
        for _ in 0..5 {
            s.record_latency_sample(10.0).await;
            let _ = s.record_completion(32, 32).await;
        }

        let cfg_a = {
            let map = s.batchers.read().await;
            map[&(Op::Encode, LoraKey::from_name("a"))]
                .former
                .config()
                .await
        };
        let cfg_b = {
            let map = s.batchers.read().await;
            map[&(Op::Encode, LoraKey::from_name("b"))]
                .former
                .config()
                .await
        };
        assert!(
            cfg_a.max_batch_wait_ms > 20.0,
            "wait must have grown from 20 (positive headroom); got {}",
            cfg_a.max_batch_wait_ms
        );
        assert_eq!(
            cfg_a, cfg_b,
            "all batchers must see the same caps after record_completion"
        );
        // Scheduler's own snapshot tracks the same value.
        assert_eq!(s.config().await, cfg_a);
    }

    #[tokio::test]
    async fn record_completion_feeds_efficiency_tracker() {
        // Efficiency tracker must see a fill ratio; confirm by
        // running enough completions to tighten cost knob.
        let ctrl = AdaptiveBatchController::builder()
            .target_p50_ms(Some(50.0))
            .update_interval(1)
            .fill_ratio_threshold(0.1) // always saturated in test terms
            .cost_gain(1.0)
            .initial_batch_cost(1_000)
            .min_batch_cost(100)
            .max_batch_cost(10_000)
            .build();
        let s = Scheduler::<StubItem, u32>::builder()
            .config(BatchConfig {
                max_batch_cost: 1_000,
                max_batch_requests: 1000,
                max_batch_wait_ms: 15.0,
                coalesce_ms: 15.0,
                coalesce_ratio: 0.5,
                ..BatchConfig::default()
            })
            .controller(ctrl)
            .build();
        s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 1, idx: 0 }, 0)
            .await;

        // Many completions with observed < target and a high fill
        // ratio → cost must grow.
        let before = s.config().await.max_batch_cost;
        for _ in 0..20 {
            s.record_latency_sample(10.0).await;
            let _ = s.record_completion(800, 32).await;
        }
        let after = s.config().await.max_batch_cost;
        assert!(after > before, "cost cap must grow: {before} → {after}");
    }

    #[tokio::test]
    async fn controller_snapshot_reflects_latency_and_fill() {
        let s = Scheduler::<StubItem, u32>::builder()
            .config(BatchConfig::default())
            .controller(
                AdaptiveBatchController::builder()
                    .target_p50_ms(Some(50.0))
                    .update_interval(1)
                    .build(),
            )
            .build();
        // Seed enough samples to cross the latency tracker's min.
        for _ in 0..12 {
            s.record_latency_sample(10.0).await;
            let _ = s.record_completion(32, 32).await;
        }
        let snap = s.controller_snapshot().await;
        assert_eq!(snap.target_p50_ms, Some(50.0));
        assert_eq!(snap.observed_p50_ms, Some(10.0));
        assert_eq!(snap.headroom_ms, Some(40.0));
        assert!(snap.fill_ratio.is_some());
    }

    #[tokio::test]
    async fn drain_feeds_do_not_step_controller() {
        // Regression for #4: Python's `_process_loop` steps the
        // adaptive controller exactly once per wave, with the
        // primary batch's size (`model_worker.py:828, 855-870`).
        // Drains feed inference + latency samples but must not
        // advance the controller's internal state.
        //
        // Encoded here at the scheduler level: the dispatcher
        // routes Primary → `record_completion`, Drain →
        // `record_inference_sample` + `record_latency_samples`
        // (no `record_completion`). This test exercises the
        // scheduler-side surface contract; the
        // [`crate::dispatcher::WaveRole`] enum + the
        // `scheduler_drain_loop` plumbing make sure drains take
        // the second path.
        let ctrl = AdaptiveBatchController::builder()
            .target_p50_ms(Some(50.0))
            .update_interval(1) // step on every record_completion
            .starvation_batch_size(1) // size>1 resets streak; we use
            // batch_size=1 so each `step()` strictly increments.
            .build();
        let s = Scheduler::<StubItem, u32>::builder()
            .config(BatchConfig::default())
            .controller(ctrl)
            .latency_window(20, 1)
            .build();

        // Wave 1 — primary at batch_size=1 increments the streak.
        s.record_latency_sample(10.0).await;
        let _ = s.record_completion(1, 1).await;
        assert_eq!(
            s.controller_snapshot().await.starvation_streak,
            1,
            "primary must advance streak"
        );

        // Three drains — feed inference + latency only. Streak
        // must NOT advance.
        for _ in 0..3 {
            s.record_inference_sample(8.0).await;
            s.record_latency_samples(&[10.0]).await;
        }
        assert_eq!(
            s.controller_snapshot().await.starvation_streak,
            1,
            "drain feeds must not step the controller (streak should stay at 1, got {})",
            s.controller_snapshot().await.starvation_streak,
        );

        // Wave 2 — next primary advances exactly once again.
        s.record_latency_sample(10.0).await;
        let _ = s.record_completion(1, 1).await;
        assert_eq!(
            s.controller_snapshot().await.starvation_streak,
            2,
            "second primary must advance streak by exactly one wave",
        );
    }

    #[tokio::test]
    async fn inference_sample_feeds_autocalibration() {
        let ctrl = AdaptiveBatchController::builder()
            .target_p50_ms(None) // auto-calibrate
            .calibration_multiplier(2.0)
            .update_interval(1)
            .build();
        let s = Scheduler::<StubItem, u32>::builder()
            .controller(ctrl)
            .build();

        // Feed 20 inference samples at 10 ms so inference_p50 = 10.
        for _ in 0..20 {
            s.record_inference_sample(10.0).await;
        }
        // One completion triggers the calibration step.
        let _ = s.record_completion(0, 1).await;
        let snap = s.controller_snapshot().await;
        assert!(snap.calibrated);
        assert_eq!(snap.target_p50_ms, Some(20.0));
    }

    #[tokio::test]
    async fn record_completion_returns_populated_outcome_shape() {
        // Verify the new outcome plumbing: every field is populated
        // with the post-step controller state. The starvation
        // recovery itself is already exhaustively tested in
        // `adaptive.rs::tests::starvation_recovery_*`; here we just
        // confirm the snapshot wiring carries the values through.
        let ctrl = AdaptiveBatchController::builder()
            .target_p50_ms(Some(50.0))
            .update_interval(1)
            .initial_wait_ms(20.0)
            .initial_batch_cost(4_000)
            .build();
        let s = Scheduler::<StubItem, u32>::builder()
            .config(BatchConfig::default())
            .controller(ctrl)
            .latency_window(20, 1)
            .build();

        s.record_latency_sample(10.0).await;
        let snap = s.record_completion(800, 32).await;

        assert!(snap.new_wait_ms > 0.0);
        assert!(snap.new_batch_cost > 0);
        assert_eq!(snap.batch_size, 32);
        assert_eq!(snap.target_p50_ms, Some(50.0));
        assert_eq!(snap.observed_p50_ms, Some(10.0));
        assert!(snap.fill_ratio.is_some());
        // No starvation triggered yet → delta is zero.
        assert_eq!(snap.starvation_resets_delta, 0);

        // After the step the scheduler's shared config snapshot
        // carries the same caps as the returned outcome — operators
        // reading `s.config()` after a completion see the same
        // numbers returned by the controller step.
        let cfg = s.config().await;
        assert_eq!(cfg.max_batch_wait_ms, snap.new_wait_ms);
        assert_eq!(cfg.max_batch_cost, snap.new_batch_cost);
    }

    // ---- BatchConfig-derived production-parity defaults ----

    #[tokio::test]
    async fn builder_default_controller_uses_production_parity_floors() {
        // No `.controller(...)` supplied → builder must derive the
        // controller from the BatchConfig with Python production
        // wiring (min_wait_ms=15, min_batch_cost=cfg.max_batch_cost/4,
        // cost_gain=gain*0.5). This is the production code path —
        // every deployed Rust scheduler hits this branch.
        let s: Scheduler<StubItem, u32> = Scheduler::builder()
            .config(BatchConfig::default()) // max_batch_cost = 16_384
            .build();
        let snap = s.controller_snapshot().await;
        // Snapshot doesn't expose floors directly; reach into the
        // controller via the lock for these invariants.
        let ctrl = s.controller.lock().await;
        assert!(
            (ctrl.min_wait_ms - 15.0).abs() < f64::EPSILON,
            "builder must produce production-parity min_wait_ms=15.0, got {}",
            ctrl.min_wait_ms
        );
        assert_eq!(
            ctrl.min_batch_cost, 4_096,
            "builder must produce production-parity min_batch_cost=max_batch_tokens/4"
        );
        assert!(
            (ctrl.cost_gain - (ctrl.gain * 0.5)).abs() < f64::EPSILON,
            "builder must produce coupled cost_gain = gain*0.5"
        );
        // Sanity: snapshot still reflects an uncalibrated auto-mode
        // scheduler — production deploys auto-calibrate target_p50.
        assert!(!snap.calibrated);
        assert!(snap.target_p50_ms.is_none());
    }

    #[tokio::test]
    async fn adopt_cost_budget_rebases_every_batcher_and_rebuilds_the_controller() {
        let s: Scheduler<StubItem, u32> = Scheduler::new(BatchConfig::default());
        assert_eq!(s.cost_budget(), 16_384);
        for lora in ["a", "b"] {
            s.submit(
                Op::Extract,
                LoraKey::from_name(lora),
                StubItem { cost: 1, idx: 0 },
                0,
            )
            .await;
        }
        // Mark the controller, then move the caps off their initial values
        // as controller steps do.
        for _ in 0..3 {
            let _ = s.record_completion(1, 1).await;
        }
        assert_eq!(s.controller_snapshot().await.starvation_streak, 3);
        {
            let mut cfg = s.config.write().await;
            cfg.max_batch_wait_ms = 42.0;
            cfg.max_batch_cost = 9_000;
        }

        assert!(s.adopt_cost_budget(720_000).await);

        let expected = BatchConfig {
            max_batch_cost: 720_000,
            ..BatchConfig::default()
        };
        assert_eq!(s.config().await, expected, "re-based from the initial caps");
        assert_eq!(s.cost_budget(), 720_000);
        for lora in ["a", "b"] {
            let former = {
                let map = s.batchers.read().await;
                Arc::clone(&map[&(Op::Extract, LoraKey::from_name(lora))].former)
            };
            assert_eq!(former.config().await, expected, "batcher {lora}");
        }
        {
            let ctrl = s.controller.lock().await;
            assert_eq!(
                (
                    ctrl.min_batch_cost,
                    ctrl.max_batch_cost,
                    ctrl.current_batch_cost()
                ),
                (180_000, 2_880_000, 720_000)
            );
            assert_eq!(ctrl.starvation_streak(), 0, "a fresh controller");
        }
        assert_eq!(s.efficiency.lock().await.sample_count(), 0);

        // The same budget again changes nothing.
        let _ = s.record_completion(1, 1).await;
        assert!(!s.adopt_cost_budget(720_000).await);
        assert_eq!(s.controller_snapshot().await.starvation_streak, 1);
    }

    #[tokio::test]
    async fn adopt_cost_budget_rebases_the_gather_windows_after_a_return() {
        let s: Scheduler<StubItem, u32> = Scheduler::new(BatchConfig::default());
        // Windows a controller step left behind.
        s.gather_quiet_us.store(1, Ordering::Release);
        s.gather_longest_us.store(2, Ordering::Release);

        assert!(s.adopt_cost_budget(720_000).await);

        let initial = BatchConfig::default();
        assert_eq!(
            s.gather_quiet_us.load(Ordering::Acquire),
            whole_micros(initial.effective_coalesce_ms())
        );
        assert_eq!(
            s.gather_longest_us.load(Ordering::Acquire),
            whole_micros(initial.max_batch_wait_ms)
        );
    }

    // ---- The lane beside the runs-alone lane ----

    /// Prepared audio: clips batch together, recordings over 30 s run alone
    /// (`batch_former` point 5).
    #[derive(Debug, Clone)]
    struct Audio {
        ms: u64,
        alone: bool,
        key: &'static str,
    }

    impl HasCost for Audio {
        fn cost(&self) -> u64 {
            self.ms
        }
        fn hard_batch_cost_cap(&self) -> Option<u64> {
            Some(crate::audio_prep::MAX_AUDIO_BATCH_DURATION_MS)
        }
        fn runs_alone(&self) -> bool {
            self.alone
        }
        fn original_index(&self) -> usize {
            0
        }
        fn request_key(&self) -> Option<&str> {
            Some(self.key)
        }
    }

    fn audio_clip(key: &'static str, seconds: u64) -> Audio {
        Audio {
            ms: seconds * 1_000,
            alone: false,
            key,
        }
    }

    fn recording(key: &'static str, seconds: u64) -> Audio {
        Audio {
            ms: seconds * 1_000,
            alone: true,
            key,
        }
    }

    /// Whisper's budget (720000 ms) and the default item cap, with batch
    /// wait and coalesce windows that do not fire by themselves in a test.
    fn audio_lane() -> Arc<Scheduler<Audio, &'static str>> {
        Arc::new(
            Scheduler::builder()
                .config(BatchConfig {
                    max_batch_cost: 720_000,
                    max_batch_wait_ms: 10_000.0,
                    coalesce_ms: 40.0,
                    coalesce_ratio: 1.0,
                    ..BatchConfig::default()
                })
                .env_lookup(Arc::new(|_| None))
                .build(),
        )
    }

    async fn put(s: &Scheduler<Audio, &'static str>, item: Audio) {
        let key = item.key;
        s.submit(Op::Extract, LoraKey::base(), item, key).await;
    }

    /// The names in the next batch the lane sends within `ms`, if any.
    async fn sent_within(
        s: &Arc<Scheduler<Audio, &'static str>>,
        ms: u64,
    ) -> Option<Vec<&'static str>> {
        timeout(TDuration::from_millis(ms), s.next_dispatch(true))
            .await
            .ok()
            .map(|dispatch| {
                let mut names = dispatch.batch.metadata;
                names.sort_unstable();
                names
            })
    }

    #[tokio::test]
    async fn a_long_recording_pending_does_not_send_a_clip_batch_ahead() {
        // r2 (7 min) is longer than half the cap, so the whole queue would
        // count as full. The clips' batch can still grow, so the lane holds
        // it while r1 is with the engine, and the clip that arrives during
        // r1's forward joins it, ahead of r2.
        let s = audio_lane();
        put(&s, recording("r1", 40)).await;
        assert_eq!(sent_within(&s, 200).await, Some(vec!["r1"]));
        put(&s, recording("r2", 420)).await;
        put(&s, audio_clip("c1", 5)).await;
        assert_eq!(sent_within(&s, 30).await, None, "held while r1 is out");
        put(&s, audio_clip("c2", 5)).await;

        s.note_return(1, Duration::from_millis(200));
        assert_eq!(sent_within(&s, 300).await, Some(vec!["c1", "c2"]));
        s.note_return(2, Duration::from_millis(200));
        assert_eq!(sent_within(&s, 300).await, Some(vec!["r2"]));
    }

    #[tokio::test]
    async fn a_long_recording_waits_for_clips_that_arrive_during_a_recording() {
        // r2 queued behind r1 cannot grow, but sending it into the second
        // slot would make a clip that arrives during r1 wait for both. Held,
        // r2 lets that clip take its turn first.
        let s = audio_lane();
        put(&s, recording("r1", 40)).await;
        assert_eq!(sent_within(&s, 200).await, Some(vec!["r1"]));
        put(&s, recording("r2", 420)).await;
        assert_eq!(sent_within(&s, 30).await, None, "held while r1 is out");
        put(&s, audio_clip("c", 5)).await;

        s.note_return(1, Duration::from_millis(200));
        assert_eq!(sent_within(&s, 300).await, Some(vec!["c"]));
        s.note_return(1, Duration::from_millis(200));
        assert_eq!(sent_within(&s, 300).await, Some(vec!["r2"]));
    }

    #[tokio::test]
    async fn a_long_recording_after_a_clip_batch_still_leaves_at_once() {
        // After a clip batch the recording goes next whatever arrives (point
        // 5), so holding it gains nothing: a 7 min one is full, as on main.
        let s = audio_lane();
        put(&s, audio_clip("c", 5)).await;
        assert_eq!(sent_within(&s, 200).await, Some(vec!["c"]));
        put(&s, recording("r", 420)).await;
        assert_eq!(sent_within(&s, 30).await, Some(vec!["r"]));
    }

    #[tokio::test]
    async fn a_full_clip_batch_still_leaves_while_a_recording_is_out() {
        // Twelve clips fill a batch whatever the recordings pending, so the
        // lane sends them into the second slot, as for any other full batch.
        let s = audio_lane();
        put(&s, recording("r1", 40)).await;
        assert_eq!(sent_within(&s, 200).await, Some(vec!["r1"]));
        put(&s, recording("r2", 60)).await;
        const CLIPS: [&str; 12] = [
            "c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12",
        ];
        for name in CLIPS {
            put(&s, audio_clip(name, 2)).await;
        }
        assert_eq!(sent_within(&s, 30).await, Some(CLIPS.to_vec()));
    }

    // ---- Aggregates ----

    #[tokio::test]
    async fn pending_count_and_cost_sum_across_batchers() {
        let s = make();
        s.submit(
            Op::Encode,
            LoraKey::from_name("a"),
            StubItem { cost: 5, idx: 0 },
            0,
        )
        .await;
        s.submit(
            Op::Encode,
            LoraKey::from_name("b"),
            StubItem { cost: 7, idx: 0 },
            0,
        )
        .await;
        s.submit(Op::Score, LoraKey::base(), StubItem { cost: 3, idx: 0 }, 0)
            .await;
        assert_eq!(s.total_pending_count().await, 3);
        assert_eq!(s.total_pending_cost().await, 15);
    }
}