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): send engine-batched extract items one per RunBatch, as wide as the adapter dispatches (#685)
svonava4d13128adaa8
diff --git a/packages/sie_server/src/sie_server/core/worker/model_worker.py b/packages/sie_server/src/sie_server/core/worker/model_worker.pyindex 09bdc8270..66ff0bbbc 100644--- a/packages/sie_server/src/sie_server/core/worker/model_worker.py+++ b/packages/sie_server/src/sie_server/core/worker/model_worker.py@@ -316,6 +316,11 @@ class ModelWorker:"""Return the worker configuration."""return self._config+ @property+ def dispatch_width(self) -> int:+ """Return how many batches this worker runs through its adapter at once."""+ return self._dispatch_width+@propertydef stats(self) -> WorkerStats:"""Return current worker statistics."""diff --git a/packages/sie_server/src/sie_server/ipc_types.py b/packages/sie_server/src/sie_server/ipc_types.pyindex db26cae67..14ab4c8e4 100644--- a/packages/sie_server/src/sie_server/ipc_types.py+++ b/packages/sie_server/src/sie_server/ipc_types.py@@ -162,6 +162,13 @@ class ModelDescriptor(msgspec.Struct):# contract as ``default_query_template`` but selected when# ``is_query=False``.default_doc_template: str | None = None+ # Batches the worker runs through this model's adapter at once (the+ # adapter's ``max_concurrent_dispatch()`` as the worker honours it).+ # Above 1 the engine behind the adapter batches continuously (SGLang):+ # the sidecar then sends each extract item in a ``RunBatch`` of its own+ # and keeps up to this many in flight, as the worker does for direct+ # requests. ``None`` (older servers) and 1 keep sidecar batching.+ max_concurrent_dispatch: int | None = Noneclass EnsureModelReadyResponse(msgspec.Struct):diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex 187f0b18d..5a5134975 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -942,6 +942,8 @@ class QueueExecutor:authoritative gate. Future work can populate from``adapter.supported_output_types`` if/when adapters expose it.* ``supports_run_batch`` — every Python adapter does.+ * ``max_concurrent_dispatch`` — the worker's dispatch width (see+ ``ModelWorker.dispatch_width``).Cached after the first successful build; the dispatcherre-handshakes on every batch and we don't want to re-stat the@@ -1008,11 +1010,18 @@ class QueueExecutor:# follow the convention silently degrade the same way.default_query_template: str | None = Nonedefault_doc_template: str | None = None+ max_concurrent_dispatch: int | None = Nonetry:worker = self._registry.get_worker(model_id)adapter = worker.adapter if worker is not None else Noneexcept Exception: # noqa: BLE001+ worker = Noneadapter = None+ # The worker's own dispatch width: above 1 only for an adapter that+ # declares ``max_concurrent_dispatch() > 1`` and has no LoRA state.+ width = getattr(worker, "dispatch_width", None)+ if isinstance(width, int) and not isinstance(width, bool) and width > 0:+ max_concurrent_dispatch = widthif adapter is not None:qt = getattr(adapter, "_query_template", None)if isinstance(qt, str):@@ -1029,6 +1038,7 @@ class QueueExecutor:supports_run_batch=True,default_query_template=default_query_template,default_doc_template=default_doc_template,+ max_concurrent_dispatch=max_concurrent_dispatch,)self._descriptor_cache[model_id] = descriptorreturn descriptordiff --git a/packages/sie_server/tests/core/test_worker_concurrent_dispatch.py b/packages/sie_server/tests/core/test_worker_concurrent_dispatch.pyindex 1b8b36017..c70383665 100644--- a/packages/sie_server/tests/core/test_worker_concurrent_dispatch.py+++ b/packages/sie_server/tests/core/test_worker_concurrent_dispatch.py@@ -71,6 +71,11 @@ def test_dispatch_width_is_one_for_lora_adapters() -> None:assert _dispatch_width(_GatedAdapter(8, lora=True)) == 1+def test_worker_exposes_its_dispatch_width() -> None:+ assert ModelWorker(_GatedAdapter(8), _config()).dispatch_width == 8+ assert ModelWorker(_GatedAdapter(8, lora=True), _config()).dispatch_width == 1++@pytest.mark.asyncioasync def test_batches_overlap_up_to_the_declared_width() -> None:adapter = _GatedAdapter(3)diff --git a/packages/sie_server/tests/test_queue_executor_stage1d.py b/packages/sie_server/tests/test_queue_executor_stage1d.pyindex a2bb0137f..08c65b4c4 100644--- a/packages/sie_server/tests/test_queue_executor_stage1d.py+++ b/packages/sie_server/tests/test_queue_executor_stage1d.py@@ -634,6 +634,28 @@ class TestGetModelDescriptor:# hash this on load and reconcile against ``tokenizer_id``.assert Path(descriptor.tokenizer_path).read_bytes() == canonical+ @pytest.mark.parametrize(("width", "expected"), [(128, 128), (1, 1), (None, None)])+ def test_descriptor_reports_the_worker_dispatch_width(+ self,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ width: int | None,+ expected: int | None,+ ) -> None:+ monkeypatch.setattr(+ "sie_server.queue_executor._TOKENIZER_STAGING_DIR",+ tmp_path,+ )+ reg = self._descriptor_registry(tokenizer_id="abc", max_len=128, canonical=b'{"version":"1.0"}')+ worker = MagicMock()+ worker.dispatch_width = width+ reg.get_worker.return_value = worker++ descriptor = QueueExecutor(reg).get_model_descriptor(MODEL_ID)++ assert descriptor is not None+ assert descriptor.max_concurrent_dispatch == expected+def test_descriptor_is_cached_per_model(self,monkeypatch: pytest.MonkeyPatch,diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex 4deb7db0c..81fce64d0 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -516,7 +516,9 @@ Prometheus-shaped copy.`EnsureModelReady` returns readiness state and an optional `ModelDescriptor`.The descriptor carries tokenizer path, tokenizer content hash, maximum sequence-length, output types, default text templates, and `supports_run_batch`.+length, output types, default text templates, `supports_run_batch`, and+`max_concurrent_dispatch` (the batches the backend runs through the model's+adapter at once; see Scheduling).`loading_started` and `loading_in_progress` mean the same worker is activelyloading the model; the dispatcher progress-ACKs and rechecks instead of NAKingthose deliveries. `retry_later` remains a NAK path.@@ -542,6 +544,15 @@ 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.+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+`RunBatch` would only make each item wait for the slowest one, so the drain+loop sends each of that model's extract items in a `RunBatch` of its own. The+model's pipeline depth becomes the larger of `SIE_RUST_PIPELINE_DEPTH` and that+width, and the IPC client grows its slot pool by the same width when the model+becomes ready, so the pool is not the limit. The Python worker's direct path+makes the same choice: it serves these items one per batch.+Routing remains gateway-owned. The sidecar does not keep a separate localactive-model routing list.diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex f3e4a0e84..4a4d28841 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -33,9 +33,9 @@ use crate::delivery::Delivery;use crate::ipc_client::IpcError;use crate::ipc_types::{BatchOutcome, BatchedF16MultivectorOutput, Disposition, EncodeBatchItem, ExtractBatchItem,- GenerateEvent, ItemOutcome, PreparedAudioPcm16, PreparedTokens, ProcessEncodeBatchRequest,- ProcessExtractBatchRequest, ProcessGenerateRequest, ProcessScoreBatchRequest, ReadinessState,- RunBatchRequest, ScoreBatchItem,+ GenerateEvent, ItemOutcome, ModelDescriptor, PreparedAudioPcm16, PreparedTokens,+ ProcessEncodeBatchRequest, ProcessExtractBatchRequest, ProcessGenerateRequest,+ ProcessScoreBatchRequest, ReadinessState, RunBatchRequest, ScoreBatchItem,};use crate::latency::LatencyTracker;use crate::log_util::ErrChain;@@ -670,9 +670,123 @@ pub struct Dispatcher {pub request_cancel_state: RequestCancelState,/// Gateway-stamped deadline enforcement, read from env at construction.pub work_deadline: WorkDeadlinePolicy,+ /// Dispatch width each model's backend reported on its last+ /// `EnsureModelReady` (`ModelDescriptor::max_concurrent_dispatch`).+ /// Only widths above 1 are kept; see [`Dispatcher::dispatch_width`].+ dispatch_widths: Arc<std::sync::RwLock<HashMap<String, usize>>>,+ /// Each model's scheduler pipeline, shared with its drain loop so a+ /// larger width reported after the loop started can widen it.+ pipelines: Arc<std::sync::Mutex<HashMap<String, Arc<ModelPipeline>>>>,+}++/// In-flight batch permits of one model's scheduler drain loop. The depth+/// only grows: a later `EnsureModelReady` that reports a larger dispatch+/// width adds permits to the running loop.+struct ModelPipeline {+ permits: Arc<Semaphore>,+ depth: std::sync::atomic::AtomicUsize,+}++impl ModelPipeline {+ fn new(depth: usize) -> Self {+ Self {+ permits: Arc::new(Semaphore::new(depth)),+ depth: std::sync::atomic::AtomicUsize::new(depth),+ }+ }++ fn depth(&self) -> usize {+ self.depth.load(Ordering::Acquire)+ }++ /// Raise the depth to `depth`; never lowers it.+ fn grow_to(&self, depth: usize) {+ let previous = self.depth.fetch_max(depth, Ordering::AcqRel);+ if depth > previous {+ self.permits.add_permits(depth - previous);+ }+ }}impl Dispatcher {+ /// Keep the dispatch width a model's backend reported on+ /// `EnsureModelReady`. A width above 1 means the adapter fronts an+ /// engine that batches continuously (SGLang): Python runs that many+ /// batches through it at once, so the scheduler sends each extract+ /// item alone and keeps up to that many in flight for the model.+ fn record_dispatch_width(&self, model_id: &str, descriptor: Option<&ModelDescriptor>) {+ let width = descriptor+ .and_then(|d| d.max_concurrent_dispatch)+ .map_or(1, |w| {+ (w as usize).clamp(1, MAX_ENGINE_BATCHED_PIPELINE_DEPTH)+ });+ if self.dispatch_width(model_id) == width {+ return;+ }+ let mut widths = self+ .dispatch_widths+ .write()+ .expect("dispatch width lock poisoned");+ if width > 1 {+ widths.insert(model_id.to_owned(), width);+ } else {+ widths.remove(model_id);+ }+ drop(widths);+ // A drain loop that is already running keeps its semaphore; widen it.+ let pipeline = self+ .pipelines+ .lock()+ .expect("pipeline map lock poisoned")+ .get(model_id)+ .cloned();+ if let Some(pipeline) = pipeline {+ pipeline.grow_to(self.pipeline_depth_for(model_id));+ }+ info!(+ model = %model_id,+ dispatch_width = width,+ "rust-scheduler: backend dispatch width recorded",+ );+ }++ /// The pipeline of `model_id`'s drain loop, created at+ /// [`Self::pipeline_depth_for`] on first use.+ fn model_pipeline(&self, model_id: &str) -> Arc<ModelPipeline> {+ let mut pipelines = self.pipelines.lock().expect("pipeline map lock poisoned");+ Arc::clone(+ pipelines+ .entry(model_id.to_owned())+ .or_insert_with(|| Arc::new(ModelPipeline::new(self.pipeline_depth_for(model_id)))),+ )+ }++ /// Batches the backend runs through `model_id`'s adapter at once+ /// (1 unless its last `EnsureModelReady` reported more).+ pub(crate) fn dispatch_width(&self, model_id: &str) -> usize {+ self.dispatch_widths+ .read()+ .expect("dispatch width lock poisoned")+ .get(model_id)+ .copied()+ .unwrap_or(1)+ }++ /// True when `op` items of `model_id` go to the backend one per+ /// `RunBatch`. For an engine that batches continuously, a shared+ /// `RunBatch` only makes every item wait for the slowest one before any+ /// result is published (the Python worker flags the same items+ /// `runs_alone` on its direct path).+ fn dispatches_items_alone(&self, model_id: &str, op: SchedOp) -> bool {+ op == SchedOp::Extract && self.dispatch_width(model_id) > 1+ }++ /// Scheduler pipeline depth for `model_id`: the configured depth, or the+ /// backend's dispatch width when that is larger.+ fn pipeline_depth_for(&self, model_id: &str) -> usize {+ pipeline_depth().max(self.dispatch_width(model_id))+ }+fn execution_hash_is_current(&self, wi: &WorkItem) -> bool {!wi.bundle_config_hash.is_empty()&& self.config_apply_state.is_some()@@ -750,6 +864,8 @@ impl Dispatcher {batch_cancel_state,request_cancel_state,work_deadline: WorkDeadlinePolicy::from_env(),+ dispatch_widths: Arc::new(std::sync::RwLock::new(HashMap::new())),+ pipelines: Arc::new(std::sync::Mutex::new(HashMap::new())),}}}@@ -2429,6 +2545,7 @@ impl Dispatcher {// re-handshake — the registry hashes the loaded// tokenizer.json and short-circuits if the declared// `tokenizer_id` already matches what's cached.+ self.record_dispatch_width(model_id, readiness_resp.descriptor.as_ref());if let Some(descriptor) = readiness_resp.descriptor.as_ref() {match self.tokenizer_registry@@ -5859,6 +5976,10 @@ fn decrement_gauge(gauge: &RuntimeGauge, value: i64) {/// conservative: Python inference is still serialized by the adapter's/// single CUDA stream, so large depths mainly park decoded batches on/// the lock and inflate per-batch latency.+/// Ceiling on a model's pipeline depth when its backend reports a dispatch+/// width (see [`Dispatcher::pipeline_depth_for`]).+const MAX_ENGINE_BATCHED_PIPELINE_DEPTH: usize = 1024;+fn pipeline_depth() -> usize {std::env::var("SIE_RUST_PIPELINE_DEPTH").ok()@@ -5921,6 +6042,95 @@ fn spawn_pipelined_batch_with_permit(});}+/// Spawn a formed scheduler batch on `permit`, or, when the model's backend+/// takes these items one at a time (see+/// [`Dispatcher::dispatches_items_alone`]), spawn each item as its own batch.+/// Every item after the first waits for its own pipeline slot, so a model+/// never has more than its pipeline depth in flight. If shutdown wins that+/// wait, the remaining items run here as one batch: they have already left+/// the scheduler, so the final drain would not see them.+#[allow(clippy::too_many_arguments)]+async fn spawn_scheduler_batch(+ model_id: &str,+ dispatcher: &Arc<Dispatcher>,+ scheduler: &Arc<ProductionScheduler>,+ pipeline_sem: &Arc<Semaphore>,+ shutdown: &Shutdown,+ permit: OwnedSemaphorePermit,+ op: SchedOp,+ lora: crate::scheduler::LoraKey,+ batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,+ role: WaveRole,+) {+ if batch.items.len() <= 1 || !dispatcher.dispatches_items_alone(model_id, op) {+ spawn_pipelined_batch_with_permit(+ model_id, dispatcher, scheduler, permit, op, lora, batch, role,+ );+ return;+ }+ let flush_reason = batch.flush_reason;+ let mut singles = batch+ .items+ .into_iter()+ .zip(batch.metadata)+ .map(|(item, meta)| crate::scheduler::FormattedBatch {+ total_cost: item.cost(),+ items: vec![item],+ metadata: vec![meta],+ flush_reason,+ });+ let first = singles.next().expect("a batch of two or more items");+ spawn_pipelined_batch_with_permit(+ model_id,+ dispatcher,+ scheduler,+ permit,+ op,+ lora.clone(),+ first,+ role,+ );+ while let Some(single) = singles.next() {+ let Some(permit) = reserve_pipeline_slot(pipeline_sem, shutdown).await else {+ let rest = std::iter::once(single).chain(singles).fold(+ crate::scheduler::FormattedBatch {+ items: Vec::new(),+ metadata: Vec::new(),+ total_cost: 0,+ flush_reason,+ },+ |mut acc, one| {+ acc.total_cost += one.total_cost;+ acc.items.extend(one.items);+ acc.metadata.extend(one.metadata);+ acc+ },+ );+ process_scheduler_batch(+ model_id,+ dispatcher,+ scheduler,+ op,+ lora,+ rest,+ WaveRole::Drain,+ )+ .await;+ return;+ };+ spawn_pipelined_batch_with_permit(+ model_id,+ dispatcher,+ scheduler,+ permit,+ op,+ lora.clone(),+ single,+ WaveRole::Drain,+ );+ }+}+/// Reserve one pipeline slot unless shutdown wins first.////// Every scheduler extract is preceded by this wait. While all slots are@@ -5974,7 +6184,11 @@ pub(crate) async fn scheduler_drain_loop(scheduler: Arc<ProductionScheduler>,shutdown: Arc<Shutdown>,) {- let depth = pipeline_depth();+ // The loop starts after the model's first `EnsureModelReady`, which+ // reports its dispatch width; a larger width reported later widens the+ // pipeline in place (see `Dispatcher::record_dispatch_width`).+ let pipeline = dispatcher.model_pipeline(&model_id);+ let depth = pipeline.depth();let idle_bypass_enabled = scheduler_idle_bypass_enabled();info!(model = %model_id,@@ -6006,7 +6220,7 @@ pub(crate) async fn scheduler_drain_loop(// dispatch (one outstanding IPC roundtrip). At very high// concurrency, operators may prefer `1` to avoid parking a second// frame behind a long GPU forward pass.- let pipeline_sem = Arc::new(Semaphore::new(depth));+ let pipeline_sem = Arc::clone(&pipeline.permits);// Idle-bypass + continuous-batching state. On the queue path,// Python's `model_worker.py::_process_loop` is bypassed and the Rust@@ -6074,16 +6288,19 @@ pub(crate) async fn scheduler_drain_loop(let initial_batch_size = batch.items.len();// First batch in the wave drives the controller step.- spawn_pipelined_batch_with_permit(+ spawn_scheduler_batch(&model_id,&dispatcher,&scheduler,+ &pipeline_sem,+ &shutdown,primary_permit,op,lora.clone(),batch,WaveRole::Primary,- );+ )+ .await;// Wait for the first continuation slot before snapshotting the drain// budget. At saturation this is when one active backend call finishes,@@ -6145,16 +6362,19 @@ pub(crate) async fn scheduler_drain_loop(drained_any = true;// Drains continue the wave: feed inference + latency samples, but// no controller step.- spawn_pipelined_batch_with_permit(+ spawn_scheduler_batch(&model_id,&dispatcher,&scheduler,+ &pipeline_sem,+ &shutdown,permit,op,lora.clone(),drain_batch,WaveRole::Drain,- );+ )+ .await;if drain_budget > 0 {let Some(next_permit) = reserve_pipeline_slot(&pipeline_sem, &shutdown).await@@ -6172,13 +6392,17 @@ pub(crate) async fn scheduler_drain_loop(was_idle = !drained_any && initial_batch_size <= 1;}- // Quiesce the pipeline: acquire all `depth` permits so every+ // Quiesce the pipeline: acquire all of its permits so every// spawned dispatch task has finished its IPC roundtrip and// released its permit. Only then do we enter synchronous shutdown// drain below. Without this the final-drain loop// could race with still-in-flight pipelined batches and double-// submit work to Python.- if let Ok(permits) = pipeline_sem.clone().acquire_many_owned(depth as u32).await {+ if let Ok(permits) = pipeline_sem+ .clone()+ .acquire_many_owned(pipeline.depth() as u32)+ .await+ {// Hold the permits for the rest of the function so no further// spawns can sneak in (`spawn_pipelined_batch` is no longer// called past this point, but defence-in-depth).@@ -7214,6 +7438,236 @@ mod tests {assert!(backend.encoded_models().is_empty());}+ /// Ready backend whose descriptor reports `width`. Holds every+ /// `RunBatch` until `release` has a permit for it, recording each+ /// batch's size and the most batches in flight at once.+ struct EngineBatchedBackend {+ width: std::sync::Mutex<Option<u32>>,+ sizes: std::sync::Mutex<Vec<usize>>,+ active: std::sync::atomic::AtomicUsize,+ peak: std::sync::atomic::AtomicUsize,+ release: Semaphore,+ }++ impl EngineBatchedBackend {+ fn new(width: Option<u32>) -> Arc<Self> {+ Arc::new(Self {+ width: std::sync::Mutex::new(width),+ sizes: std::sync::Mutex::new(Vec::new()),+ active: std::sync::atomic::AtomicUsize::new(0),+ peak: std::sync::atomic::AtomicUsize::new(0),+ release: Semaphore::new(0),+ })+ }++ /// Batch sizes and peak in flight since the last call.+ fn take_observations(&self) -> (Vec<usize>, usize) {+ let sizes = std::mem::take(&mut *self.sizes.lock().unwrap());+ (sizes, self.peak.swap(0, Ordering::SeqCst))+ }+ }++ #[async_trait::async_trait]+ impl crate::backend::InferenceBackend for EngineBatchedBackend {+ fn name(&self) -> &'static str {+ "engine-batched"+ }++ fn supports(&self, _model_id: &str) -> bool {+ true+ }++ async fn ensure_model_ready(+ &self,+ _model_id: &str,+ ) -> Result<crate::ipc_types::EnsureModelReadyResponse, BackendError> {+ Ok(crate::ipc_types::EnsureModelReadyResponse {+ state: ReadinessState::Ready,+ batch_budget: None,+ descriptor: Some(ModelDescriptor {+ supports_run_batch: true,+ max_concurrent_dispatch: *self.width.lock().unwrap(),+ ..Default::default()+ }),+ })+ }++ async fn process_encode_batch(+ &self,+ _req: ProcessEncodeBatchRequest,+ ) -> Result<BatchOutcome, BackendError> {+ Err(BackendError::UnsupportedModel("encode".into()))+ }++ async fn process_score_batch(+ &self,+ _req: ProcessScoreBatchRequest,+ ) -> Result<BatchOutcome, BackendError> {+ Err(BackendError::UnsupportedModel("score".into()))+ }++ async fn process_extract_batch(+ &self,+ _req: ProcessExtractBatchRequest,+ ) -> Result<BatchOutcome, BackendError> {+ Err(BackendError::UnsupportedModel("extract".into()))+ }++ async fn run_batch(&self, req: RunBatchRequest) -> Result<BatchOutcome, BackendError> {+ self.sizes.lock().unwrap().push(req.items.len());+ let now = self.active.fetch_add(1, Ordering::SeqCst) + 1;+ self.peak.fetch_max(now, Ordering::SeqCst);+ self.release+ .acquire()+ .await+ .expect("release stays open")+ .forget();+ self.active.fetch_sub(1, Ordering::SeqCst);+ let outcomes = req+ .items+ .iter()+ .map(|item| {+ outcome(+ &item.request_id,+ item.item_index,+ Disposition::NakRetry,+ None,+ None,+ )+ })+ .collect();+ Ok(BatchOutcome {+ outcomes,+ batched_f16_multivectors: Vec::new(),+ })+ }+ }++ /// A dispatcher with the production scheduler wired in.+ fn scheduled_dispatcher(+ backend: Arc<EngineBatchedBackend>,+ ) -> (Arc<Dispatcher>, Arc<Shutdown>) {+ let mut dispatcher = dispatcher_with_backend(backend);+ let shutdown = Arc::new(Shutdown::new());+ let mutable = Arc::get_mut(&mut dispatcher).unwrap();+ mutable.scheduler_registry = Some(Arc::new(ProductionSchedulerRegistry::new(+ crate::scheduler::BatchConfig::default(),+ )));+ mutable.shutdown = Some(Arc::clone(&shutdown));+ (dispatcher, shutdown)+ }++ /// Send `slots` one-page extract requests for model "ocr", then give the+ /// scheduler time to send all it will while the backend holds them.+ async fn send_extract_pages(+ dispatcher: &Arc<Dispatcher>,+ prefix: &str,+ slots: std::ops::Range<u32>,+ tx: &tokio::sync::mpsc::UnboundedSender<crate::delivery::LocalDeliveryEvent>,+ ) {+ let count = slots.len();+ let group = slots+ .map(|slot| {+ (+ wi(&format!("{prefix}-{slot}"), 0, "ocr", "extract"),+ Delivery::Local(LocalDelivery::new(slot as usize, 0, tx.clone())),+ )+ })+ .collect();+ dispatcher+ .dispatch_decoded(group, count, Instant::now())+ .await;+ tokio::time::sleep(Duration::from_secs(1)).await;+ }++ async fn stop_scheduled(dispatcher: &Arc<Dispatcher>, shutdown: &Shutdown) {+ shutdown.fire();+ for handle in dispatcher.take_scheduler_drain_handles().await {+ handle.abort();+ }+ }++ /// Dispatch `items` single-page extract requests for one model and+ /// return the `RunBatch` sizes, the peak in flight before any batch+ /// finished, and the model's pipeline depth.+ async fn run_extract_group(width: Option<u32>, items: u32) -> (Vec<usize>, usize, usize) {+ let backend = EngineBatchedBackend::new(width);+ let (dispatcher, shutdown) = scheduled_dispatcher(backend.clone());+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();+ send_extract_pages(&dispatcher, "page", 0..items, &tx).await;+ let (sizes, peak) = backend.take_observations();+ let depth = dispatcher.model_pipeline("ocr").depth();+ backend.release.add_permits(items as usize);+ tokio::time::sleep(Duration::from_secs(1)).await;+ stop_scheduled(&dispatcher, &shutdown).await;+ (sizes, peak, depth)+ }++ #[tokio::test(start_paused = true)]+ async fn engine_batched_extract_items_run_alone_and_all_at_once() {+ let (sizes, peak, depth) = run_extract_group(Some(8), 6).await;+ assert_eq!(depth, 8, "the model's pipeline depth follows its width");+ assert_eq!(sizes, vec![1; 6], "each page is its own RunBatch");+ assert_eq!(peak, 6, "every page is in flight before any finishes");+ }++ #[tokio::test(start_paused = true)]+ async fn extract_items_still_share_batches_without_a_dispatch_width() {+ let (sizes, peak, depth) = run_extract_group(None, 6).await;+ assert_eq!(depth, pipeline_depth());+ assert_eq!(sizes.iter().sum::<usize>(), 6);+ assert!(sizes.iter().any(|&size| size > 1), "sizes {sizes:?}");+ assert!(peak <= pipeline_depth(), "peak {peak}");+ }++ #[tokio::test(start_paused = true)]+ async fn a_larger_width_reported_later_widens_the_running_pipeline() {+ let backend = EngineBatchedBackend::new(None);+ let (dispatcher, shutdown) = scheduled_dispatcher(backend.clone());+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();++ // First traffic starts the drain loop at the default depth. One page+ // keeps the loop idle afterwards, so the next group flushes at once+ // instead of on the batch former's wall-clock windows.+ send_extract_pages(&dispatcher, "before", 0..1, &tx).await;+ backend.release.add_permits(1);+ tokio::time::sleep(Duration::from_secs(1)).await;+ assert_eq!(dispatcher.model_pipeline("ocr").depth(), pipeline_depth());+ backend.take_observations();++ // A reload reports width 8: the same loop now runs every page at once.+ *backend.width.lock().unwrap() = Some(8);+ send_extract_pages(&dispatcher, "after", 1..7, &tx).await;+ let (sizes, peak) = backend.take_observations();+ assert_eq!(dispatcher.model_pipeline("ocr").depth(), 8);+ assert_eq!(sizes, vec![1; 6]);+ assert_eq!(peak, 6);++ backend.release.add_permits(6);+ tokio::time::sleep(Duration::from_secs(1)).await;+ stop_scheduled(&dispatcher, &shutdown).await;+ }++ #[test]+ fn only_extract_on_an_engine_batched_model_dispatches_alone() {+ let dispatcher = dispatcher_with_backend(EngineBatchedBackend::new(None));+ let wide = ModelDescriptor {+ max_concurrent_dispatch: Some(128),+ ..Default::default()+ };+ dispatcher.record_dispatch_width("ocr", Some(&wide));+ assert_eq!(dispatcher.dispatch_width("ocr"), 128);+ assert!(dispatcher.dispatches_items_alone("ocr", SchedOp::Extract));+ assert!(!dispatcher.dispatches_items_alone("ocr", SchedOp::Encode));+ assert!(!dispatcher.dispatches_items_alone("other", SchedOp::Extract));++ // A reload that no longer reports a width restores batching.+ dispatcher.record_dispatch_width("ocr", Some(&ModelDescriptor::default()));+ assert_eq!(dispatcher.dispatch_width("ocr"), 1);+ assert!(!dispatcher.dispatches_items_alone("ocr", SchedOp::Extract));+ assert_eq!(dispatcher.pipeline_depth_for("ocr"), pipeline_depth());+ }+#[tokio::test]async fn half_wired_scheduler_cannot_downgrade_verified_numeric_work() {let backend = LoadingModelBackend::new("cold");diff --git a/packages/sie_server_sidecar/src/ipc_client.rs b/packages/sie_server_sidecar/src/ipc_client.rsindex 40497d37e..8c8d0abc3 100644--- a/packages/sie_server_sidecar/src/ipc_client.rs+++ b/packages/sie_server_sidecar/src/ipc_client.rs@@ -28,9 +28,9 @@//! `SIE_MAX_CONCURRENT_BATCHES` so the dispatcher's concurrency limit//! is the binding one, not this socket mutex.-use std::collections::VecDeque;+use std::collections::{HashMap, VecDeque};use std::path::{Path, PathBuf};-use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};use std::sync::{Arc, Mutex as StdMutex};use std::time::Duration;@@ -48,12 +48,13 @@ use crate::ipc_types::{EnsureModelReadyRequest, EnsureModelReadyResponse, GenerateEvent,NumericalProfileSnapshotRequest, NumericalProfileSnapshotResponse, PingRequest, PingResponse,ProcessEncodeBatchRequest, ProcessExtractBatchRequest, ProcessGenerateRequest,- ProcessScoreBatchRequest, ReplaceModelConfigsRequest, ReplaceModelConfigsResponse,- RequestEnvelope, ResponseEnvelope, RunBatchRequest, SetPinnedModelsRequest,- SetPinnedModelsResponse, SignalGenerateCancelRequest, SignalGenerateCancelResponse,- WorkerCapabilitiesRequest, WorkerCapabilitiesResponse, IPC_VERSION, METHOD_APPLY_MODEL_CONFIG,- METHOD_DRAIN, METHOD_ENSURE_MODEL_READY, METHOD_NUMERICAL_PROFILE_SNAPSHOT, METHOD_PING,- METHOD_PROCESS_ENCODE_BATCH, METHOD_PROCESS_EXTRACT_BATCH, METHOD_PROCESS_GENERATE,+ ProcessScoreBatchRequest, ReadinessState, ReplaceModelConfigsRequest,+ ReplaceModelConfigsResponse, RequestEnvelope, ResponseEnvelope, RunBatchRequest,+ SetPinnedModelsRequest, SetPinnedModelsResponse, SignalGenerateCancelRequest,+ SignalGenerateCancelResponse, WorkerCapabilitiesRequest, WorkerCapabilitiesResponse,+ IPC_VERSION, METHOD_APPLY_MODEL_CONFIG, METHOD_DRAIN, METHOD_ENSURE_MODEL_READY,+ METHOD_NUMERICAL_PROFILE_SNAPSHOT, METHOD_PING, METHOD_PROCESS_ENCODE_BATCH,+ METHOD_PROCESS_EXTRACT_BATCH, METHOD_PROCESS_GENERATE,METHOD_PROCESS_GENERATE_WITH_EXECUTION_AUTHORITY_V1, METHOD_PROCESS_SCORE_BATCH,METHOD_REPLACE_MODEL_CONFIGS, METHOD_RUN_BATCH, METHOD_RUN_BATCH_WITH_EXECUTION_AUTHORITY_V1,METHOD_RUN_BATCH_WITH_NUMERICAL_ADMISSION_V1, METHOD_SET_PINNED_MODELS,@@ -263,7 +264,8 @@ impl Slot {/// idle. Checkout-and-return gives strict fairness and head-of-line/// isolation.struct Pool {- capacity: usize,+ /// Slots in the pool. Only grows (see [`Self::grow_to`]).+ capacity: AtomicUsize,slots: StdMutex<VecDeque<Slot>>,permits: Arc<Semaphore>,telemetry: Option<SidecarTelemetry>,@@ -277,13 +279,36 @@ impl Pool {slots.push_back(Slot::new(id));}Self {- capacity,+ capacity: AtomicUsize::new(capacity),slots: StdMutex::new(slots),permits: Arc::new(Semaphore::new(capacity)),telemetry,}}+ fn capacity(&self) -> usize {+ self.capacity.load(Ordering::Acquire)+ }++ /// Add slots until the pool holds `capacity`, returning the previous+ /// capacity, or `None` when the pool is already that large. New slots+ /// are queued before their permits are released, which keeps the+ /// invariant that a woken waiter always finds a slot.+ fn grow_to(&self, capacity: usize) -> Option<usize> {+ let mut q = self.slots.lock().expect("pool slot mutex poisoned");+ let current = self.capacity();+ if capacity <= current {+ return None;+ }+ for id in current..capacity {+ q.push_back(Slot::new(id));+ }+ self.capacity.store(capacity, Ordering::Release);+ drop(q);+ self.permits.add_permits(capacity - current);+ Some(current)+ }+/// Wait for a free slot. Returns an RAII guard that returns the slot/// to the pool on drop. If the caller wishes to discard a slot (e.g./// after an unrecoverable error) they can still drop the guard —@@ -440,8 +465,16 @@ pub struct IpcClient {/// cannot reserve unbounded sidecar heap.response_chunk_budget: Arc<ResponseChunkBudget>,response_chunk_limits: ResponseChunkLimits,+ /// Pool size before any engine-batched model asked for more.+ configured_pool_size: usize,+ /// Dispatch width above 1 that each ready model reported (see+ /// [`Self::ensure_model_ready`]).+ model_dispatch_widths: StdMutex<HashMap<String, usize>>,}+/// Ceiling on the dispatch width one model can add to the pool.+const MAX_MODEL_DISPATCH_WIDTH: usize = 1024;+impl IpcClient {/// Create a single-connection client. Equivalent to the pre-pool/// behaviour — kept for tests and simple callers; production@@ -477,6 +510,8 @@ impl IpcClient {mux,response_chunk_budget,response_chunk_limits: ResponseChunkLimits::production(),+ configured_pool_size: capacity,+ model_dispatch_widths: StdMutex::new(HashMap::new()),}}@@ -494,20 +529,20 @@ impl IpcClient {/// observation per RPC and negotiated response-chunk transfer.pub fn with_telemetry(mut self, telemetry: SidecarTelemetry) -> Self {if !telemetry.is_enabled() {- self.pool = Arc::new(Pool::new(self.pool.capacity, None));+ self.pool = Arc::new(Pool::new(self.pool.capacity(), None));self.telemetry = None;return self;}if let Some(mux) = &self.mux {// The slot pool is inactive in mux mode. Keep it telemetry-free so// dashboards never show capacity for a transport that cannot run.- self.pool = Arc::new(Pool::new(self.pool.capacity, None));+ self.pool = Arc::new(Pool::new(self.pool.capacity(), None));mux.attach_telemetry(telemetry.clone());} else {self.response_chunk_budget.attach_telemetry(telemetry.clone());- self.pool = Arc::new(Pool::new(self.pool.capacity, Some(telemetry.clone())));- telemetry.ipc_transport_registered("pool", self.pool.capacity);+ self.pool = Arc::new(Pool::new(self.pool.capacity(), Some(telemetry.clone())));+ telemetry.ipc_transport_registered("pool", self.pool.capacity());}self.telemetry = Some(telemetry);self@@ -517,8 +552,9 @@ impl IpcClient {/// parsed from env in `main.rs` after `IpcClient::new` was chosen/// for a reasonable default. Clamped to `>= 1`.pub fn with_pool_size(mut self, pool_size: usize) -> Self {- let previous_capacity = self.pool.capacity;+ let previous_capacity = self.pool.capacity();let capacity = pool_size.max(1);+ self.configured_pool_size = capacity;let pool_telemetry = if self.mux.is_none() {self.telemetry.clone()} else {@@ -537,9 +573,10 @@ impl IpcClient {&self.socket_path}- /// Configured pool capacity (≥ 1).+ /// Current pool capacity (≥ 1): the configured size plus the slots added+ /// for engine-batched models (see [`Self::ensure_model_ready`]).pub fn pool_size(&self) -> usize {- self.pool.capacity+ self.pool.capacity()}/// Drop every idle pooled socket. Used on shutdown or after a hard@@ -1021,18 +1058,69 @@ impl IpcClient {self.call(METHOD_PING, PingRequest { timestamp_ms }).await}+ /// Ask the backend to make `model_id` ready.+ ///+ /// A ready model whose descriptor reports `max_concurrent_dispatch`+ /// above 1 fronts an engine that batches continuously; the dispatcher+ /// then keeps that many single-item `RunBatch` calls in flight for it.+ /// Each pooled call holds a connection, so the pool grows to its+ /// configured size plus every such model's width. It never shrinks.pub async fn ensure_model_ready(&self,model_id: impl Into<String>,) -> Result<EnsureModelReadyResponse, IpcError> {- self.call_with_timeout(- METHOD_ENSURE_MODEL_READY,- EnsureModelReadyRequest {- model_id: model_id.into(),- },- self.model_ready_timeout,- )- .await+ let model_id = model_id.into();+ let response: EnsureModelReadyResponse = self+ .call_with_timeout(+ METHOD_ENSURE_MODEL_READY,+ EnsureModelReadyRequest {+ model_id: model_id.clone(),+ },+ self.model_ready_timeout,+ )+ .await?;+ if response.state == ReadinessState::Ready {+ let width = response+ .descriptor+ .as_ref()+ .and_then(|d| d.max_concurrent_dispatch)+ .map_or(1, |w| (w as usize).clamp(1, MAX_MODEL_DISPATCH_WIDTH));+ self.size_pool_for_model(&model_id, width);+ }+ Ok(response)+ }++ /// Keep the pool at its configured size plus the dispatch width of+ /// every ready engine-batched model. The multiplexed transport has no+ /// slots to size.+ fn size_pool_for_model(&self, model_id: &str, width: usize) {+ if self.mux.is_some() {+ return;+ }+ let target = {+ let mut widths = self+ .model_dispatch_widths+ .lock()+ .expect("model dispatch width mutex poisoned");+ if width > 1 {+ widths.insert(model_id.to_owned(), width);+ } else {+ widths.remove(model_id);+ }+ self.configured_pool_size + widths.values().sum::<usize>()+ };+ if let Some(previous) = self.pool.grow_to(target) {+ info!(+ model = %model_id,+ dispatch_width = width,+ previous,+ capacity = target,+ "ipc_client: pool grown for an engine-batched model"+ );+ if let Some(telemetry) = &self.telemetry {+ telemetry.ipc_transport_resized("pool", previous, target);+ }+ }}pub async fn worker_capabilities(&self) -> Result<WorkerCapabilitiesResponse, IpcError> {@@ -1628,6 +1716,68 @@ mod tests {server.await.unwrap();}+ #[tokio::test]+ async fn pool_grows_for_engine_batched_models_and_never_shrinks() {+ let client = IpcClient::new_pool(short_sock_path(), 4);+ client.size_pool_for_model("ocr", 128);+ assert_eq!(client.pool_size(), 132);+ client.size_pool_for_model("glm", 16);+ assert_eq!(client.pool_size(), 148, "widths add up across models");+ client.size_pool_for_model("ocr", 1);+ assert_eq!(client.pool_size(), 148, "the pool never shrinks");+ client.size_pool_for_model("ocr", 64);+ assert_eq!(client.pool_size(), 148, "4 + 16 + 64 fits the grown pool");++ // Every slot can be checked out at once, and each holds its own id.+ let guards = tokio::time::timeout(+ Duration::from_secs(5),+ futures_util::future::join_all((0..148).map(|_| client.pool.acquire())),+ )+ .await+ .expect("all 148 slots are free");+ let mut ids: Vec<usize> = guards+ .into_iter()+ .map(|mut guard| guard.slot_mut().id)+ .collect();+ ids.sort_unstable();+ assert_eq!(ids, (0..148).collect::<Vec<_>>());+ }++ #[tokio::test]+ async fn ready_model_with_a_dispatch_width_grows_the_pool() {+ let path = short_sock_path();+ let _server = spawn_echo(path.clone(), |req_bytes| {+ let req: serde_json::Value = rmp_serde::from_slice(req_bytes).unwrap();+ let model_id = req["body"]["model_id"].as_str().unwrap().to_string();+ let descriptor = match model_id.as_str() {+ "ocr" => {+ serde_json::json!({"supports_run_batch": true, "max_concurrent_dispatch": 128})+ }+ _ => serde_json::json!({"supports_run_batch": true}),+ };+ let envelope = serde_json::json!({+ "version": IPC_VERSION,+ "request_id": req["request_id"],+ "ok": true,+ "body": {"state": "ready", "batch_budget": 12, "descriptor": descriptor},+ "error": serde_json::Value::Null,+ });+ rmp_serde::to_vec_named(&envelope).unwrap()+ })+ .await;+ tokio::task::yield_now().await;++ let client = IpcClient::new_pool(path, 4);+ client.ensure_model_ready("encoder").await.unwrap();+ assert_eq!(client.pool_size(), 4, "no width, no growth");+ let ready = client.ensure_model_ready("ocr").await.unwrap();+ assert_eq!(+ ready.descriptor.and_then(|d| d.max_concurrent_dispatch),+ Some(128)+ );+ assert_eq!(client.pool_size(), 132);+ }+#[tokio::test]async fn server_error_surfaces_as_ipc_server() {let path = short_sock_path();diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rsindex 84068cd35..30252febb 100644--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs@@ -290,6 +290,15 @@ pub struct ModelDescriptor {/// `is_query=false`.#[serde(default)]pub default_doc_template: Option<String>,+ /// Batches the backend runs through this model's adapter at once+ /// (Python: the worker's honoured `max_concurrent_dispatch()`). Above 1+ /// the engine behind the adapter batches continuously (SGLang), so the+ /// dispatcher sends each extract item in a `RunBatch` of its own and+ /// keeps up to this many in flight for the model, matching the+ /// worker's direct path. `None` (older backends) and 1 keep scheduler+ /// batching and the default pipeline depth.+ #[serde(default)]+ pub max_concurrent_dispatch: Option<u32>,}#[derive(Debug, Clone, Serialize, Deserialize)]