Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix(sidecar): bound costly request waiting (#708)

svonava8ec90e1eb487
diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rs
index 4a4d28841..4f902fffb 100644
--- a/packages/sie_server_sidecar/src/dispatcher.rs
+++ b/packages/sie_server_sidecar/src/dispatcher.rs
@@ -8977,6 +8977,265 @@ mod tests {
drop(next_permit);
}
+ /// Holds actual RunBatch calls until the test completes them. The real
+ /// scheduler/drain/settlement paths decide which requests reach it.
+ struct HeldScoreBackend {
+ started: tokio::sync::mpsc::UnboundedSender<(String, tokio::sync::oneshot::Sender<()>)>,
+ }
+
+ #[async_trait::async_trait]
+ impl crate::backend::InferenceBackend for HeldScoreBackend {
+ fn name(&self) -> &'static str {
+ "held-score"
+ }
+
+ fn supports(&self, _model_id: &str) -> bool {
+ true
+ }
+
+ async fn ensure_model_ready(
+ &self,
+ _model_id: &str,
+ ) -> Result<crate::ipc_types::EnsureModelReadyResponse, BackendError> {
+ Ok(crate::ipc_types::EnsureModelReadyResponse {
+ state: ReadinessState::Ready,
+ batch_budget: None,
+ descriptor: None,
+ })
+ }
+
+ async fn process_encode_batch(
+ &self,
+ _req: ProcessEncodeBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ Err(BackendError::UnsupportedModel("encode".into()))
+ }
+
+ async fn process_score_batch(
+ &self,
+ _req: ProcessScoreBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ Err(BackendError::UnsupportedModel("score".into()))
+ }
+
+ async fn process_extract_batch(
+ &self,
+ _req: ProcessExtractBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ Err(BackendError::UnsupportedModel("extract".into()))
+ }
+
+ async fn run_batch(&self, req: RunBatchRequest) -> Result<BatchOutcome, BackendError> {
+ // Every short item costs 9 against a cap of 16, so these batches
+ // must be singletons even with an eight-item count limit.
+ assert_eq!(req.items.len(), 1);
+ let item = &req.items[0];
+ assert_eq!(item.op, "score");
+ let (release, held) = tokio::sync::oneshot::channel();
+ self.started
+ .send((item.request_id.clone(), release))
+ .unwrap();
+ held.await.expect("the test releases every backend call");
+ let mut result = outcome(
+ &item.request_id,
+ item.item_index,
+ Disposition::PublishAndAck,
+ Some(1.0),
+ None,
+ );
+ result.result_msgpack = rmp_serde::to_vec_named(&item.request_id).unwrap();
+ Ok(BatchOutcome {
+ outcomes: vec![result],
+ batched_f16_multivectors: Vec::new(),
+ })
+ }
+ }
+
+ fn score_client_work(
+ slot: usize,
+ cost: usize,
+ tx: &tokio::sync::mpsc::UnboundedSender<crate::delivery::LocalDeliveryEvent>,
+ ) -> (WorkItem, Delivery) {
+ let mut work = wi(&format!("score-{slot}"), 0, "reranker", "score");
+ work.query_item = Some(text_item("q"));
+ work.score_items = Some(vec![text_item(&"x".repeat(cost - 1))]);
+ (
+ work,
+ Delivery::Local(LocalDelivery::new(slot, 0, tx.clone())),
+ )
+ }
+
+ #[tokio::test]
+ async fn aged_score_requests_progress_under_closed_loop_c8_replenishment() {
+ // Both an in-cap large request and a single oversize request must
+ // progress. Eight clients each submit their next request only after
+ // the previous one settles; the seven cheap clients replenish demand.
+ for large_cost in [12, 24] {
+ let (started_tx, mut started_rx) = tokio::sync::mpsc::unbounded_channel();
+ let dispatcher = dispatcher_with_backend(Arc::new(HeldScoreBackend {
+ started: started_tx,
+ }));
+ // Pin the production pipeline without changing process-global env.
+ dispatcher
+ .pipelines
+ .lock()
+ .unwrap()
+ .insert("reranker".into(), Arc::new(ModelPipeline::new(2)));
+ let controller = crate::scheduler::AdaptiveBatchController::builder()
+ .target_p50_ms(Some(100.0))
+ .min_wait_ms(20.0)
+ .max_wait_ms(20.0)
+ .initial_wait_ms(20.0)
+ .min_batch_cost(16)
+ .max_batch_cost(16)
+ .initial_batch_cost(16)
+ .starvation_recovery_enabled(false)
+ .build();
+ let scheduler = Arc::new(
+ ProductionScheduler::builder()
+ .config(BatchConfig {
+ max_batch_cost: 16,
+ max_batch_requests: 8,
+ max_batch_wait_ms: 20.0,
+ ..BatchConfig::default()
+ })
+ .controller(controller)
+ .build(),
+ );
+ let shutdown = Arc::new(Shutdown::new());
+ let drain = tokio::spawn(scheduler_drain_loop(
+ "reranker".into(),
+ dispatcher.clone(),
+ scheduler.clone(),
+ shutdown.clone(),
+ ));
+ let streams: Vec<_> = (0..8)
+ .map(|_| tokio::sync::mpsc::unbounded_channel())
+ .collect();
+
+ // Occupy the first slot before atomically queuing the large item
+ // and six cheap ones. A second dispatch can overtake it while
+ // unaged, then both pipeline slots remain held during aging.
+ dispatcher
+ .enqueue_score_into_scheduler(
+ "reranker",
+ &scheduler,
+ vec![score_client_work(0, 9, &streams[0].0)],
+ )
+ .await;
+ let first = tokio::time::timeout(Duration::from_secs(2), started_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(first.0, "score-0");
+ dispatcher
+ .enqueue_score_into_scheduler(
+ "reranker",
+ &scheduler,
+ (1..8)
+ .map(|client| {
+ let cost = if client == 1 { large_cost } else { 9 };
+ score_client_work(client, cost, &streams[client].0)
+ })
+ .collect(),
+ )
+ .await;
+ let second = tokio::time::timeout(Duration::from_secs(2), started_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+
+ let mut clients = tokio::task::JoinSet::new();
+ for (client, (tx, mut rx)) in streams.into_iter().enumerate() {
+ let dispatcher = dispatcher.clone();
+ let scheduler = scheduler.clone();
+ clients.spawn(async move {
+ let mut settled = Vec::new();
+ for round in 0..8 {
+ let expected_slot = round * 8 + client;
+ let event = tokio::time::timeout(Duration::from_secs(2), rx.recv())
+ .await
+ .expect("every submitted request must settle")
+ .unwrap();
+ let crate::delivery::LocalDeliveryEvent::Result { slot, result } = event
+ else {
+ panic!("fake backend must not cause redelivery");
+ };
+ assert_eq!(slot, expected_slot, "once-only settlement in client order");
+ assert!(result.success);
+ assert_eq!(result.request_id, format!("score-{slot}"));
+ assert_eq!(
+ rmp_serde::from_slice::<String>(&result.result_msgpack).unwrap(),
+ result.request_id,
+ "backend output stays paired with its request"
+ );
+ settled.push(slot);
+ if round < 7 {
+ dispatcher
+ .enqueue_score_into_scheduler(
+ "reranker",
+ &scheduler,
+ vec![score_client_work(expected_slot + 8, 9, &tx)],
+ )
+ .await;
+ }
+ }
+ (settled, rx)
+ });
+ }
+
+ // This is real wall time: BatchFormer uses std::Instant. Nothing
+ // can be extracted while both actual pipeline permits are held.
+ tokio::time::sleep(Duration::from_millis(30)).await;
+ let mut dispatched = vec![first.0, second.0];
+ first.1.send(()).unwrap();
+ let third = tokio::time::timeout(Duration::from_secs(2), started_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ if dispatched[1] != "score-1" {
+ assert_eq!(third.0, "score-1", "aged request gets the next open slot");
+ }
+ dispatched.push(third.0);
+ second.1.send(()).unwrap();
+ third.1.send(()).unwrap();
+ for _ in 3..64 {
+ let (request, release) =
+ tokio::time::timeout(Duration::from_secs(2), started_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ dispatched.push(request);
+ release.send(()).unwrap();
+ }
+
+ let mut settled = Vec::new();
+ let mut receivers = Vec::new();
+ while let Some(client) = clients.join_next().await {
+ let (slots, rx) = client.unwrap();
+ settled.extend(slots);
+ receivers.push(rx);
+ }
+ settled.sort_unstable();
+ assert_eq!(settled, (0..64).collect::<Vec<_>>());
+ dispatched.sort();
+ let mut expected: Vec<_> = (0..64).map(|slot| format!("score-{slot}")).collect();
+ expected.sort();
+ assert_eq!(dispatched, expected, "every request runs exactly once");
+ assert_eq!(scheduler.total_pending_count().await, 0);
+ shutdown.fire();
+ tokio::time::timeout(Duration::from_secs(2), drain)
+ .await
+ .expect("owned drain loop exits after all work settles")
+ .unwrap();
+ assert!(started_rx.try_recv().is_err());
+ for mut rx in receivers {
+ assert!(rx.try_recv().is_err(), "no duplicate terminal result");
+ }
+ assert_eq!(dispatcher.runtime_state.inflight_batches.get(), 0);
+ }
+ }
+
#[tokio::test]
async fn shutdown_cancels_pipeline_wait_without_extracting_pending_tail() {
let scheduler = Scheduler::<PipelineTestItem, usize>::new(BatchConfig::default());
diff --git a/packages/sie_server_sidecar/src/scheduler/batch_former.rs b/packages/sie_server_sidecar/src/scheduler/batch_former.rs
index 7192145bc..529265a1e 100644
--- a/packages/sie_server_sidecar/src/scheduler/batch_former.rs
+++ b/packages/sie_server_sidecar/src/scheduler/batch_former.rs
@@ -1,8 +1,8 @@
//! [`BatchFormer`] — async pending queue + flush loop.
//!
//! Ported from `sie_server/core/batcher.py::BatchFormer`. The port preserves
-//! its batching/packing contract, with one intentional Rust queue-path
-//! divergence called out below:
+//! its batching/packing contract, with Rust queue-path differences for
+//! bounded waiting and timer refresh called out below:
//!
//! 1. **Flush triggers**: cost cap, count cap, `max_batch_wait_ms`
//! timeout since the *first* item, or the coalesce window
@@ -10,10 +10,13 @@
//! 2. **Oversize item**: a single item whose cost already exceeds
//! `max_batch_cost` still flushes (alone) so it can't starve
//! forever.
-//! 3. **Cost-sorted sub-batch**: `_pending` is sorted by `cost`
-//! ascending before each extract; packing is greedy under the cost
-//! and count caps. Remaining items stay in the queue for the next
-//! extract, preserving FIFO-within-cost-bucket ordering.
+//! 3. **Bounded cost-sorted packing**: before each extract, the oldest
+//! request that has reached `max_batch_wait_ms` gets the first packing
+//! opportunity. All other requests are stably sorted by cost, then packed
+//! greedily under the cost and count caps. This prevents replenishing
+//! cheap requests from indefinitely overtaking an aged expensive one.
+//! Progress requires a downstream dispatch slot; the wait window is not
+//! an end-to-end latency guarantee.
//! 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.
@@ -22,8 +25,9 @@
//! extract and clears them only when empty. Rust re-anchors them to the actual
//! remainder because the sidecar's cross-key FCFS selector reads that state:
//! retaining a removed request's timestamp can repeatedly prioritize a hot key
-//! and can make a newer tail skip its own coalescing window. Packing, caps, and
-//! flush triggers otherwise follow the Python test contract. The async
+//! and can make a newer tail skip its own coalescing window. Python's packing
+//! remains strictly cost-sorted; Rust promotes one aged request per extract.
+//! Caps and flush triggers otherwise follow the Python test contract. The async
//! primitives differ as expected (`tokio::sync` rather than asyncio).
use std::marker::PhantomData;
@@ -379,9 +383,10 @@ impl<I: HasCost, T> BatchFormer<I, T> {
///
/// The scheduler drain loop uses this to bound one continuous-batching
/// wave to the backlog count observed when its first continuation slot
- /// opens. Because packing cost-sorts all currently pending items, a newer
- /// cheap item can participate ahead of an older expensive item; the count
- /// budget bounds wave size but does not identify an exact request cohort.
+ /// opens. A newer cheap item can participate ahead of an unaged expensive
+ /// item; the oldest request gets the first packing opportunity once its
+ /// wait window expires. The count budget bounds wave size but does not
+ /// identify an exact request cohort.
pub async fn try_drain_up_to(&self, max_items: usize) -> Option<FormattedBatch<I, T>> {
if max_items == 0 {
return None;
@@ -540,11 +545,29 @@ fn extract_batch_up_to<I: HasCost, T>(
max_items: usize,
) -> FormattedBatch<I, T> {
debug_assert!(max_items > 0, "zero-item drains are rejected by the caller");
+ // A timeout must give the waiting request an extraction opportunity,
+ // even while cheaper arrivals keep the queue full. Select before sorting
+ // so tied arrival timestamps retain their pending order. Removing only
+ // the oldest aged request keeps the remaining cost buckets stable.
+ let oldest_aged = inner
+ .pending
+ .iter()
+ .enumerate()
+ .min_by_key(|(_, request)| request.arrival_time)
+ .filter(|(_, request)| {
+ request.arrival_time.elapsed().as_secs_f64() * 1000.0 >= inner.config.max_batch_wait_ms
+ })
+ .map(|(index, _)| index);
+ let promoted = oldest_aged.map(|index| inner.pending.remove(index));
+
// Cost-sort pending before slicing — keeps each sub-batch's
// items close in length, minimising padding waste on the adapter
// side. Stable sort preserves FIFO order within equal-cost items
// (matches Python's stable `list.sort`).
inner.pending.sort_by_key(|r| r.item.cost());
+ if let Some(request) = promoted {
+ inner.pending.insert(0, request);
+ }
let max_cost = effective_max_cost(inner);
let max_requests = inner.config.max_batch_requests;
@@ -656,6 +679,151 @@ mod tests {
}
}
+ // 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>(
+ former: &BatchFormer<I, usize>,
+ ages_ms: &[(usize, u64)],
+ ) {
+ let now = Instant::now();
+ let mut guard = former.inner.lock().await;
+ for request in &mut guard.pending {
+ let age_ms = ages_ms
+ .iter()
+ .find(|(metadata, _)| *metadata == request.metadata)
+ .expect("every pending request has an explicit age")
+ .1;
+ request.arrival_time = now - Duration::from_millis(age_ms);
+ }
+ guard.first_request_time = guard.pending.iter().map(|r| r.arrival_time).min();
+ guard.last_submit_time = guard.pending.iter().map(|r| r.arrival_time).max();
+ former.refresh_fcfs_head(&guard);
+ }
+
+ #[tokio::test]
+ async fn aged_requests_progress_in_arrival_order_under_replenishment() {
+ let former = BatchFormer::<StubItem, usize>::new(BatchConfig {
+ max_batch_cost: 10,
+ max_batch_requests: 8,
+ max_batch_wait_ms: 20.0,
+ ..BatchConfig::default()
+ });
+ // Pending order and cost order both differ from actual arrival order.
+ for id in [2, 0, 1] {
+ former.submit(StubItem::with_idx(10, id), id).await;
+ }
+ former.submit(StubItem::with_idx(1, 3), 3).await;
+ set_request_ages(&former, &[(2, 100), (0, 300), (1, 200), (3, 0)]).await;
+
+ for id in 0..3 {
+ let batch = former.try_drain_up_to(1).await.unwrap();
+ assert_eq!(batch.metadata, vec![id], "oldest aged request goes first");
+ assert_eq!(batch.items, vec![StubItem::with_idx(10, id)]);
+ assert_eq!(batch.total_cost, 10);
+ former.submit(StubItem::with_idx(1, id + 4), id + 4).await;
+ }
+ assert_eq!(former.pending_count().await, 4);
+ assert_eq!(former.pending_cost().await, 4);
+ let remainder = former.try_drain().await.unwrap();
+ assert_eq!(remainder.metadata, vec![3, 4, 5, 6]);
+ assert_eq!(former.pending_count().await, 0);
+ assert_eq!(former.pending_cost().await, 0);
+ assert_eq!(former.fcfs_head_ns(), 0);
+ }
+
+ #[tokio::test]
+ async fn aged_oversize_request_flushes_alone_among_smaller_requests() {
+ let former = BatchFormer::<StubItem, usize>::new(BatchConfig {
+ max_batch_cost: 10,
+ max_batch_requests: 8,
+ max_batch_wait_ms: 20.0,
+ ..BatchConfig::default()
+ });
+ former.submit(StubItem::with_idx(20, 0), 0).await;
+ former.submit(StubItem::with_idx(0, 1), 1).await;
+ former.submit(StubItem::with_idx(1, 2), 2).await;
+ set_request_ages(&former, &[(0, 100), (1, 0), (2, 0)]).await;
+ let remaining_first = former.inner.lock().await.pending[1].arrival_time;
+
+ let batch = former.try_get_batch().await.unwrap();
+ assert_eq!(batch.metadata, vec![0]);
+ assert_eq!(batch.items, vec![StubItem::with_idx(20, 0)]);
+ assert_eq!(batch.total_cost, 20);
+ assert_eq!(former.pending_count().await, 2);
+ assert_eq!(former.pending_cost().await, 1);
+ let guard = former.inner.lock().await;
+ assert_eq!(guard.first_request_time, Some(remaining_first));
+ assert_eq!(guard.last_submit_time, Some(remaining_first));
+ assert_ne!(former.fcfs_head_ns(), 0);
+ }
+
+ #[tokio::test]
+ async fn aged_promotion_preserves_hard_cost_and_updated_count_caps() {
+ let config = BatchConfig {
+ max_batch_cost: 1_000,
+ max_batch_requests: 8,
+ max_batch_wait_ms: 20.0,
+ ..BatchConfig::default()
+ };
+ let former = BatchFormer::<HardCapItem, usize>::new(config);
+ for (id, cost) in [4, 2, 2, 2].into_iter().enumerate() {
+ former.submit(HardCapItem { cost, cap: 7 }, id).await;
+ }
+ set_request_ages(&former, &[(0, 100), (1, 0), (2, 0), (3, 0)]).await;
+
+ let batch = former.try_drain_up_to(3).await.unwrap();
+ assert_eq!(batch.metadata, vec![0, 1]);
+ assert_eq!(
+ batch.total_cost, 6,
+ "promotion must still honor the hard cap"
+ );
+ assert_eq!(former.pending_cost().await, 4);
+ former
+ .update_config(BatchConfig {
+ max_batch_cost: 5,
+ max_batch_requests: 1,
+ ..config
+ })
+ .await;
+ let batch = former.try_drain_up_to(3).await.unwrap();
+ assert_eq!(batch.metadata, vec![2]);
+ assert_eq!(batch.total_cost, 2);
+ assert_eq!(former.pending_count().await, 1);
+ }
+
+ #[tokio::test]
+ async fn promotion_tracks_updated_wait_threshold() {
+ let config = BatchConfig {
+ max_batch_cost: 10,
+ max_batch_requests: 8,
+ max_batch_wait_ms: 1_000_000.0,
+ ..BatchConfig::default()
+ };
+ let former = BatchFormer::<StubItem, usize>::new(config);
+ former.submit(StubItem::with_idx(10, 0), 0).await;
+ former.submit(StubItem::with_idx(1, 1), 1).await;
+ set_request_ages(&former, &[(0, 100), (1, 0)]).await;
+ let first = former.try_drain_up_to(1).await.unwrap();
+ assert_eq!(
+ first.metadata,
+ vec![1],
+ "unaged requests remain cost-sorted"
+ );
+ former.submit(StubItem::with_idx(1, 2), 2).await;
+ former
+ .update_config(BatchConfig {
+ max_batch_wait_ms: 20.0,
+ ..config
+ })
+ .await;
+
+ let next = former.get_batch(true).await;
+ assert_eq!(next.metadata, vec![0]);
+ assert_eq!(next.total_cost, 10);
+ assert_eq!(former.pending_count().await, 1);
+ assert_eq!(former.pending_cost().await, 1);
+ }
+
#[tokio::test]
async fn submit_and_drain_roundtrip() {
let b = BatchFormer::<StubItem, u32>::new(BatchConfig::default());
@@ -827,6 +995,7 @@ mod tests {
let cfg = BatchConfig {
max_batch_cost: 1_000_000,
max_batch_requests: 64,
+ max_batch_wait_ms: 1_000_000.0,
..BatchConfig::default()
};
let b = BatchFormer::<StubItem, usize>::new(cfg);
@@ -834,10 +1003,16 @@ mod tests {
b.submit(StubItem::with_idx(50, 0), 0).await;
b.submit(StubItem::with_idx(10, 1), 1).await;
b.submit(StubItem::with_idx(30, 2), 2).await;
+ b.submit(StubItem::with_idx(10, 3), 3).await;
let batch = b.try_drain().await.unwrap();
let costs: Vec<u64> = batch.items.iter().map(|i| i.cost()).collect();
- assert_eq!(costs, vec![10, 30, 50], "must be sorted ascending");
+ assert_eq!(costs, vec![10, 10, 30, 50], "must be sorted ascending");
+ assert_eq!(
+ batch.metadata,
+ vec![1, 3, 2, 0],
+ "equal-cost FIFO is stable"
+ );
}
#[tokio::test]