Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
perf(sidecar): hold arrivals while the engine is busy and send them together when its batch returns (#725)
svonava761a060e0e5a
diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex 81fce64d0..803b4e5e5 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -544,8 +544,59 @@ query/document pair. The cached score estimate never enters the IPC schema,never mutates or truncates inputs, and is not an authoritative token or billingcount. Extract currently uses unit cost.+The item cap (`SIE_BATCHER_MAX_BATCH_REQUESTS`, default 12) cuts a request of+more items than the cap into batches that run one after another.+`SIE_BATCHER_MAX_REQUEST_ITEMS` (default 0, off) keeps a request of up to that+many items in one batch past the item cap; the cost cap and the per-item media+caps still cut. It is off by default because whether one large batch beats+several smaller ones is the adapter's property: one that pads a batch to its+longest row can be slower on the whole request.++### When a batch leaves++An engine that runs one batch at a time is the scarce thing on its lane. A batch+sent while another is still with it only waits at the engine's lock, with its+membership frozen; the requests that come back a moment later start a batch of+their own behind it, and two groups then take turns, each request waiting for+the other group's forward. The drain loop therefore asks the model's lane+([`scheduler/lane.rs`](../src/scheduler/lane.rs)) when the next batch leaves:++1. **Idle lane: at once.** Nothing is with the engine and no batch has just+ come back. The request leaves immediately with everything else pending. A+ lone request, of one item or of several, never waits a window.+2. **Busy lane: hold.** While a batch is with the engine, arrivals stay in the+ queue, where later arrivals can join them. Two things take the second+ pipeline slot (`SIE_RUST_PIPELINE_DEPTH`, default 2) instead: the next batch+ if it is already full (item cap, cost cap, one request over the cost cap, or+ no room under the cost cap for another item like its largest), because+ holding it cannot improve it, and the rest of a request whose first part is+ with the engine, because its caller is waiting on that part. The+ next batch is the one of the `(operation, LoRA)` queue whose head is oldest:+ a full batch on a younger queue does not overtake an older queue's held one.+3. **On a return: gather once, then send everything pending.** The callers just+ answered are the ones most likely to come straight back. The lane waits for+ as many arrivals as the returned batch answered. It stops waiting when+ nothing has arrived for the coalesce window (`SIE_BATCHER_COALESCE_MS`,+ default 5), and in any case after half the returned batch's round trip or+ the batch wait (`SIE_BATCHER_MAX_BATCH_WAIT_MS`), whichever is shorter.+ `SIE_BATCHER_COALESCE_MS=0` turns the gather off. A batch that answered+ nobody (the first part of a request the item cap cut) is followed by an+ immediate send.+4. **No gather where it does not pay.** The lane keeps a running score of+ whether returns are followed by that many arrivals inside the window. A+ closed loop of callers scores high. Arrivals at random times score low, and a+ return is then followed by an immediate send of what is pending. The score+ is updated either way, so the lane notices when callers start coming back.++`SIE_BATCHER_IDLE_BYPASS_ENABLED=false` makes an idle lane wait for the classic+triggers (caps, batch wait, coalesce window since the last arrival) instead of+rule 1. `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 those+triggers allow.+A model whose descriptor reports `max_concurrent_dispatch` above 1 fronts an-engine that batches continuously, such as SGLang serving an OCR model. A shared+engine that batches continuously, such as SGLang serving an OCR model. Its lane+keeps the earlier loop: there is no single forward to wait for. A shared`RunBatch` would only make each item wait for the slowest one, so the drainloop sends each of that model's extract items in a `RunBatch` of its own. Themodel's pipeline depth becomes the larger of `SIE_RUST_PIPELINE_DEPTH` and thatdiff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex 4f902fffb..d091ca957 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -5972,6 +5972,11 @@ fn decrement_gauge(gauge: &RuntimeGauge, value: i64) {/// 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@@ -5991,7 +5996,10 @@ fn pipeline_depth() -> usize {/// 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.+/// 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@@ -6011,6 +6019,87 @@ fn scheduler_idle_bypass_enabled() -> bool {})}+/// 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.@@ -6190,10 +6279,13 @@ pub(crate) async fn scheduler_drain_loop(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",);@@ -6260,8 +6352,85 @@ pub(crate) async fn scheduler_drain_loop(// 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,@@ -7648,6 +7817,99 @@ mod tests {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));@@ -8920,6 +9182,7 @@ mod tests {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_semdiff --git a/packages/sie_server_sidecar/src/scheduler/batch_config.rs b/packages/sie_server_sidecar/src/scheduler/batch_config.rsindex a1cb974eb..6e88bc663 100644--- a/packages/sie_server_sidecar/src/scheduler/batch_config.rs+++ b/packages/sie_server_sidecar/src/scheduler/batch_config.rs@@ -58,6 +58,17 @@ pub struct BatchConfig {/// keeps the coalesce time proportional when the adaptive/// controller mutates `max_batch_wait_ms`.pub coalesce_ratio: f64,++ /// Largest request that leaves in one batch even past+ /// [`Self::max_batch_requests`]. `0`, the default, is off: the item+ /// cap cuts a request as it cuts a burst.+ ///+ /// When set, a request of up to this many items whose turn has come is+ /// taken whole (the cost cap and the per-item hard caps still cut). It+ /// is off by default because whether one large batch beats several+ /// smaller ones is the adapter's property: an adapter that pads a+ /// batch to its longest row can be slower on the whole request.+ pub max_request_items: usize,}impl BatchConfig {@@ -77,6 +88,7 @@ impl BatchConfig {/// | `SIE_BATCHER_MAX_BATCH_REQUESTS` | `max_batch_requests` | **12** | Hard count cap (controller does not move). **Diverges from Python's 64** — see [`BatchConfig::default`] for the runtime rationale. |/// | `SIE_BATCHER_COALESCE_MS` | `coalesce_ms` | **5.0** | Coalesce window ceiling. **Diverges from Python's 15.0** — see [`BatchConfig::default`] for the runtime rationale. |/// | `SIE_BATCHER_COALESCE_RATIO` | `coalesce_ratio` | 0.5 | Coalesce as fraction of `max_batch_wait_ms`. |+ /// | `SIE_BATCHER_MAX_REQUEST_ITEMS` | `max_request_items` | 0 (off) | Largest request kept in one batch past the item cap. Not in Python. |////// Bad values (non-numeric, NaN) log a warning and fall back to/// the default — never crash the registry init.@@ -120,6 +132,9 @@ impl BatchConfig {if let Some(v) = get_f64("SIE_BATCHER_COALESCE_RATIO") {c.coalesce_ratio = v;}+ if let Some(v) = get_usize("SIE_BATCHER_MAX_REQUEST_ITEMS") {+ c.max_request_items = v;+ }tracing::info!(max_batch_cost = c.max_batch_cost,@@ -127,6 +142,7 @@ impl BatchConfig {max_batch_wait_ms = c.max_batch_wait_ms,coalesce_ms = c.coalesce_ms,coalesce_ratio = c.coalesce_ratio,+ max_request_items = c.max_request_items,"batcher: BatchConfig constructed from env+defaults");@@ -169,6 +185,9 @@ impl Default for BatchConfig {/// `tests::defaults_diverge_from_python_intentionally` so Python parity/// is not restored by accident; retunes should update this rationale and/// the test together.+ ///+ /// `max_request_items` has no Python counterpart and is off: the item+ /// cap cuts a request of more items than the cap, as in Python.fn default() -> Self {Self {max_batch_cost: 16_384,@@ -176,6 +195,7 @@ impl Default for BatchConfig {max_batch_wait_ms: 15.0,coalesce_ms: 5.0,coalesce_ratio: 0.5,+ max_request_items: 0,}}}@@ -210,6 +230,8 @@ mod tests {c.max_batch_requests, 12,"expected max_batch_requests=12 (Rust-side worker default)");+ // Keeping a request whole past the item cap is opt-in.+ assert_eq!(c.max_request_items, 0);}#[test]diff --git a/packages/sie_server_sidecar/src/scheduler/batch_former.rs b/packages/sie_server_sidecar/src/scheduler/batch_former.rsindex 529265a1e..ddc3357ab 100644--- a/packages/sie_server_sidecar/src/scheduler/batch_former.rs+++ b/packages/sie_server_sidecar/src/scheduler/batch_former.rs@@ -20,6 +20,11 @@//! 4. **Timer refresh**: after a partial cost-sorted extract, first/last//! timestamps are re-anchored to the requests that remain; once the queue//! empties both are cleared so the next submit starts a fresh window.+//! 5. **A request can be kept whole** (`max_request_items`, off by+//! default): the request at the head of an extract is then taken with+//! all of its pending items even past the item cap, so one caller's+//! request is not cut into batches that run one after another. The cost+//! cap still cuts. Python has no such rule.//!//! Python currently retains its original first/last timers after a partial//! extract and clears them only when empty. Rust re-anchors them to the actual@@ -60,6 +65,15 @@ pub trait HasCost {/// Used by the adapter-side output router to zip results back to/// the correct request item.fn original_index(&self) -> usize;++ /// Identity of the request this item came from, when it has one.+ /// Items that share a key were sent by one caller in one request:+ /// the packer keeps them in one batch where the caps allow (see+ /// [`BatchConfig::max_request_items`]) and the lane counts them as one+ /// arrival. `None` means the item stands for itself.+ fn request_key(&self) -> Option<&str> {+ None+ }}/// A single request waiting to be batched, together with@@ -97,6 +111,12 @@ impl<I: HasCost, T> FormattedBatch<I, T> {self.total_cost}+ /// Number of requests the batch's items came from.+ #[must_use]+ pub fn request_count(&self) -> usize {+ super::engine::distinct_requests(self.items.iter())+ }+/// Return a new batch sorted by cost (ascending). Preserves the/// `items[i] ↔ metadata[i]` correspondence.///@@ -401,6 +421,37 @@ impl<I: HasCost, T> BatchFormer<I, T> {}}+ /// What a lane's dispatch rule ([`super::lane::Lane`]) reads from this+ /// queue: whether the pending work already fills a batch, and the+ /// classic flush triggers for a lane that has the idle bypass off.+ pub(crate) async fn gate_view(&self) -> GateView {+ let guard = self.inner.lock().await;+ GateView {+ full: full_reason(&guard),+ classic: flush_reason(&guard, false),+ classic_wait: wait_timeout(&guard),+ }+ }++ /// Take the next batch now, whatever the flush triggers say, under the+ /// usual caps. `reason` records why the lane sent it; a batch that is+ /// full keeps its cap as the reason. `None` when nothing is pending.+ ///+ /// The second value is the number of requests the batch completes:+ /// those with no item left pending here. A request cut by a cap is+ /// completed by the batch that takes its last items.+ pub(crate) async fn take(&self, reason: FlushReason) -> Option<(FormattedBatch<I, T>, usize)> {+ let mut guard = self.inner.lock().await;+ if guard.pending.is_empty() {+ return None;+ }+ let reason = full_reason(&guard).unwrap_or(reason);+ let batch = extract_batch(&mut guard, reason);+ self.refresh_fcfs_head(&guard);+ let completes = completed_requests(&batch.items, &guard.pending);+ Some((batch, completes))+ }+/// Refresh the atomic FCFS head from the queue while `inner` is locked.////// [`extract_batch_up_to`] recomputes the timers from the actual remainder,@@ -423,6 +474,22 @@ impl<I: HasCost, T> BatchFormer<I, T> {}}+/// Snapshot of one queue for the lane's dispatch rule.+#[derive(Debug, Clone, Copy, PartialEq)]+pub(crate) struct GateView {+ /// The cap the pending work has reached, if it already fills a batch:+ /// the item cap, the cost cap, one request over the cost cap, or no+ /// room under the cost cap for another item like its largest. Waiting+ /// cannot improve such a batch.+ pub full: Option<FlushReason>,+ /// The classic flush trigger that has fired, if any (caps, batch wait,+ /// coalesce window since the last arrival).+ pub classic: Option<FlushReason>,+ /// Time until a classic trigger fires by itself; `None` when nothing is+ /// pending.+ pub classic_wait: Option<Duration>,+}+// ---------------------------------------------------------------------// Free-standing helpers. Kept outside the `BatchFormer` impl so the// hot-path decisions are easy to test in isolation (see the `tests`@@ -509,6 +576,26 @@ fn flush_reason<I: HasCost, T>(inner: &Inner<I, T>, immediate: bool) -> Option<FNone}+/// The cap the pending work has reached, if any: one request over the cost+/// cap, the cost cap, the item cap, or a cost so close to the cap that+/// another item like the largest one pending would not fit.+///+/// The last case is what makes a single large item full by itself: a+/// 15,000-cost request under a 16,384 cap cannot share a batch with another+/// like it, so holding it for company only delays the engine-side+/// preparation that could overlap the forward before it.+fn full_reason<I: HasCost, T>(inner: &Inner<I, T>) -> Option<FlushReason> {+ if let reason @ Some(+ FlushReason::SingleOversize | FlushReason::CostCap | FlushReason::CountCap,+ ) = flush_reason(inner, false)+ {+ return reason;+ }+ let largest = inner.pending.iter().map(|r| r.item.cost()).max()?;+ (inner.total_cost.saturating_add(largest) > effective_max_cost(inner))+ .then_some(FlushReason::CostCap)+}+/// Time remaining until the next guaranteed flush, given current/// state. `None` means "wait indefinitely" (no pending items).fn wait_timeout<I: HasCost, T>(inner: &Inner<I, T>) -> Option<Duration> {@@ -572,6 +659,14 @@ fn extract_batch_up_to<I: HasCost, T>(let max_cost = effective_max_cost(inner);let max_requests = inner.config.max_batch_requests;+ // The request whose turn has come leaves whole: bring its other pending+ // items to the front, in their sorted order, and let the item cap stop+ // the pack only after them. The cap is there to bound how many arrivals+ // are merged, not to cut one caller's request into batches that run one+ // after another. The cost cap below still cuts, and a request of more+ // than `max_request_items` items is packed item by item as before.+ let head_request_len = bring_head_request_forward(inner);+// Greedy pack. Always take at least one item so a single large// request (cost ≥ max_cost) doesn't starve.let mut batch_cost: u64 = 0;@@ -591,7 +686,7 @@ fn extract_batch_up_to<I: HasCost, T>(}batch_cost += c;take_count += 1;- if take_count >= max_requests {+ if take_count >= max_requests && take_count >= head_request_len {break;}}@@ -629,6 +724,58 @@ fn extract_batch_up_to<I: HasCost, T>(}}+/// Number of requests among `taken` that have no item left in `pending`.+/// An item without a request key is a request of its own.+fn completed_requests<I: HasCost, T>(taken: &[I], pending: &[PendingRequest<I, T>]) -> usize {+ let still_pending: std::collections::HashSet<&str> = pending+ .iter()+ .filter_map(|request| request.item.request_key())+ .collect();+ let mut completed: std::collections::HashSet<&str> = std::collections::HashSet::new();+ let mut unkeyed = 0usize;+ for item in taken {+ match item.request_key() {+ Some(key) if still_pending.contains(key) => {}+ Some(key) => {+ completed.insert(key);+ }+ None => unkeyed += 1,+ }+ }+ completed.len() + unkeyed+}++/// Move the other pending items of the head item's request to the front,+/// keeping their order, and return how many items that request has pending.+/// Returns 0 (and moves nothing) when the head item has no request key, is+/// its request's only pending item, or its request is larger than+/// `max_request_items`.+fn bring_head_request_forward<I: HasCost, T>(inner: &mut Inner<I, T>) -> usize {+ let limit = inner.config.max_request_items;+ if limit <= 1 || inner.pending.len() <= 1 {+ return 0;+ }+ let Some(key) = inner.pending[0].item.request_key().map(str::to_owned) else {+ return 0;+ };+ let same_request =+ |request: &PendingRequest<I, T>| request.item.request_key() == Some(key.as_str());+ let len = inner+ .pending+ .iter()+ .filter(|request| same_request(request))+ .count();+ if len <= 1 || len > limit {+ return 0;+ }+ let (mut head, rest): (Vec<_>, Vec<_>) = std::mem::take(&mut inner.pending)+ .into_iter()+ .partition(same_request);+ head.extend(rest);+ inner.pending = head;+ len+}+#[cfg(test)]mod tests {use super::*;@@ -679,6 +826,227 @@ mod tests {}}+ /// An item that belongs to a request, as production items do.+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]+ struct RequestItem {+ request: &'static str,+ cost: u64,+ idx: usize,+ }++ impl HasCost for RequestItem {+ fn cost(&self) -> u64 {+ self.cost+ }+ fn original_index(&self) -> usize {+ self.idx+ }+ fn request_key(&self) -> Option<&str> {+ Some(self.request)+ }+ }++ fn request_items(request: &'static str, count: usize, cost: u64) -> Vec<(RequestItem, usize)> {+ (0..count)+ .map(|idx| (RequestItem { request, cost, idx }, idx))+ .collect()+ }++ fn batch_requests(batch: &FormattedBatch<RequestItem, usize>) -> Vec<(&'static str, usize)> {+ let mut counts: Vec<(&'static str, usize)> = Vec::new();+ for item in &batch.items {+ match counts+ .iter_mut()+ .find(|(request, _)| *request == item.request)+ {+ Some((_, count)) => *count += 1,+ None => counts.push((item.request, 1)),+ }+ }+ counts+ }++ /// The default caps with whole requests of up to 64 items switched on.+ fn whole_requests() -> BatchConfig {+ BatchConfig {+ max_request_items: 64,+ ..BatchConfig::default()+ }+ }++ #[tokio::test]+ async fn by_default_the_item_cap_cuts_a_request_and_the_last_batch_completes_it() {+ let former = BatchFormer::<RequestItem, usize>::new(BatchConfig::default());+ former.submit_many(request_items("a", 32, 1)).await;++ let (first, completes) = former.take(FlushReason::IdleBypass).await.unwrap();+ assert_eq!((first.size(), completes), (12, 0));+ assert_eq!(first.flush_reason, FlushReason::CountCap);+ let (second, completes) = former.take(FlushReason::IdleBypass).await.unwrap();+ assert_eq!((second.size(), completes), (12, 0));+ // The remainder is no longer full, and it is the batch that answers+ // the request.+ assert_eq!(former.gate_view().await.full, None);+ let (third, completes) = former.take(FlushReason::IdleBypass).await.unwrap();+ assert_eq!((third.size(), completes), (8, 1));+ assert_eq!(third.flush_reason, FlushReason::IdleBypass);+ assert_eq!(former.fcfs_head_ns(), 0);+ }++ #[tokio::test]+ async fn a_whole_request_larger_than_the_item_cap_leaves_in_one_batch() {+ // 12 items merged across requests, a request of up to 64 items+ // whole: 32 states in one request leave together, not as 12, 12+ // and 8.+ let former = BatchFormer::<RequestItem, usize>::new(whole_requests());+ former.submit_many(request_items("a", 32, 1)).await;++ let view = former.gate_view().await;+ assert_eq!(view.full, Some(FlushReason::CountCap));+ let (batch, completes) = former.take(FlushReason::IdleBypass).await.unwrap();+ assert_eq!(batch.size(), 32);+ assert_eq!(batch.request_count(), 1);+ assert_eq!(completes, 1);+ assert_eq!(batch.flush_reason, FlushReason::CountCap);+ let indices: Vec<usize> = batch.items.iter().map(HasCost::original_index).collect();+ assert_eq!(+ indices,+ (0..32).collect::<Vec<_>>(),+ "equal-cost items keep their order"+ );+ assert_eq!(former.pending_count().await, 0);+ assert_eq!(former.fcfs_head_ns(), 0);+ }++ #[tokio::test]+ async fn two_whole_requests_leave_as_two_batches() {+ let former = BatchFormer::<RequestItem, usize>::new(whole_requests());+ former.submit_many(request_items("a", 32, 1)).await;+ former.submit_many(request_items("b", 32, 1)).await;++ let first = former.try_drain().await.unwrap();+ assert_eq!(batch_requests(&first), vec![("a", 32)]);+ let second = former.try_drain().await.unwrap();+ assert_eq!(batch_requests(&second), vec![("b", 32)]);+ assert_eq!(former.pending_count().await, 0);+ }++ #[tokio::test]+ async fn the_item_cap_still_bounds_how_many_whole_requests_are_merged() {+ // Three requests of 8 items under an item cap of 12: the head+ // request whole, then the pack fills to the cap as it always did.+ let former = BatchFormer::<RequestItem, usize>::new(whole_requests());+ for request in ["a", "b", "c"] {+ former.submit_many(request_items(request, 8, 1)).await;+ }+ let (first, completes) = former.take(FlushReason::Drain).await.unwrap();+ assert_eq!(batch_requests(&first), vec![("a", 8), ("b", 4)]);+ assert_eq!(completes, 1, "b still has items pending");+ let (second, completes) = former.take(FlushReason::Drain).await.unwrap();+ assert_eq!(batch_requests(&second), vec![("b", 4), ("c", 8)]);+ assert_eq!(completes, 2);+ }++ #[tokio::test]+ async fn the_cost_cap_still_cuts_a_whole_request() {+ let former = BatchFormer::<RequestItem, usize>::new(BatchConfig {+ max_batch_cost: 100,+ ..whole_requests()+ });+ former.submit_many(request_items("a", 32, 10)).await;+ let sizes: Vec<usize> = [+ former.try_drain().await.unwrap(),+ former.try_drain().await.unwrap(),+ former.try_drain().await.unwrap(),+ former.try_drain().await.unwrap(),+ ]+ .iter()+ .map(FormattedBatch::size)+ .collect();+ assert_eq!(sizes, vec![10, 10, 10, 2]);+ }++ #[tokio::test]+ async fn a_request_over_the_whole_request_limit_is_cut_by_the_item_cap() {+ let former = BatchFormer::<RequestItem, usize>::new(whole_requests());+ former.submit_many(request_items("a", 65, 1)).await;+ assert_eq!(former.try_drain().await.unwrap().size(), 12);+ }++ #[tokio::test]+ async fn the_head_request_is_the_one_whose_turn_it_is() {+ // A cheap single-item request sorts ahead of a costlier large one,+ // and takes its turn first; the large request then leaves whole.+ let former = BatchFormer::<RequestItem, usize>::new(BatchConfig {+ max_batch_requests: 4,+ ..whole_requests()+ });+ former.submit_many(request_items("large", 6, 5)).await;+ former.submit_many(request_items("small", 1, 1)).await;+ let first = former.try_drain().await.unwrap();+ assert_eq!(batch_requests(&first), vec![("small", 1), ("large", 3)]);+ let second = former.try_drain().await.unwrap();+ assert_eq!(batch_requests(&second), vec![("large", 3)]);+ }++ #[tokio::test]+ async fn pending_work_with_no_room_for_another_like_its_largest_is_full() {+ let config = BatchConfig {+ max_batch_cost: 100,+ max_batch_wait_ms: 1_000_000.0,+ coalesce_ms: 1_000_000.0,+ coalesce_ratio: 1.0,+ ..BatchConfig::default()+ };+ // One item that could share the batch with another like it: not+ // full, the lane may hold it for company.+ let former = BatchFormer::<StubItem, usize>::new(config);+ former.submit(StubItem::with_idx(40, 0), 0).await;+ assert_eq!(former.gate_view().await.full, None);+ // A second one leaves no room for a third.+ former.submit(StubItem::with_idx(40, 1), 1).await;+ assert_eq!(former.gate_view().await.full, Some(FlushReason::CostCap));+ let (batch, _) = former.take(FlushReason::IdleBypass).await.unwrap();+ assert_eq!(batch.size(), 2);+ assert_eq!(batch.flush_reason, FlushReason::CostCap);++ // One item under the cap that another like it could not join (a+ // 20-candidate rerank request under the default cap): full alone.+ let former = BatchFormer::<StubItem, usize>::new(config);+ former.submit(StubItem::with_idx(60, 0), 0).await;+ assert_eq!(former.gate_view().await.full, Some(FlushReason::CostCap));+ // The classic triggers are unchanged: nothing has fired for it.+ assert_eq!(former.gate_view().await.classic, None);+ assert!(former.try_get_batch().await.is_none());+ }++ #[tokio::test]+ async fn take_sends_what_is_pending_without_a_flush_trigger() {+ let former = BatchFormer::<StubItem, usize>::new(BatchConfig {+ max_batch_wait_ms: 1_000_000.0,+ coalesce_ms: 1_000_000.0,+ coalesce_ratio: 1.0,+ ..BatchConfig::default()+ });+ assert!(former.take(FlushReason::IdleBypass).await.is_none());+ former.submit(StubItem::with_idx(3, 0), 0).await;+ former.submit(StubItem::with_idx(2, 1), 1).await;+ let view = former.gate_view().await;+ assert_eq!(view.full, None);+ assert_eq!(view.classic, None);+ assert!(view.classic_wait.is_some());++ let (batch, completes) = former.take(FlushReason::Coalesce).await.unwrap();+ assert_eq!(batch.metadata, vec![1, 0], "still cost-sorted");+ assert_eq!(batch.flush_reason, FlushReason::Coalesce);+ assert_eq!(batch.request_count(), 2);+ assert_eq!(+ completes, 2,+ "an item without a key is a request of its own"+ );+ assert_eq!(former.fcfs_head_ns(), 0);+ }+// Arrival age is a std::Instant value, so these tests backdate the real// pending requests rather than advancing Tokio's separate virtual clock.async fn set_request_ages<I: HasCost>(@@ -927,6 +1295,7 @@ mod tests {max_batch_wait_ms: 10_000.0, // big so only cost triggerscoalesce_ms: 10_000.0,coalesce_ratio: 1.0,+ ..BatchConfig::default()};let b = BatchFormer::<StubItem, u32>::new(cfg);b.submit(StubItem::new(15), 1).await;@@ -946,6 +1315,7 @@ mod tests {max_batch_wait_ms: 10_000.0,coalesce_ms: 10_000.0,coalesce_ratio: 1.0,+ ..BatchConfig::default()};let b = BatchFormer::<HardCapItem, u32>::new(cfg);b.submit(@@ -980,6 +1350,7 @@ mod tests {max_batch_wait_ms: 10_000.0,coalesce_ms: 10_000.0,coalesce_ratio: 1.0,+ ..BatchConfig::default()};let b = BatchFormer::<StubItem, u32>::new(cfg);b.submit(StubItem::new(1), 1).await;@@ -1103,6 +1474,7 @@ mod tests {max_batch_wait_ms: 20.0,coalesce_ms: 1_000.0,coalesce_ratio: 1.0, // coalesce ties max-wait; timeout wins by priority+ ..BatchConfig::default()};let b = BatchFormer::<StubItem, u32>::new(cfg);b.submit(StubItem::new(1), 1).await;@@ -1145,6 +1517,7 @@ mod tests {max_batch_wait_ms: 1_000_000.0,coalesce_ms: 1_000_000.0,coalesce_ratio: 1.0,+ ..BatchConfig::default()};let b = std::sync::Arc::new(BatchFormer::<StubItem, u32>::new(original));b.submit(StubItem::new(5), 1).await;diff --git a/packages/sie_server_sidecar/src/scheduler/engine.rs b/packages/sie_server_sidecar/src/scheduler/engine.rsindex 3f2466211..7000ef15d 100644--- a/packages/sie_server_sidecar/src/scheduler/engine.rs+++ b/packages/sie_server_sidecar/src/scheduler/engine.rs@@ -37,10 +37,11 @@//! 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;+use std::collections::{HashMap, HashSet};use std::hash::Hash;+use std::sync::atomic::{AtomicU64, Ordering};use std::sync::Arc;-use std::time::Instant;+use std::time::{Duration, Instant};use tokio::sync::{Mutex, Notify, RwLock};@@ -49,6 +50,7 @@ use crate::latency::LatencyTracker;use super::adaptive::AdaptiveBatchController;use super::batch_config::BatchConfig;use super::batch_former::{BatchFormer, FormattedBatch, HasCost};+use super::lane::{Lane, Verdict};use super::trackers::BatchEfficiencyTracker;/// Snapshot returned by [`Scheduler::record_completion`] for the@@ -90,6 +92,19 @@ pub struct RecordCompletionOutcome {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@@ -189,10 +204,20 @@ pub struct Scheduler<I: HasCost, T> {/// after each controller step. Kept behind an async `RwLock`/// because readers are rare (new-batcher creation only).config: RwLock<BatchConfig>,- /// Fired on every submit that inserts into a previously empty- /// batcher. [`Scheduler::consume_next`] uses this to wake its- /// FCFS scan without polling.+ /// 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,@@ -281,6 +306,7 @@ wherelet 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();}@@ -292,7 +318,9 @@ where}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();}@@ -322,6 +350,99 @@ where}}+ /// 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).@@ -462,6 +583,12 @@ wherecfg.max_batch_cost = new_cost;*cfg};+ self.gather_quiet_us.store(+ whole_micros(new_cfg.effective_coalesce_ms()),+ Ordering::Release,+ );+ self.gather_longest_us+ .store(whole_micros(new_cfg.max_batch_wait_ms), Ordering::Release);// Propagate to every live batcher. We snapshot the Vec of// Arcs under the read lock and drop it before the async@@ -491,6 +618,14 @@ where// ---- 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@@ -650,13 +785,46 @@ whereefficiency: Mutex::new(BatchEfficiencyTracker::new(self.efficiency_window)),config: RwLock::new(self.config),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};@@ -684,6 +852,7 @@ mod tests {max_batch_wait_ms: 10_000.0,coalesce_ms: 10_000.0,coalesce_ratio: 1.0,+ ..BatchConfig::default()}).build()}@@ -846,6 +1015,7 @@ mod tests {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),@@ -940,6 +1110,7 @@ mod tests {max_batch_wait_ms: 10_000.0,coalesce_ms: 10_000.0,coalesce_ratio: 1.0,+ ..BatchConfig::default()}).build();let base = LoraKey::base();@@ -998,6 +1169,375 @@ mod tests {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]@@ -1019,6 +1559,7 @@ mod tests {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@@ -1099,6 +1640,7 @@ mod tests {max_batch_wait_ms: 15.0,coalesce_ms: 15.0,coalesce_ratio: 0.5,+ ..BatchConfig::default()}).controller(ctrl).build();diff --git a/packages/sie_server_sidecar/src/scheduler/item.rs b/packages/sie_server_sidecar/src/scheduler/item.rsindex c61053447..da75a8a23 100644--- a/packages/sie_server_sidecar/src/scheduler/item.rs+++ b/packages/sie_server_sidecar/src/scheduler/item.rs@@ -244,6 +244,15 @@ impl HasCost for SchedulerItem {}}+ fn request_key(&self) -> Option<&str> {+ let request_id = match self {+ Self::Encode(e) => e.request_id.as_str(),+ Self::Score { item, .. } => item.request_id.as_str(),+ Self::Extract(x) => x.request_id.as_str(),+ };+ (!request_id.is_empty()).then_some(request_id)+ }+fn original_index(&self) -> usize {// Original request-local index is what the cost-sorted// packer uses to restore order inside a flushed batch sodiff --git a/packages/sie_server_sidecar/src/scheduler/lane.rs b/packages/sie_server_sidecar/src/scheduler/lane.rsnew file mode 100644index 000000000..1513193ac--- /dev/null+++ b/packages/sie_server_sidecar/src/scheduler/lane.rs@@ -0,0 +1,586 @@+//! [`Lane`]: when a model's pending work is handed to its engine.+//!+//! A [`BatchFormer`](super::BatchFormer) decides *what* goes into a batch.+//! A lane decides *when* the next batch leaves, for an engine that runs+//! one batch at a time. The engine is the scarce thing: a batch sent+//! while another is still with it only waits at the engine's lock, with+//! its membership frozen, and the requests that arrive a moment later+//! start a batch of their own behind it. Two groups then take turns and+//! every request waits for the other group's forward.+//!+//! The rule:+//!+//! 1. **Idle lane, send at once.** Nothing is with the engine and no batch+//! has just come back: a request leaves immediately with everything+//! else pending. A lone request never waits a window.+//! 2. **Busy lane, hold.** While a batch is with the engine, arrivals+//! stay in the queue where later arrivals can join them. Two things go+//! ahead into a free pipeline slot instead: the next batch if it is+//! already full (a cap reached, or no room under the cost cap for+//! another item like its largest), since holding it cannot improve it,+//! and the rest of a+//! request whose first part is with the engine, since its caller is+//! waiting on that part and has nobody to come back with. "Next" is the+//! scheduler's first-come-first-served pick across its queues: a full+//! batch on a younger queue does not overtake an older queue's held+//! one, which would then wait a forward longer for it.+//! 3. **On a return, gather once.** The callers just answered are the+//! ones most likely to come straight back. The lane waits for as many+//! arrivals as the returned batch answered, then sends everything+//! pending as one batch. It stops waiting when nothing has arrived for+//! the coalesce window, and in any case after half the returned+//! batch's round trip or the batch wait, whichever is shorter. A batch+//! that answered nobody (the first part of a request a cap cut) has no+//! caller to wait for.+//! 4. **Skip the gather where it does not pay.** The lane scores whether+//! returns are followed by that many arrivals inside the window. A+//! closed loop of callers scores high; arrivals at random times score+//! low, and then a return is followed by an immediate send. The score+//! keeps updating either way, so the lane notices when callers start+//! coming back.+//!+//! Everything here is synchronous and takes the current time as an+//! argument, so the rule is tested without a clock or a runtime. The+//! async plumbing is [`Scheduler::next_dispatch`](super::Scheduler).++use std::time::{Duration, Instant};++use super::batch_former::FlushReason;++/// Share of a returned batch's round trip the lane may spend gathering.+/// Half a forward is the most a caller should wait for company: past+/// that, two forwards one after another beat one late forward.+const GATHER_ROUND_TRIP_SHARE: f64 = 0.5;++/// A gather window shorter than this is not worth a timer.+const MIN_GATHER: Duration = Duration::from_micros(200);++/// Weight of the newest observation in the echo score.+const ECHO_SCORE_WEIGHT: f64 = 0.25;++/// The lane gathers while the echo score is at or above this.+const ECHO_SCORE_GATHER_AT: f64 = 0.5;++/// What the lane says about the pending work right now.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum Verdict {+ /// Send the next batch now, for this reason.+ Send(FlushReason),+ /// Nothing to do before this instant unless something arrives or a+ /// batch returns.+ WaitUntil(Instant),+ /// Wait for a batch to return (or for the pending work to fill up).+ Hold,+}++/// Arrivals expected after a returned batch, and the time they have.+#[derive(Debug, Clone, Copy)]+struct EchoWatch {+ /// No waiting past this instant, whatever arrives.+ latest: Instant,+ /// Waiting also ends when nothing has arrived for this long.+ quiet: Duration,+ /// The return, or the last arrival since.+ last_event: Instant,+ needed: usize,+ seen: usize,+}++impl EchoWatch {+ /// When the gather ends unless another request arrives first.+ fn deadline(&self) -> Instant {+ // A coalesce window too long to add to an instant never ends the+ // gather by itself; `latest` still does.+ self.last_event+ .checked_add(self.quiet)+ .map_or(self.latest, |quiet_end| self.latest.min(quiet_end))+ }+}++/// Dispatch state of one model's lane. One per+/// [`Scheduler`](super::Scheduler), shared by all its `(op, lora)` queues+/// because they share the engine.+#[derive(Debug)]+pub(crate) struct Lane {+ /// Batches handed to the engine and not yet returned.+ in_flight: usize,+ /// Open after a return until its arrivals came back or its window+ /// closed.+ watch: Option<EchoWatch>,+ /// Running share of returns whose callers came straight back.+ echo_score: f64,+ /// The pending work has waited in a gather since the last send.+ gathered: bool,+ /// The last batch sent left part of one of its requests in the queue.+ continues: bool,+}++impl Default for Lane {+ fn default() -> Self {+ Self {+ in_flight: 0,+ watch: None,+ // Start by gathering: a closed loop gains from its first+ // return, and callers that do not come back turn it off within+ // three returns.+ echo_score: 1.0,+ gathered: false,+ continues: false,+ }+ }+}++impl Lane {+ /// `requests` requests arrived.+ pub(crate) fn on_arrival(&mut self, now: Instant, requests: usize) {+ let Some(watch) = self.watch.as_mut() else {+ return;+ };+ if now >= watch.deadline() {+ self.settle_watch(now);+ return;+ }+ watch.seen += requests;+ watch.last_event = now;+ if watch.seen >= watch.needed {+ self.watch = None;+ self.record_echo(true);+ }+ }++ /// A batch was handed to the engine. `leaves_remainder` says a cap cut+ /// one of its requests and the rest of that request is still pending.+ pub(crate) fn on_dispatch(&mut self, leaves_remainder: bool) {+ self.in_flight += 1;+ self.gathered = false;+ self.continues = leaves_remainder;+ }++ /// A batch that answered `answered` requests came back after+ /// `round_trip`. `quiet` is the coalesce window and `longest` the batch+ /// wait: the gather ends when nothing has arrived for `quiet`, and no+ /// later than `longest` or half the round trip after the return.+ pub(crate) fn on_return(+ &mut self,+ now: Instant,+ answered: usize,+ round_trip: Duration,+ quiet: Duration,+ longest: Duration,+ ) {+ self.in_flight = self.in_flight.saturating_sub(1);+ if self.in_flight > 0 {+ // Still busy: the batch that empties the lane opens the watch.+ return;+ }+ // A watch left open by an earlier return is over either way.+ self.close_watch();+ let total = longest.min(round_trip.mul_f64(GATHER_ROUND_TRIP_SHARE));+ if answered == 0 || quiet.min(total) < MIN_GATHER {+ return;+ }+ self.watch = Some(EchoWatch {+ latest: now + total,+ quiet,+ last_event: now,+ needed: answered,+ seen: 0,+ });+ }++ /// What to do with the pending work. `full` is the cap it has already+ /// reached, if any. The caller holds a free pipeline slot.+ pub(crate) fn verdict(&mut self, now: Instant, full: Option<FlushReason>) -> Verdict {+ if let Some(reason) = full {+ return Verdict::Send(reason);+ }+ if self.in_flight > 0 {+ // The rest of a request that is partly with the engine follows+ // it at once; anything else waits for the return.+ return if self.continues {+ Verdict::Send(FlushReason::Drain)+ } else {+ Verdict::Hold+ };+ }+ self.settle_watch(now);+ match self.watch {+ Some(watch) if self.gathers() => {+ self.gathered = true;+ Verdict::WaitUntil(watch.deadline())+ }+ // A batch just returned and its callers have not been coming+ // back: send what is pending behind it.+ Some(_) => Verdict::Send(FlushReason::Drain),+ None if self.gathered => Verdict::Send(FlushReason::Coalesce),+ None => Verdict::Send(FlushReason::IdleBypass),+ }+ }++ /// Nothing is with the engine and no return is being watched.+ pub(crate) fn is_idle(&mut self, now: Instant) -> bool {+ self.settle_watch(now);+ self.in_flight == 0 && self.watch.is_none()+ }++ /// Batches with the engine.+ #[cfg(test)]+ pub(crate) fn in_flight(&self) -> usize {+ self.in_flight+ }++ /// Whether a return is currently followed by a gather.+ pub(crate) fn gathers(&self) -> bool {+ self.echo_score >= ECHO_SCORE_GATHER_AT+ }++ /// Close a watch whose window has passed, as a miss.+ fn settle_watch(&mut self, now: Instant) {+ if self.watch.is_some_and(|watch| now >= watch.deadline()) {+ self.close_watch();+ }+ }++ /// Close the open watch, if any, scoring what it saw.+ fn close_watch(&mut self) {+ if let Some(watch) = self.watch.take() {+ self.record_echo(watch.seen >= watch.needed);+ }+ }++ fn record_echo(&mut self, came_back: bool) {+ let observation = if came_back { 1.0 } else { 0.0 };+ self.echo_score += ECHO_SCORE_WEIGHT * (observation - self.echo_score);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const COALESCE: Duration = Duration::from_millis(5);+ const LONGEST: Duration = Duration::from_millis(15);++ fn ms(value: u64) -> Duration {+ Duration::from_millis(value)+ }++ fn us(value: u64) -> Duration {+ Duration::from_micros(value)+ }++ /// One closed-loop cycle with work pending: the batch returns at `t`,+ /// the loop asks for a verdict, then `callers` requests come back+ /// within a millisecond. Returns the verdict after the last arrival.+ fn return_then_echo(lane: &mut Lane, t: Instant, answered: usize, callers: usize) -> Verdict {+ lane.on_return(t, answered, ms(6), COALESCE, LONGEST);+ let _ = lane.verdict(t, None);+ for caller in 0..callers {+ lane.on_arrival(t + us(100 * (caller as u64 + 1)), 1);+ }+ lane.verdict(t + us(100 * callers as u64 + 1), None)+ }++ #[test]+ fn a_request_on_an_idle_lane_is_sent_at_once() {+ let mut lane = Lane::default();+ let now = Instant::now();+ lane.on_arrival(now, 1);+ assert_eq!(+ lane.verdict(now, None),+ Verdict::Send(FlushReason::IdleBypass)+ );+ }++ #[test]+ fn a_request_arriving_while_a_batch_is_out_is_held() {+ let mut lane = Lane::default();+ let now = Instant::now();+ lane.on_dispatch(false);+ lane.on_arrival(now + ms(1), 1);+ assert_eq!(lane.verdict(now + ms(1), None), Verdict::Hold);+ // However long it has waited: the engine is the limit, not a timer.+ assert_eq!(lane.verdict(now + ms(500), None), Verdict::Hold);+ }++ #[test]+ fn a_full_batch_goes_ahead_while_a_batch_is_out() {+ let mut lane = Lane::default();+ lane.on_dispatch(false);+ assert_eq!(+ lane.verdict(Instant::now(), Some(FlushReason::CountCap)),+ Verdict::Send(FlushReason::CountCap)+ );+ }++ #[test]+ fn after_a_return_the_lane_waits_for_the_callers_it_answered() {+ let mut lane = Lane::default();+ let t = Instant::now();+ lane.on_dispatch(false);+ // Seven requests arrived during the forward and are pending.+ lane.on_arrival(t, 7);+ lane.on_return(t + ms(6), 1, ms(6), COALESCE, LONGEST);+ // The one caller just answered has not come back yet: gather, for+ // at most half the round trip.+ assert_eq!(+ lane.verdict(t + ms(6), None),+ Verdict::WaitUntil(t + ms(6) + ms(3))+ );+ // It comes back: all eight leave together, with no timer involved.+ lane.on_arrival(t + ms(6) + us(400), 1);+ assert_eq!(+ lane.verdict(t + ms(6) + us(400), None),+ Verdict::Send(FlushReason::Coalesce)+ );+ }++ #[test]+ fn a_lone_caller_in_a_closed_loop_never_waits_the_window() {+ let mut lane = Lane::default();+ let mut t = Instant::now();+ for _ in 0..20 {+ lane.on_dispatch(false);+ t += ms(6);+ lane.on_return(t, 1, ms(6), COALESCE, LONGEST);+ // Nothing is pending until the caller is back, and its arrival+ // is the one the lane was waiting for.+ t += us(300);+ lane.on_arrival(t, 1);+ assert_eq!(+ lane.verdict(t, None),+ Verdict::Send(FlushReason::IdleBypass)+ );+ }+ }++ #[test]+ fn the_gather_ends_when_nothing_has_arrived_for_the_coalesce_window() {+ let mut lane = Lane::default();+ let t = Instant::now();+ lane.on_dispatch(false);+ lane.on_arrival(t, 2);+ lane.on_return(t + ms(40), 8, ms(40), COALESCE, LONGEST);+ // Nobody back yet: one coalesce window from the return.+ assert_eq!(+ lane.verdict(t + ms(40), None),+ Verdict::WaitUntil(t + ms(45))+ );+ // Three of the eight come back: the window restarts from them.+ lane.on_arrival(t + ms(41), 3);+ assert_eq!(+ lane.verdict(t + ms(41), None),+ Verdict::WaitUntil(t + ms(46))+ );+ assert_eq!(+ lane.verdict(t + ms(46), None),+ Verdict::Send(FlushReason::Coalesce)+ );+ }++ #[test]+ fn a_slow_trickle_of_callers_is_waited_for_no_longer_than_the_batch_wait() {+ // 64 callers answered by a 40 ms batch; one comes back every 2 ms.+ // Each arrival restarts the coalesce window, but the gather never+ // outlasts the 15 ms batch wait (half the round trip would be 20).+ let mut lane = Lane::default();+ let t = Instant::now();+ lane.on_dispatch(false);+ lane.on_return(t, 64, ms(40), COALESCE, LONGEST);+ let mut waited_until = t;+ for step in 1..=7u64 {+ lane.on_arrival(t + ms(2 * step), 1);+ match lane.verdict(t + ms(2 * step), None) {+ Verdict::WaitUntil(deadline) => waited_until = deadline,+ verdict => panic!("still gathering at {} ms, got {verdict:?}", 2 * step),+ }+ }+ assert_eq!(waited_until, t + ms(15));+ assert_eq!(+ lane.verdict(t + ms(15), None),+ Verdict::Send(FlushReason::Coalesce)+ );++ // And never longer than half the round trip, for a short forward.+ let mut lane = Lane::default();+ lane.on_dispatch(false);+ lane.on_return(t, 8, ms(6), COALESCE, LONGEST);+ lane.on_arrival(t + ms(2), 1);+ assert_eq!(lane.verdict(t + ms(2), None), Verdict::WaitUntil(t + ms(3)));+ }++ #[test]+ fn random_arrivals_turn_the_gather_off_within_three_returns() {+ let mut lane = Lane::default();+ let mut t = Instant::now();+ let mut waited = 0;+ for _ in 0..6 {+ lane.on_dispatch(false);+ // A request arrives during the forward, later than the window+ // of the return before it.+ lane.on_arrival(t + ms(4), 1);+ t += ms(6);+ lane.on_return(t, 1, ms(6), COALESCE, LONGEST);+ match lane.verdict(t, None) {+ Verdict::WaitUntil(deadline) => {+ waited += 1;+ // Nobody comes back inside the window.+ t = deadline + us(1);+ assert_eq!(lane.verdict(t, None), Verdict::Send(FlushReason::Coalesce));+ }+ verdict => assert_eq!(verdict, Verdict::Send(FlushReason::Drain)),+ }+ }+ assert_eq!(+ waited, 3,+ "three returns with no caller back end the gather"+ );+ assert!(!lane.gathers());+ }++ #[test]+ fn callers_that_start_coming_back_turn_the_gather_on_again() {+ let mut lane = Lane::default();+ let mut t = Instant::now();+ // Drive the score down with returns nobody follows.+ for _ in 0..3 {+ lane.on_dispatch(false);+ t += ms(6);+ lane.on_return(t, 4, ms(6), COALESCE, LONGEST);+ t += ms(20);+ assert!(lane.is_idle(t));+ }+ assert!(!lane.gathers());++ // A closed loop starts. The lane is not gathering, so the first+ // return sends at once, but the arrivals behind it are still+ // scored, and the next return gathers.+ lane.on_dispatch(false);+ t += ms(6);+ lane.on_arrival(t - ms(1), 3);+ lane.on_return(t, 1, ms(6), COALESCE, LONGEST);+ assert_eq!(lane.verdict(t, None), Verdict::Send(FlushReason::Drain));+ lane.on_dispatch(false);+ lane.on_arrival(t + us(300), 1);+ assert!(+ lane.gathers(),+ "one caller back inside the window is enough"+ );++ t += ms(6);+ assert_eq!(+ return_then_echo(&mut lane, t, 3, 3),+ Verdict::Send(FlushReason::Coalesce)+ );+ }++ #[test]+ fn a_closed_loop_keeps_one_group() {+ // Eight callers. The first leaves alone, as it must; from the+ // first return on, every batch holds all eight.+ let mut lane = Lane::default();+ let mut t = Instant::now();+ lane.on_arrival(t, 1);+ assert_eq!(+ lane.verdict(t, None),+ Verdict::Send(FlushReason::IdleBypass)+ );+ lane.on_dispatch(false);+ lane.on_arrival(t + us(200), 7);+ assert_eq!(lane.verdict(t + us(200), None), Verdict::Hold);++ t += ms(6);+ assert_eq!(+ return_then_echo(&mut lane, t, 1, 1),+ Verdict::Send(FlushReason::Coalesce)+ );+ for _ in 0..10 {+ lane.on_dispatch(false);+ t += ms(7);+ lane.on_return(t, 8, ms(7), COALESCE, LONGEST);+ // Seven of eight back: still waiting for the eighth.+ for caller in 0..7u64 {+ lane.on_arrival(t + us(100 * (caller + 1)), 1);+ }+ assert!(matches!(+ lane.verdict(t + us(800), None),+ Verdict::WaitUntil(_)+ ));+ lane.on_arrival(t + us(900), 1);+ assert_eq!(+ lane.verdict(t + us(900), None),+ Verdict::Send(FlushReason::Coalesce)+ );+ }+ }++ #[test]+ fn a_zero_coalesce_window_turns_the_gather_off() {+ let mut lane = Lane::default();+ let t = Instant::now();+ lane.on_dispatch(false);+ lane.on_arrival(t, 3);+ lane.on_return(t + ms(6), 1, ms(6), Duration::ZERO, LONGEST);+ assert_eq!(+ lane.verdict(t + ms(6), None),+ Verdict::Send(FlushReason::IdleBypass)+ );+ }++ #[test]+ fn a_second_batch_out_keeps_the_lane_busy_until_it_returns() {+ let mut lane = Lane::default();+ let t = Instant::now();+ lane.on_dispatch(false);+ lane.on_dispatch(false);+ assert_eq!(lane.in_flight(), 2);+ lane.on_return(t + ms(6), 12, ms(6), COALESCE, LONGEST);+ lane.on_arrival(t + ms(6), 5);+ assert_eq!(lane.verdict(t + ms(6), None), Verdict::Hold);+ lane.on_return(t + ms(12), 12, ms(6), COALESCE, LONGEST);+ assert!(matches!(+ lane.verdict(t + ms(12), None),+ Verdict::WaitUntil(_)+ ));+ }++ #[test]+ fn the_rest_of_a_cut_request_follows_its_first_part_at_once() {+ let mut lane = Lane::default();+ let t = Instant::now();+ // The first part of a request the item cap cut is out.+ lane.on_dispatch(true);+ assert_eq!(lane.verdict(t, None), Verdict::Send(FlushReason::Drain));+ // The batch that takes the last of it ends that.+ lane.on_dispatch(false);+ lane.on_arrival(t + ms(1), 1);+ assert_eq!(lane.verdict(t + ms(1), None), Verdict::Hold);+ // The parts that answered nobody open no watch.+ lane.on_return(t + ms(6), 0, ms(6), COALESCE, LONGEST);+ lane.on_return(t + ms(9), 1, ms(9), COALESCE, LONGEST);+ assert!(matches!(+ lane.verdict(t + ms(9), None),+ Verdict::WaitUntil(_)+ ));+ }++ #[test]+ fn a_coalesce_window_beyond_any_instant_leaves_the_other_limits_in_charge() {+ let mut lane = Lane::default();+ let t = Instant::now();+ lane.on_dispatch(false);+ lane.on_arrival(t, 1);+ lane.on_return(t + ms(10), 4, ms(10), Duration::MAX, LONGEST);+ assert_eq!(+ lane.verdict(t + ms(10), None),+ Verdict::WaitUntil(t + ms(15))+ );+ }++ #[test]+ fn an_unmatched_return_does_not_underflow() {+ let mut lane = Lane::default();+ lane.on_return(Instant::now(), 1, ms(6), COALESCE, LONGEST);+ assert_eq!(lane.in_flight(), 0);+ }+}diff --git a/packages/sie_server_sidecar/src/scheduler/mod.rs b/packages/sie_server_sidecar/src/scheduler/mod.rsindex 8c6545c27..096e94250 100644--- a/packages/sie_server_sidecar/src/scheduler/mod.rs+++ b/packages/sie_server_sidecar/src/scheduler/mod.rs@@ -25,6 +25,11 @@//! "does this active model run under the Rust scheduler" is answered by//! which worker pool handles the model, not by a per-worker env var.//!+//! When a formed batch leaves is the lane's rule ([`lane`]): at once on an+//! idle lane, held while a batch is with the engine, and together after+//! it returns. Python has no counterpart; its batcher runs in the engine+//! process and sees the forward end.+//!//! Invariants to preserve (same as the Python code; any deviation is a//! production bug, not a design call)://!@@ -42,13 +47,14 @@ pub mod batch_config;pub mod batch_former;pub mod engine;pub mod item;+pub(crate) mod lane;pub mod registry;pub mod trackers;pub use adaptive::{AdaptiveBatchController, AdaptiveBatchControllerBuilder, AdaptiveBatchState};pub use batch_config::BatchConfig;pub use batch_former::{BatchFormer, FlushReason, FormattedBatch, HasCost, PendingRequest};-pub use engine::{LoraKey, Op, RecordCompletionOutcome, Scheduler, SchedulerBuilder};+pub use engine::{Dispatch, LoraKey, Op, RecordCompletionOutcome, Scheduler, SchedulerBuilder};pub use item::{lora_from_options, SchedulerItem, SchedulerMeta};pub use registry::SchedulerRegistry;pub use trackers::BatchEfficiencyTracker;