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
fix(sidecar): serve long-form audio in its own lane, with per-model batch cost caps (#628)
Shai Shmuel422b99f6ced9
diff --git a/packages/sie_server/src/sie_server/_ipc_test_harness.py b/packages/sie_server/src/sie_server/_ipc_test_harness.pyindex 019c5946b..f5ccc3a56 100644--- a/packages/sie_server/src/sie_server/_ipc_test_harness.py+++ b/packages/sie_server/src/sie_server/_ipc_test_harness.py@@ -125,10 +125,12 @@ class _StubExecutor:per_request_delay_ms: float = 0.0,generation_model: str | None = None,generation_hidden_polls: int = 0,+ max_batch_tokens: int | None = None,) -> None:self._readiness = readinessself._batch_budget = batch_budgetself._descriptor = descriptor+ self._max_batch_tokens = max_batch_tokensself._per_request_delay_ms = per_request_delay_msself._pinned_models: frozenset[str] = frozenset()self.registry = _StubRegistry(generation_model, generation_hidden_polls)@@ -142,6 +144,9 @@ class _StubExecutor:def get_model_descriptor(self, model_id: str) -> ModelDescriptor | None: # noqa: ARG002return self._descriptor+ def get_max_batch_tokens(self, model_id: str) -> int | None: # noqa: ARG002+ return self._max_batch_tokens+def loaded_model_names(self) -> list[str]:return []diff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.pyindex 4556fd6ba..80db324c7 100644--- a/packages/sie_server/src/sie_server/ipc_server.py+++ b/packages/sie_server/src/sie_server/ipc_server.py@@ -709,18 +709,21 @@ class IpcServer:async def _handle_ensure_ready(self, req: EnsureModelReadyRequest) -> EnsureModelReadyResponse:state = await self._executor.ensure_model_ready(req.model_id)- # Only populate batch_budget + descriptor on the "ready" path — the- # worker isn't guaranteed to exist in other states and the Rust- # side will re-query after the NAK delay anyway.+ # Only populate batch_budget, descriptor and max_batch_tokens on the+ # "ready" path — the worker isn't guaranteed to exist in other states+ # and the Rust side will re-query after the NAK delay anyway.batch_budget: int | None = Nonedescriptor = None+ max_batch_tokens: int | None = Noneif state == "ready":batch_budget = self._executor.get_batch_budget(req.model_id)descriptor = self._executor.get_model_descriptor(req.model_id)+ max_batch_tokens = self._executor.get_max_batch_tokens(req.model_id)return EnsureModelReadyResponse(state=state,batch_budget=batch_budget,descriptor=descriptor,+ max_batch_tokens=max_batch_tokens,)async def _handle_process_encode(self, req: ProcessEncodeBatchRequest) -> BatchOutcome:diff --git a/packages/sie_server/src/sie_server/ipc_types.py b/packages/sie_server/src/sie_server/ipc_types.pyindex 14ab4c8e4..cf1cd2f83 100644--- a/packages/sie_server/src/sie_server/ipc_types.py+++ b/packages/sie_server/src/sie_server/ipc_types.py@@ -185,6 +185,12 @@ class EnsureModelReadyResponse(msgspec.Struct):# HF fast tokeniser + structured ``output_types``; ``None`` for non-text /# image / audio adapters that do not emit it.descriptor: ModelDescriptor | None = None+ # The model's batch cost budget from its profile (``max_batch_tokens``), in+ # the model's cost units: tokens for text, milliseconds for audio. The+ # worker-sidecar sizes the model's batch cost cap and adaptive cost range+ # from it, as ``ModelWorker`` does for its own batcher. ``None`` when the+ # model is not ready.+ max_batch_tokens: int | None = None# -----------------------------------------------------------------------------diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex 5a5134975..7b3918dd1 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -1066,6 +1066,26 @@ class QueueExecutor:return budgetreturn None+ def get_max_batch_tokens(self, model_id: str) -> int | None:+ """Return the model's batch cost budget, or ``None`` if unknown / not loaded.++ Reads the worker's static ``config.max_batch_tokens`` (the resolved+ profile value), not ``_batch_config.max_batch_cost``, which the+ direct-path adaptive controller rewrites as it steps. The+ worker-sidecar derives the model's batch cost cap and adaptive cost+ range from it.+ """+ try:+ worker = self._registry.get_worker(model_id)+ except (KeyError, AttributeError):+ return None+ if worker is None:+ return None+ budget = getattr(getattr(worker, "config", None), "max_batch_tokens", None)+ if isinstance(budget, int) and not isinstance(budget, bool) and budget > 0:+ return budget+ return None+@staticmethoddef _options_key(options: dict[str, Any] | None) -> bytes:return pack_msgpack(options, use_bin_type=True) if options else b""diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.pyindex 634645cbd..05b2e54ac 100644--- a/packages/sie_server/tests/test_ipc_server.py+++ b/packages/sie_server/tests/test_ipc_server.py@@ -33,7 +33,7 @@ from sie_server.core.profile_identity import runtime_instance_idfrom sie_server.core.readiness import mark_not_ready, mark_ready, register_liveness_probefrom sie_server.core.registry import ModelRegistryfrom sie_server.core.timing import RequestTiming-from sie_server.core.worker.types import WorkerResult+from sie_server.core.worker.types import WorkerConfig, WorkerResultfrom sie_server.ipc_server import IpcServer, IpcServerErrorfrom sie_server.ipc_types import (IPC_VERSION,@@ -1185,6 +1185,43 @@ class TestEnsureModelReady:finally:await srv.stop(drain_timeout_s=1.0)+ @pytest.mark.asyncio+ async def test_max_batch_tokens_included_on_ready_only(self) -> None:+ """EnsureModelReady carries the model's batch cost budget so the+ worker-sidecar sizes the model's scheduler cost cap from it.+ """+ reg = MagicMock()+ reg.model_names = ["test/model"]+ reg.device = "cpu"+ reg.is_loaded.return_value = True+ reg.is_loading.return_value = False+ reg.loaded_model_names = []+ worker = MagicMock()+ worker.config = WorkerConfig(max_batch_tokens=720_000)+ reg.get_worker.return_value = worker+ executor = QueueExecutor(reg)+ sock = _short_sock_path()+ srv = IpcServer(sock, executor, worker_id="worker-test", stale_after_ms=10_000)+ await srv.start()+ try:+ client = await _Client.connect(sock)+ try:+ resp = await client.rpc("EnsureModelReady", {"model_id": "test/model"})+ assert resp["ok"] is True+ assert resp["body"]["state"] == "ready"+ assert resp["body"]["max_batch_tokens"] == 720_000++ # Not ready (unknown model): no budget, even with a worker.+ reg.has_model.return_value = False+ resp = await client.rpc("EnsureModelReady", {"model_id": "test/model"})+ assert resp["ok"] is True+ assert resp["body"]["state"] == "retry_later"+ assert resp["body"]["max_batch_tokens"] is None+ finally:+ await client.close()+ finally:+ await srv.stop(drain_timeout_s=1.0)+# -----------------------------------------------------------------------------# ApplyModelConfigdiff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.pyindex 45964b84e..f38cb9af4 100644--- a/packages/sie_server/tests/test_queue_executor.py+++ b/packages/sie_server/tests/test_queue_executor.py@@ -15,12 +15,13 @@ from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters.gliner2.adapter import GLiNER2Adapterfrom sie_server.adapters.laya.adapter import LayaAdapterfrom sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks+from sie_server.core.batcher import BatchConfigfrom sie_server.core.extract_cost import MAX_EXTRACT_LABELSfrom sie_server.core.inference_output import ExtractOutput, ScoreOutputfrom sie_server.core.loader import expand_profile_variants, load_model_configfrom sie_server.core.registry import ModelRegistryfrom sie_server.core.timing import RequestTiming-from sie_server.core.worker.types import WorkerResult+from sie_server.core.worker.types import WorkerConfig, WorkerResultfrom sie_server.ipc_types import (EncodeBatchItem,ExtractBatchItem,@@ -508,6 +509,62 @@ class TestGetBatchBudget:assert ex.get_batch_budget("test/model") is None+class TestGetMaxBatchTokens:+ """Per-model batch cost budget advertised to the worker-sidecar via+ EnsureModelReadyResponse.+ """++ def test_returns_the_profile_budget_from_the_worker_config(self) -> None:+ reg = _make_registry()+ worker = MagicMock()+ worker.config = WorkerConfig(max_batch_tokens=720_000)+ reg.get_worker.return_value = worker+ ex = QueueExecutor(reg)+ assert ex.get_max_batch_tokens("test/model") == 720_000++ def test_ignores_the_adaptive_batch_config_cost(self) -> None:+ # The direct-path adaptive controller rewrites+ # ``_batch_config.max_batch_cost`` (aliased as ``max_batch_tokens``) in+ # place as it steps; the advertised budget must stay the profile value.+ reg = _make_registry()+ worker = MagicMock()+ worker.config = WorkerConfig(max_batch_tokens=720_000)+ worker._batch_config = BatchConfig(max_batch_tokens=720_000)+ worker._batch_config.max_batch_cost = 180_000+ reg.get_worker.return_value = worker+ ex = QueueExecutor(reg)+ assert worker._batch_config.max_batch_tokens == 180_000+ assert ex.get_max_batch_tokens("test/model") == 720_000++ def test_returns_none_when_worker_missing(self) -> None:+ reg = _make_registry()+ reg.get_worker.return_value = None+ ex = QueueExecutor(reg)+ assert ex.get_max_batch_tokens("test/model") is None++ def test_returns_none_when_worker_has_no_config(self) -> None:+ reg = _make_registry()+ reg.get_worker.return_value = object() # no `config` attribute+ ex = QueueExecutor(reg)+ assert ex.get_max_batch_tokens("test/model") is None++ def test_returns_none_when_registry_raises(self) -> None:+ reg = _make_registry()+ reg.get_worker.side_effect = KeyError("test/model")+ ex = QueueExecutor(reg)+ assert ex.get_max_batch_tokens("test/model") is None++ @pytest.mark.parametrize("budget", ["720000", True, 0, -1, 720_000.0, None])+ def test_returns_none_for_a_non_positive_or_non_int_budget(self, budget: object) -> None:+ # Protect the wire: only a positive int reaches the IPC response.+ reg = _make_registry()+ worker = MagicMock()+ worker.config = MagicMock(max_batch_tokens=budget)+ reg.get_worker.return_value = worker+ ex = QueueExecutor(reg)+ assert ex.get_max_batch_tokens("test/model") is None++# -----------------------------------------------------------------------------# process_encode_batch# -----------------------------------------------------------------------------diff --git a/packages/sie_server_rust/src/candle_backend.rs b/packages/sie_server_rust/src/candle_backend.rsindex 30bb5f90e..3b9358f58 100644--- a/packages/sie_server_rust/src/candle_backend.rs+++ b/packages/sie_server_rust/src/candle_backend.rs@@ -1199,6 +1199,7 @@ impl CandleBackend {state: ReadinessState::RetryLater,batch_budget: None,descriptor: None,+ max_batch_tokens: None,};}@@ -1211,6 +1212,7 @@ impl CandleBackend {state: ReadinessState::RetryLater,batch_budget: Some(self.config.batch_budget),descriptor: None,+ max_batch_tokens: None,};};@@ -1221,6 +1223,7 @@ impl CandleBackend {state: ReadinessState::RetryLater,batch_budget: None,descriptor: None,+ max_batch_tokens: None,};}@@ -1231,6 +1234,7 @@ impl CandleBackend {state,batch_budget: None,descriptor: None,+ max_batch_tokens: None,};}Err(error) => {@@ -1243,6 +1247,7 @@ impl CandleBackend {state: ReadinessState::RetryLater,batch_budget: None,descriptor: None,+ max_batch_tokens: None,};}}@@ -1253,12 +1258,14 @@ impl CandleBackend {state: ReadinessState::LoadingInProgress,batch_budget: None,descriptor: None,+ max_batch_tokens: None,};};EnsureModelReadyResponse {state: ReadinessState::Ready,batch_budget: Some(self.config.batch_budget),+ max_batch_tokens: ready_max_batch_tokens(&defaults),descriptor: Some(ModelDescriptor {tokenizer_path: Some(tokenizer_path),tokenizer_id: Some(tokenizer_id),@@ -3807,6 +3814,14 @@ fn candle_slow_forward_log_threshold_ms() -> Option<f64> {})}+/// The profile budget a ready model reports with `EnsureModelReady`: the+/// effective `max_batch_tokens` of the profile `model_id` routes to.+fn ready_max_batch_tokens(defaults: &RuntimeDefaults) -> Option<u64> {+ defaults+ .max_batch_tokens+ .and_then(|budget| u64::try_from(budget).ok())+}+fn selected_runtime_defaults(model_id: &str,requested_profile: Option<&str>,@@ -7060,6 +7075,39 @@ profiles:assert_eq!(defaults.normalize, Some(false));}+ #[test]+ fn ready_budget_is_the_routed_profile_max_batch_tokens() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));+ for (model_id, model_config) in [+ (+ "prithivida/Splade_PP_en_v2",+ include_str!("../../sie_server/models/prithivida__Splade_PP_en_v2.yaml"),+ ),+ (+ "topk-io/Iso-ModernColBERT",+ include_str!("../../sie_server/models/topk-io__Iso-ModernColBERT.yaml"),+ ),+ ] {+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: model_id.to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: model_config.to_string(),+ })+ .expect("apply Candle model config");+ }++ // SPLADE's `candle` profile extends `default`, which sets 8192.+ let budget =+ |model_id| ready_max_batch_tokens(&backend.runtime_defaults_for(model_id, None));+ assert_eq!(budget("prithivida/Splade_PP_en_v2:candle"), Some(8192));+ assert_eq!(budget("topk-io/Iso-ModernColBERT:candle"), Some(16384));+ assert_eq!(budget("unknown/model:candle"), None);+ }+#[test]fn encode_normalize_fallback_is_output_kind_aware() {assert!(!default_normalize(EncodeOutputKind::Sparse, true));diff --git a/packages/sie_server_rust/src/ipc_types.rs b/packages/sie_server_rust/src/ipc_types.rsindex 672b16781..491d9aa40 100644--- a/packages/sie_server_rust/src/ipc_types.rs+++ b/packages/sie_server_rust/src/ipc_types.rs@@ -130,6 +130,12 @@ pub struct EnsureModelReadyResponse {pub batch_budget: Option<u32>,#[serde(default)]pub descriptor: Option<ModelDescriptor>,+ /// The model's batch cost budget from its profile (`max_batch_tokens`).+ /// Only populated when `state == Ready`. The worker-sidecar sizes the+ /// model's batch cost cap and adaptive cost range from it, as it does+ /// for the Python server's `EnsureModelReadyResponse.max_batch_tokens`.+ #[serde(default)]+ pub max_batch_tokens: Option<u64>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -718,6 +724,31 @@ mod tests {assert_eq!(sparse.dims, Some(30_522));}+ #[test]+ fn ensure_ready_response_carries_max_batch_tokens_as_a_named_field() {+ let response = EnsureModelReadyResponse {+ state: ReadinessState::Ready,+ batch_budget: Some(64),+ descriptor: None,+ max_batch_tokens: Some(8192),+ };++ let bytes = rmp_serde::to_vec_named(&response).unwrap();+ let map: std::collections::BTreeMap<String, serde_json::Value> =+ rmp_serde::from_slice(&bytes).unwrap();+ assert_eq!(map["max_batch_tokens"].as_u64(), Some(8192));++ // A response without the field still decodes.+ let old_wire = rmp_serde::to_vec_named(&serde_json::json!({+ "state": "ready",+ "batch_budget": 64,+ "descriptor": null,+ }))+ .unwrap();+ let back: EnsureModelReadyResponse = rmp_serde::from_slice(&old_wire).unwrap();+ assert_eq!(back.max_batch_tokens, None);+ }+#[test]fn raw_output_without_sparse_field_remains_compatible() {let old_wire = rmp_serde::to_vec_named(&serde_json::json!({diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex 91c3bca7b..b8ec0cc69 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -520,10 +520,12 @@ canonical facade. It projects to `sie.worker.ipc.response.chunks` (outcomes`sie.worker.ipc.response.chunk.reserved`. The sidecar does not emit a secondPrometheus-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, `supports_run_batch`, and-`max_concurrent_dispatch` (the batches the backend runs through the model's+`EnsureModelReady` returns readiness state, an optional `ModelDescriptor`, and,+once the model is ready, its `max_batch_tokens`: the batch cost budget from the+model's profile, in the model's cost units (tokens for text, milliseconds for+audio). The descriptor carries tokenizer path, tokenizer content hash, maximum+sequence length, output types, default text templates, `supports_run_batch`,+and `max_concurrent_dispatch` (the batches the backend runs through the model'sadapter 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 NAKing@@ -543,20 +545,68 @@ request count, coalescing windows, adaptive pull timing, and model-specificscheduler state. Oversize items flush alone. Per-item outcomes are publishedwithout dropping the rest of the batch.+Each model's scheduler sizes its cost cap from the model's own+`max_batch_tokens`, as the Python worker does for its own batcher: the static+cost cap starts at that budget, and the adaptive cost range runs from+`min(max(256, budget / 4), budget)` to `4 * budget`. A speech model with a+720000 ms budget can therefore fill a clip batch up to the request count cap,+while a text model keeps its token budget. Precedence:++1. `SIE_BATCHER_MAX_BATCH_COST`, when set, pins the cap and the range for every+ model, as before per-model budgets.+2. Otherwise the budget `EnsureModelReady` reports for the model.+3. Otherwise, with a backend that does not report one, 16384.++`SIE_ADAPTIVE_BATCH_MIN_COST`, `SIE_ADAPTIVE_BATCH_MAX_COST`, and+`SIE_ADAPTIVE_BATCH_INITIAL_COST` still override the range for every model,+from its first batch on: the static cost cap starts at the adaptive+controller's starting cost, which is the budget unless one of them clamps it.+The request count cap and the hard audio duration cap per batch do not change.+When a ready model later reports a different budget, for example after the+backend restarts with a changed profile, its scheduler adopts the new budget+and restarts its adaptive controller.+Encode cost uses prepared-token length when available. Score tokenization staysbackend-owned, so its scheduler wrapper caches the same model-independent proxyas Python: Unicode character count plus 1024 per media input, summed once perquery/document pair. The cached score estimate never enters the IPC schema,never mutates or truncates inputs, and is not an authoritative token or billing-count. Extract currently uses unit cost.+count. Extract uses the prepared audio duration in milliseconds when the+sidecar decoded the item's audio, and unit cost otherwise.++Prepared audio longer than 30 s (Whisper's feature window) never shares a+batch, whatever the model. Such recordings are served one per batch in arrival+order, and while other items are pending too the two kinds take turns: a turn+of the other items, then the oldest long recording. A turn of other items+serves the items pending when it began, as one batch does in Python. The+request count cap (12 by default, against Python's 64) can split the turn into+several batches. Items that arrive during a turn wait for the next one. A turn+owes the items earlier turns left over: the oldest whatever its length, and+more of them, oldest first, while they fit the cost cap together. Its budget is+the cost cap plus the oldest one's cost, and it serves its other items+cheapest first with the rest, so a long left-over clip does not take the turn+from shorter ones. Short clips that keep arriving therefore cannot pass a+longer clip over turn after turn: every turn serves the oldest left-over item,+and an item is served within the first `n + 1` turns that begin after it+arrives, where `n` counts it and the older items still pending when the first+of them ended. Batches stay in cost order. Each batch keeps the request count+cap and the hard audio duration cap, and the cost cap unless it is a single+item above it, which runs alone. The turns run only while a long recording is+pending or has just run. Outside them, batches form as for every other model:+the oldest request that has waited out the batch window goes first, the rest by+cost. Inside a turn, nothing is promoted that way, because what the turn owes+already bounds each item's wait. The Python batcher applies the same rule, but+there only the Whisper adapter flags audio as long-form, a turn is always one+batch, and it is ordered by cost alone.The item cap (`SIE_BATCHER_MAX_BATCH_REQUESTS`, default 12) cuts a request ofmore 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 thatmany 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.+caps still cut. Like the aged promotion, it applies only outside the turns of+the long-recording lane. 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@@ -576,9 +626,12 @@ the other group's forward. The drain loop therefore asks the model's laneif it is already full (item cap, cost cap, one request over the cost cap, orno room under the cost cap for another item like its largest), becauseholding 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.+ with the engine, because its caller is waiting on that part. Beside a long+ recording, only the other items count toward full. A recording that is all+ that is pending is not full right after another recording: holding it lets+ the clips that arrive meanwhile take their turn first. 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 justanswered are the ones most likely to come straight back. The lane waits foras many arrivals as the returned batch answered. It stops waiting whendiff --git a/packages/sie_server_sidecar/src/audio_prep.rs b/packages/sie_server_sidecar/src/audio_prep.rsindex 5ef082b89..0aac92497 100644--- a/packages/sie_server_sidecar/src/audio_prep.rs+++ b/packages/sie_server_sidecar/src/audio_prep.rs@@ -13,6 +13,17 @@ pub use sie_audio_prep::msgpack::{AudioPreparation, PrepareAudioError};pub const MAX_AUDIO_BATCH_DURATION_MS: u64 = sie_audio_prep::DEFAULT_MAX_DURATION_MS;+/// Prepared audio with more samples than this is long-form: the scheduler+/// serves it in a batch of its own (see `HasCost::runs_alone`, #585).+///+/// The value is 30 s at the target sample rate, Whisper's feature window+/// (`WhisperFeatureExtractor.n_samples`). The Python batcher has the same lane,+/// but there only the Whisper adapter flags audio, through+/// `AudioPreprocessor(runs_alone_above_samples=feature_extractor.n_samples)`.+/// The sidecar applies the threshold to prepared audio for every model,+/// Parakeet included.+pub const RUNS_ALONE_ABOVE_SAMPLES: u64 = 30 * sie_audio_prep::TARGET_SAMPLE_RATE as u64;+/// Classify cheap pass-through inputs before the dispatcher acquires the/// bounded decode permit. Duplicate top-level audio fields are still rejected.pub fn classify_item(item: WireValue) -> Result<AudioPreparation, PrepareAudioError> {diff --git a/packages/sie_server_sidecar/src/backend/router.rs b/packages/sie_server_sidecar/src/backend/router.rsindex f74131024..7b8a60b94 100644--- a/packages/sie_server_sidecar/src/backend/router.rs+++ b/packages/sie_server_sidecar/src/backend/router.rs@@ -541,6 +541,7 @@ mod tests {state: ReadinessState::Ready,batch_budget: Some(32),descriptor: None,+ max_batch_tokens: None,})}async fn process_encode_batch(diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex 07035734b..b7c3ba11a 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -2679,7 +2679,9 @@ impl Dispatcher {//// Registry absent ⇒ legacy path unchanged. Only unit tests// exercise that branch today.- let scheduler_opt = self.resolve_scheduler(model_id).await;+ let scheduler_opt = self+ .resolve_scheduler(model_id, readiness_resp.max_batch_tokens)+ .await;let encode_fut = async {if encode_items.is_empty() {return Ok(());@@ -3831,13 +3833,21 @@ impl Dispatcher {/// old eager-at-startup `spawn_scheduler_drains`. Schedulers are/// now materialised only for active models that land on a sidecar/// worker, so boot does not need a model list to iterate.+ ///+ /// `model_max_batch_tokens` is the model's batch cost budget from the+ /// `EnsureModelReady` answer for this group; the registry sizes the+ /// scheduler's cost cap and adaptive range from it (see+ /// [`crate::scheduler::SchedulerRegistry::get_or_create`]).async fn resolve_scheduler(self: &Arc<Self>,model_id: &str,+ model_max_batch_tokens: Option<u64>,) -> Option<Arc<ProductionScheduler>> {let registry = self.scheduler_registry.as_ref()?;let shutdown = self.shutdown.as_ref()?;- let (sched, created) = registry.get_or_create(model_id).await;+ let (sched, created) = registry+ .get_or_create(model_id, model_max_batch_tokens)+ .await;if created {let mut handles = self.scheduler_drain_handles.lock().await;// Double-check under the lock: a concurrent `resolve_scheduler`@@ -6851,12 +6861,14 @@ mod tests {/// Reports `LoadingInProgress` for one model until `loaded` is set and/// `Ready` for every other model; records which models were encoded./// When `later_probe_delay` is set, every readiness call for the loading- /// model after the first takes that long.+ /// model after the first takes that long. Every readiness answer reports+ /// `max_batch_tokens` as the model's batch cost budget.struct LoadingModelBackend {loading_model: &'static str,loading_state: ReadinessState,loaded: AtomicBool,later_probe_delay: Option<Duration>,+ max_batch_tokens: Option<u64>,probes: std::sync::atomic::AtomicUsize,encoded_models: std::sync::Mutex<Vec<String>>,}@@ -6869,12 +6881,28 @@ mod tests {fn with_later_probe_delay(loading_model: &'static str,later_probe_delay: Option<Duration>,+ ) -> Arc<Self> {+ Self::build(loading_model, later_probe_delay, None)+ }++ fn with_max_batch_tokens(+ loading_model: &'static str,+ max_batch_tokens: Option<u64>,+ ) -> Arc<Self> {+ Self::build(loading_model, None, max_batch_tokens)+ }++ fn build(+ loading_model: &'static str,+ later_probe_delay: Option<Duration>,+ max_batch_tokens: Option<u64>,) -> Arc<Self> {Arc::new(Self {loading_model,loading_state: ReadinessState::LoadingInProgress,loaded: AtomicBool::new(false),later_probe_delay,+ max_batch_tokens,probes: std::sync::atomic::AtomicUsize::new(0),encoded_models: std::sync::Mutex::new(Vec::new()),})@@ -6913,6 +6941,7 @@ mod tests {state,batch_budget: None,descriptor: None,+ max_batch_tokens: self.max_batch_tokens,})}@@ -7104,6 +7133,7 @@ mod tests {state: ReadinessState::Ready,batch_budget: None,descriptor: None,+ max_batch_tokens: None,})}@@ -7672,6 +7702,7 @@ mod tests {max_concurrent_dispatch: *self.width.lock().unwrap(),..Default::default()}),+ max_batch_tokens: None,})}@@ -8751,6 +8782,39 @@ mod tests {assert!(retried_slots(&mut rx).is_empty());}+ #[tokio::test]+ async fn scheduler_takes_the_cost_budget_the_backend_reports_for_its_model() {+ for (reported, expected) in [(Some(720_000), 720_000), (None, 16_384)] {+ let backend = LoadingModelBackend::with_max_batch_tokens("cold", reported);+ let registry = Arc::new(ProductionSchedulerRegistry::new(+ crate::scheduler::BatchConfig::default(),+ ));+ let shutdown = Arc::new(Shutdown::new());+ let mut dispatcher = dispatcher_with_backend(backend.clone());+ let mutable = Arc::get_mut(&mut dispatcher).unwrap();+ mutable.scheduler_registry = Some(Arc::clone(®istry));+ mutable.shutdown = Some(Arc::clone(&shutdown));+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();++ dispatcher+ .dispatch_decoded(local_group("req", "warm", 0..2, &tx), 2, Instant::now())+ .await;++ let (sched, created) = registry.get_or_create("warm", None).await;+ assert!(!created, "the group created the model's scheduler");+ assert_eq!(sched.cost_budget(), expected, "reported {reported:?}");+ assert_eq!(+ sched.config().await.max_batch_cost,+ expected,+ "reported {reported:?}"+ );+ shutdown.fire();+ for handle in dispatcher.take_scheduler_drain_handles().await {+ handle.abort();+ }+ }+ }+#[test]fn releasing_cancelled_scheduled_item_clears_global_and_child_pressure() {let runtime_state = Arc::new(RuntimeState::new());@@ -9585,6 +9649,7 @@ mod tests {state: ReadinessState::Ready,batch_budget: None,descriptor: None,+ max_batch_tokens: None,})}diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex 7078e265d..c87a15909 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -441,17 +441,18 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {// traffic inside `Dispatcher::resolve_scheduler`; the shutdown// path below awaits every handle collected along the way so// final-drain windows have a chance to complete.+ //+ // BatchConfig pulls `SIE_BATCHER_*` overrides; the controller+ // (constructed lazily per model in `Scheduler::builder().build()`)+ // pulls `SIE_ADAPTIVE_BATCH_*` overrides — see the doc comments on+ // `BatchConfig::from_env_or_default` and+ // `AdaptiveBatchController::from_env_or_default` for the full list.+ // Each model's cost cap and adaptive cost range come from the+ // `max_batch_tokens` its backend reports with `EnsureModelReady`,+ // unless `SIE_BATCHER_MAX_BATCH_COST` pins them for every model+ // (see `SchedulerRegistry::from_env`).let scheduler_registry: Arc<crate::scheduler::ProductionSchedulerRegistry> =- Arc::new(crate::scheduler::ProductionSchedulerRegistry::new(- // BatchConfig pulls `SIE_BATCHER_*` overrides; the- // controller (constructed lazily per model in- // `Scheduler::builder().build()`) pulls- // `SIE_ADAPTIVE_BATCH_*` overrides — see the doc comments- // on `BatchConfig::from_env_or_default` and- // `AdaptiveBatchController::from_env_or_default` for the- // full list.- crate::scheduler::BatchConfig::from_env_or_default(),- ));+ Arc::new(crate::scheduler::ProductionSchedulerRegistry::from_env());info!("rust-scheduler: enabled for every model (per-model drain loops spawn on first traffic)");let config_apply_state = Arc::new(ConfigApplyState::new(config.bundle_config_hash.clone()));@@ -848,9 +849,7 @@ pub async fn run_local(config: WorkerConfig) -> anyhow::Result<()> {let tokenizer_registry = TokenizerRegistry::empty();let scheduler_registry: Arc<crate::scheduler::ProductionSchedulerRegistry> =- Arc::new(crate::scheduler::ProductionSchedulerRegistry::new(- crate::scheduler::BatchConfig::from_env_or_default(),- ));+ Arc::new(crate::scheduler::ProductionSchedulerRegistry::from_env());let config_apply_state = Arc::new(ConfigApplyState::new(config.bundle_config_hash.clone()));let loaded_models = config_apply_state.loaded_models();let health_publish_now = Arc::new(Notify::new());diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rsindex 30252febb..df47ee113 100644--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs@@ -317,6 +317,15 @@ pub struct EnsureModelReadyResponse {/// fallback policy.#[serde(default)]pub descriptor: Option<ModelDescriptor>,+ /// The model's batch cost budget from its profile (`max_batch_tokens`),+ /// in the model's cost units: tokens for text, milliseconds for audio.+ /// Mirrors `sie_server.ipc_types.EnsureModelReadyResponse.max_batch_tokens`;+ /// the Candle worker sends it too. Only populated when `state == Ready`.+ /// The scheduler sizes the model's cost cap and adaptive cost range from+ /// it; backends that do not send it leave the scheduler on its default+ /// budget.+ #[serde(default)]+ pub max_batch_tokens: Option<u64>,}// -----------------------------------------------------------------------------@@ -1318,6 +1327,41 @@ mod tests {assert_eq!(back, ReadinessState::Failed);}+ /// Encode an `EnsureModelReadyResponse` the way Python's msgspec does: a+ /// map of the fields it knows, so an older engine omits `max_batch_tokens`.+ fn ensure_ready_response_bytes(max_batch_tokens: Option<u64>) -> Vec<u8> {+ let mut buf = Vec::new();+ rmp::encode::write_map_len(&mut buf, 3 + u32::from(max_batch_tokens.is_some())).unwrap();+ rmp::encode::write_str(&mut buf, "state").unwrap();+ rmp::encode::write_str(&mut buf, "ready").unwrap();+ rmp::encode::write_str(&mut buf, "batch_budget").unwrap();+ rmp::encode::write_uint(&mut buf, 64).unwrap();+ rmp::encode::write_str(&mut buf, "descriptor").unwrap();+ rmp::encode::write_nil(&mut buf).unwrap();+ if let Some(value) = max_batch_tokens {+ rmp::encode::write_str(&mut buf, "max_batch_tokens").unwrap();+ rmp::encode::write_uint(&mut buf, value).unwrap();+ }+ buf+ }++ #[test]+ fn ensure_ready_response_without_max_batch_tokens_decodes_to_none() {+ let back: EnsureModelReadyResponse =+ rmp_serde::from_slice(&ensure_ready_response_bytes(None))+ .expect("a response from an engine without the field must decode");+ assert_eq!(back.state, ReadinessState::Ready);+ assert_eq!(back.batch_budget, Some(64));+ assert_eq!(back.max_batch_tokens, None);+ }++ #[test]+ fn ensure_ready_response_carries_max_batch_tokens() {+ let back: EnsureModelReadyResponse =+ rmp_serde::from_slice(&ensure_ready_response_bytes(Some(720_000))).unwrap();+ assert_eq!(back.max_batch_tokens, Some(720_000));+ }+#[test]fn disposition_serde_matches_python_literal() {let s = serde_json::to_string(&Disposition::PublishAndAck).unwrap();diff --git a/packages/sie_server_sidecar/src/scheduler/adaptive.rs b/packages/sie_server_sidecar/src/scheduler/adaptive.rsindex f533be988..dfebae04f 100644--- a/packages/sie_server_sidecar/src/scheduler/adaptive.rs+++ b/packages/sie_server_sidecar/src/scheduler/adaptive.rs@@ -224,7 +224,7 @@ impl AdaptiveBatchController {/// | `SIE_ADAPTIVE_BATCH_CALIBRATION_MULT` | `calibration_multiplier` | 1.5 | 1.5 |/// | `SIE_ADAPTIVE_BATCH_MAX_COST` | `max_batch_cost` | 65536 | `max(cost_floor, max_batch_tokens * 4)` |/// | `SIE_ADAPTIVE_BATCH_MIN_COST` | `min_batch_cost` | 256 | `max(256, max_batch_tokens / 4)` |- /// | `SIE_ADAPTIVE_BATCH_INITIAL_COST` | `initial_batch_cost` | 16384 | 16384 |+ /// | `SIE_ADAPTIVE_BATCH_INITIAL_COST` | `initial_batch_cost` | 16384 | `max_batch_tokens` |////// The production floor values are intentionally higher than the/// dataclass-style defaults used in small unit tests. Lower wait/cost@@ -340,6 +340,10 @@ impl AdaptiveBatchController {/// | `cost_gain` | `gain * 0.5` — coupled, not free |/// | `_current_batch_cost` | `max_batch_tokens` (default **16_384**) |///+ /// `max_batch_tokens` here is `cfg.max_batch_cost`: the model's own+ /// profile budget as the scheduler registry passes it, so each model+ /// gets its own cost range exactly as each Python `ModelWorker` does.+ ////// These production floors matter: deployed Python does not run the/// low module-level defaults. If Rust falls back to those bare/// values, the PI loop flushes tiny batches too eagerly under@@ -366,7 +370,9 @@ impl AdaptiveBatchController {c.initial_wait_ms = cfg.max_batch_wait_ms;// Cost-knob floor + ceiling are derived from the model's- // `max_batch_tokens` budget (= cfg.max_batch_cost in Rust).+ // `max_batch_tokens` budget (= cfg.max_batch_cost in Rust, which+ // the scheduler registry sets per model from the budget the+ // backend reports, unless `SIE_BATCHER_MAX_BATCH_COST` pins it).// Python's expression captured here verbatim.let max_batch_tokens = cfg.max_batch_cost;let cost_floor = u64::max(256, max_batch_tokens / PRODUCTION_MIN_COST_DIVISOR);@@ -398,8 +404,18 @@ impl AdaptiveBatchController {/// defaults plus operator env tuning in one shot.#[must_use]pub fn from_batch_config_and_env(cfg: &BatchConfig) -> Self {+ Self::from_batch_config_and_lookup(cfg, &|var| std::env::var(var).ok())+ }++ /// [`Self::from_batch_config_and_env`] reading the `SIE_ADAPTIVE_BATCH_*`+ /// overrides through `lookup`.+ #[must_use]+ pub fn from_batch_config_and_lookup(+ cfg: &BatchConfig,+ lookup: &dyn Fn(&str) -> Option<String>,+ ) -> Self {let mut c = Self::from_batch_config(cfg);- Self::apply_env_overrides(&mut c);+ Self::apply_env_overrides(&mut c, lookup);tracing::info!(min_wait_ms = c.min_wait_ms,@@ -419,10 +435,12 @@ impl AdaptiveBatchController {/// Apply `SIE_ADAPTIVE_BATCH_*` env-var overrides to an already/// constructed controller. Bad values log and fall through —- /// never crash.- fn apply_env_overrides(c: &mut Self) {- fn get_f64(var: &str) -> Option<f64> {- std::env::var(var).ok().and_then(|s| {+ /// never crash. `lookup` reads one variable; production passes the+ /// process environment, tests pass a fixed table so they never+ /// mutate the environment other tests read.+ fn apply_env_overrides(c: &mut Self, lookup: impl Fn(&str) -> Option<String>) {+ let get_f64 = |var: &str| -> Option<f64> {+ lookup(var).and_then(|s| {s.parse::<f64>().ok().filter(|v| v.is_finite()).or_else(|| {tracing::warn!(var = var,@@ -432,10 +450,9 @@ impl AdaptiveBatchController {None})})- }- fn get_u64(var: &str) -> Option<u64> {- std::env::var(var).ok().and_then(|s| s.parse::<u64>().ok())- }+ };+ let get_u64 =+ |var: &str| -> Option<u64> { lookup(var).and_then(|s| s.parse::<u64>().ok()) };if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_MAX_WAIT_MS") {c.max_wait_ms = v;@@ -1335,6 +1352,85 @@ mod tests {);}+ #[test]+ fn from_batch_config_derives_cost_range_from_each_model_budget() {+ // Python's `ModelWorker` per model budget `m`:+ // floor = min(max(256, m // 4), m), ceiling = max(floor, m * 4),+ // start = m.+ // 720000: audio models (ms). 16384: the default every model used+ // before per-model budgets. 4096 / 8192: VLM and cross-encoder+ // profiles. 1: one-document-per-batch extractors.+ for (budget, floor, ceiling) in [+ (720_000, 180_000, 2_880_000),+ (16_384, 4_096, 65_536),+ (8_192, 2_048, 32_768),+ (4_096, 1_024, 16_384),+ (1, 1, 4),+ ] {+ let cfg = BatchConfig {+ max_batch_cost: budget,+ ..BatchConfig::default()+ };+ let c = AdaptiveBatchController::from_batch_config(&cfg);+ assert_eq!(+ (c.min_batch_cost, c.max_batch_cost, c.initial_batch_cost),+ (floor, ceiling, budget),+ "budget {budget}"+ );+ assert_eq!(c.current_batch_cost, budget, "budget {budget}");+ }+ }++ #[test]+ fn adaptive_cost_env_overrides_apply_on_top_of_a_model_budget() {+ // An operator's `SIE_ADAPTIVE_BATCH_*_COST` keeps winning over the+ // range a model's budget derives, as it won over the 16384 range.+ let cfg = BatchConfig {+ max_batch_cost: 720_000,+ ..BatchConfig::default()+ };+ let env = |pairs: &'static [(&'static str, &'static str)]| {+ move |var: &str| {+ pairs+ .iter()+ .find(|(name, _)| *name == var)+ .map(|(_, value)| (*value).to_string())+ }+ };++ let mut c = AdaptiveBatchController::from_batch_config(&cfg);+ AdaptiveBatchController::apply_env_overrides(&mut c, env(&[]));+ assert_eq!(+ (c.min_batch_cost, c.max_batch_cost, c.current_batch_cost),+ (180_000, 2_880_000, 720_000)+ );++ let mut c = AdaptiveBatchController::from_batch_config(&cfg);+ AdaptiveBatchController::apply_env_overrides(+ &mut c,+ env(&[+ ("SIE_ADAPTIVE_BATCH_MIN_COST", "4096"),+ ("SIE_ADAPTIVE_BATCH_MAX_COST", "65536"),+ ("SIE_ADAPTIVE_BATCH_INITIAL_COST", "16384"),+ ]),+ );+ assert_eq!(+ (c.min_batch_cost, c.max_batch_cost, c.current_batch_cost),+ (4_096, 65_536, 16_384)+ );++ // A ceiling override alone still clamps the model's starting cost.+ let mut c = AdaptiveBatchController::from_batch_config(&cfg);+ AdaptiveBatchController::apply_env_overrides(+ &mut c,+ env(&[("SIE_ADAPTIVE_BATCH_MAX_COST", "100000")]),+ );+ assert_eq!(+ (c.min_batch_cost, c.max_batch_cost, c.current_batch_cost),+ (100_000, 100_000, 100_000)+ );+ }+#[test]fn from_batch_config_uses_cfg_max_batch_wait_ms() {// Operator who tunes `BatchConfig.max_batch_wait_ms` viadiff --git a/packages/sie_server_sidecar/src/scheduler/batch_config.rs b/packages/sie_server_sidecar/src/scheduler/batch_config.rsindex 6e88bc663..28e8f6fc2 100644--- a/packages/sie_server_sidecar/src/scheduler/batch_config.rs+++ b/packages/sie_server_sidecar/src/scheduler/batch_config.rs@@ -21,6 +21,19 @@//! are documented on [`BatchConfig::default`] and locked by the//! `defaults_diverge_from_python_intentionally` test below.+use std::sync::Arc;++/// Reads one environment variable. Production schedulers read the process+/// environment ([`process_env`]); tests pass a fixed table so they never+/// mutate the environment other tests read.+pub type EnvLookup = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;++/// [`EnvLookup`] over the process environment.+#[must_use]+pub fn process_env() -> EnvLookup {+ Arc::new(|var| std::env::var(var).ok())+}+/// Batch formation caps.////// Ported from `sie_server.core.batcher.BatchConfig`.@@ -67,7 +80,9 @@ pub struct BatchConfig {/// 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.+ /// batch to its longest row can be slower on the whole request. It does+ /// not apply inside the runs-alone lane's batchable turns or while a+ /// runs-alone item is pending (see `batch_former`'s module docs).pub max_request_items: usize,}@@ -84,7 +99,7 @@ impl BatchConfig {/// | Var | Field | Default | Notes |/// |-------------------------------------|----------------------|---------|-------|/// | `SIE_BATCHER_MAX_BATCH_WAIT_MS` | `max_batch_wait_ms` | 15.0 | Static flush-trigger ceiling — `AdaptiveBatchController` overwrites this on every step but the initial value matters during cold-start (see Python `core/batcher.py:BatchConfig`). |- /// | `SIE_BATCHER_MAX_BATCH_COST` | `max_batch_cost` | 16384 | Static cost cap initial value. |+ /// | `SIE_BATCHER_MAX_BATCH_COST` | `max_batch_cost` | 16384 | Static cost cap initial value. When set, it pins every model's cap and adaptive cost range; unset, each model uses its profile's `max_batch_tokens` (see [`crate::scheduler::SchedulerRegistry`]), else 16384. |/// | `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`. |@@ -94,10 +109,16 @@ impl BatchConfig {/// the default — never crash the registry init.#[must_use]pub fn from_env_or_default() -> Self {+ Self::from_lookup(&|var| std::env::var(var).ok())+ }++ /// [`Self::from_env_or_default`] reading variables through `lookup`.+ #[must_use]+ pub fn from_lookup(lookup: &dyn Fn(&str) -> Option<String>) -> Self {let mut c = Self::default();- fn get_f64(var: &str) -> Option<f64> {- std::env::var(var).ok().and_then(|s| {+ let get_f64 = |var: &str| -> Option<f64> {+ lookup(var).and_then(|s| {s.parse::<f64>().ok().filter(|v| v.is_finite()).or_else(|| {tracing::warn!(var = var,@@ -107,20 +128,13 @@ impl BatchConfig {None})})- }- fn get_u64(var: &str) -> Option<u64> {- std::env::var(var).ok().and_then(|s| s.parse::<u64>().ok())- }- fn get_usize(var: &str) -> Option<usize> {- std::env::var(var)- .ok()- .and_then(|s| s.parse::<usize>().ok())- }+ };+ let get_usize = |var: &str| -> Option<usize> { lookup(var).and_then(|s| s.parse().ok()) };if let Some(v) = get_f64("SIE_BATCHER_MAX_BATCH_WAIT_MS") {c.max_batch_wait_ms = v;}- if let Some(v) = get_u64("SIE_BATCHER_MAX_BATCH_COST") {+ if let Some(v) = Self::max_batch_cost_override(lookup) {c.max_batch_cost = v;}if let Some(v) = get_usize("SIE_BATCHER_MAX_BATCH_REQUESTS") {@@ -149,6 +163,19 @@ impl BatchConfig {c}+ /// The operator's static cost cap, `SIE_BATCHER_MAX_BATCH_COST`, when+ /// `lookup` finds it set to an unsigned integer.+ ///+ /// When present it wins over each model's own `max_batch_tokens`: the+ /// scheduler registry is then built cost-pinned and every model keeps+ /// this cap and the adaptive range derived from it, as before per-model+ /// budgets existed. Unparseable values are ignored, as in+ /// [`Self::from_env_or_default`].+ #[must_use]+ pub fn max_batch_cost_override(lookup: &dyn Fn(&str) -> Option<String>) -> Option<u64> {+ parse_max_batch_cost(lookup("SIE_BATCHER_MAX_BATCH_COST").as_deref())+ }+/// Effective coalesce window used by the batcher.////// Mirrors Python's@@ -171,6 +198,10 @@ impl BatchConfig {}}+fn parse_max_batch_cost(raw: Option<&str>) -> Option<u64> {+ raw.and_then(|s| s.parse::<u64>().ok())+}+impl Default for BatchConfig {/// Defaults: most fields mirror Python's `BatchConfig` line-for-line.///@@ -258,6 +289,45 @@ mod tests {assert!((c.effective_coalesce_ms() - 2.0).abs() < f64::EPSILON);}+ #[test]+ fn max_batch_cost_override_parses_only_unsigned_integers() {+ // Same acceptance as the `max_batch_cost` field of+ // `from_env_or_default`: anything else leaves the cap unpinned.+ assert_eq!(parse_max_batch_cost(Some("720000")), Some(720_000));+ assert_eq!(parse_max_batch_cost(Some("16384")), Some(16_384));+ assert_eq!(parse_max_batch_cost(None), None);+ assert_eq!(parse_max_batch_cost(Some("")), None);+ assert_eq!(parse_max_batch_cost(Some("-1")), None);+ assert_eq!(parse_max_batch_cost(Some("16k")), None);+ }++ #[test]+ fn from_lookup_reads_each_batcher_variable() {+ let lookup = |var: &str| -> Option<String> {+ match var {+ "SIE_BATCHER_MAX_BATCH_WAIT_MS" => Some("20".into()),+ "SIE_BATCHER_MAX_BATCH_COST" => Some("32768".into()),+ "SIE_BATCHER_MAX_BATCH_REQUESTS" => Some("64".into()),+ "SIE_BATCHER_COALESCE_MS" => Some("3".into()),+ "SIE_BATCHER_COALESCE_RATIO" => Some("NaN".into()),+ _ => None,+ }+ };+ assert_eq!(+ BatchConfig::from_lookup(&lookup),+ BatchConfig {+ max_batch_cost: 32_768,+ max_batch_requests: 64,+ max_batch_wait_ms: 20.0,+ coalesce_ms: 3.0,+ ..BatchConfig::default()+ }+ );+ assert_eq!(BatchConfig::max_batch_cost_override(&lookup), Some(32_768));+ assert_eq!(BatchConfig::from_lookup(&|_| None), BatchConfig::default());+ assert_eq!(BatchConfig::max_batch_cost_override(&|_| None), None);+ }+#[test]fn max_batch_tokens_alias() {let c = BatchConfig {diff --git a/packages/sie_server_sidecar/src/scheduler/batch_former.rs b/packages/sie_server_sidecar/src/scheduler/batch_former.rsindex ddc3357ab..ecb451d3e 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 Rust queue-path differences for-//! bounded waiting and timer refresh called out below:+//! its batching/packing contract, with the intentional Rust differences+//! called out below://!//! 1. **Flush triggers**: cost cap, count cap, `max_batch_wait_ms`//! timeout since the *first* item, or the coalesce window@@ -16,25 +16,100 @@//! 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.+//! an end-to-end latency guarantee. Nothing is promoted during a+//! batchable turn or while a runs-alone item is pending: there, what a+//! turn owes bounds the wait instead (point 5).//! 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+//! 5. **Runs-alone lane** (long-form audio, #585): items whose+//! [`HasCost::runs_alone`] is true never share a batch. They are served+//! one per batch in arrival order, and while batchable items are pending+//! too the two lanes take turns: a batchable turn, then the oldest flagged+//! item. A batchable turn serves the batchable items that were pending+//! when it began, in as many batches as the request count cap and drain+//! budgets need; items that arrive during the turn wait for the next one.+//! A turn begins after each flagged item runs, even if no other flagged+//! item is pending yet, so the items that waited behind it get a turn+//! before the next one. Before any batch has been taken, the first turn+//! goes to the lane holding the oldest pending item. Batchable batches+//! outside turns (none under way, nothing pending flagged, and the last+//! batch not a flagged item) are packed as points 3 and 6.+//!+//! What a turn takes: it owes the items earlier turns left over, the+//! oldest whatever its cost, then, oldest first, as many more as fit the+//! cost cap it began with together. Its budget is that cost cap plus the+//! oldest left-over item's cost. Besides what it owes, it takes the items+//! it serves cheapest first, while what is left of its budget still covers+//! what it owes and the next one fits. Until it has taken an item it does+//! not owe, it takes the cheapest one even above what is left, as point 2+//! takes an oversize item. Each batch is packed in cost order under the+//! cost cap, the request count cap and items' hard caps, a single item+//! above the cost cap running alone (point 2). Owed items join the batch+//! at which the next cheapest item would leave too little budget for them,+//! so a batch stops early only to keep that budget.+//!+//! Wait bound: every turn serves the oldest left-over item, and no later+//! arrival is older. So a batchable item is served by the first turn that+//! begins after it arrives or, if that turn leaves it over, within the+//! next `n` turns, where `n` counts it and the batchable items that+//! arrived before it and were still pending when that turn ended: at most+//! `n + 1` turns in all. Later arrivals never add to `n`, so cheaper items+//! that keep arriving cannot pass it over turn after turn. A turn takes at+//! most its cost cap plus two items: the oldest left-over one and the+//! cheapest other one. A flagged item still waits at most one turn per+//! flagged item ahead of it, plus one.+//!+//! The extra budget keeps the share of a turn that goes cheapest first at+//! no less than the cost cap minus what the other owed items cost, so a+//! costly left-over item, even one above the cost cap, does not take a+//! turn from the cheaper ones. Under a load the turns cannot keep up with,+//! owed items take most of each turn, in arrival order: no item waits+//! indefinitely and more items are served than in cost order alone, but+//! the median wait grows, most where the cost cap holds few items (such as+//! 4096 ms, the adaptive floor for a backend that reports no budget, or a+//! cap set low through `SIE_ADAPTIVE_BATCH_MAX_COST`). Point 3's+//! promotion makes the same trade between turns.+//! 6. **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.+//! cap still cuts. Like point 3's promotion, this applies only outside+//! batchable turns with nothing flagged pending: a turn's batches keep+//! the item cap and their cost order (point 5). 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//! 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. 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).+//! remains strictly cost-sorted; Rust promotes at most one aged request per+//! extract, outside batchable turns (points 3 and 5).+//!+//! The runs-alone lane (point 5) is the Python batcher's rule too (#601),+//! with three differences:+//!+//! * What gets flagged: Python flags audio only in the Whisper adapter, at+//! its feature window, while the sidecar flags every prepared audio item+//! longer than [`crate::audio_prep::RUNS_ALONE_ABOVE_SAMPLES`], whatever+//! the model, Parakeet included.+//! * How long a batchable turn lasts: Python's turn is one batch. Its request+//! count cap is 64, so in practice the cost cap bounds the turn. The+//! sidecar's count cap is 12 (see [`BatchConfig::default`]), and a turn of+//! one batch would then leave the costliest pending items behind every+//! turn, so they could wait indefinitely. The sidecar's turn takes what+//! Python's batch takes, bounded by the cost cap, split into batches that+//! respect the count cap.+//! * What a batchable turn serves: Python orders every turn by cost alone,+//! so cheaper items that keep arriving can pass a costlier one over turn+//! after turn. The sidecar's turn owes the items earlier turns left over,+//! which gives the wait bound of point 5.+//!+//! Caps and flush triggers otherwise follow the Python test contract. The+//! async primitives differ as expected (`tokio::sync` rather than asyncio).+use std::cmp::Reverse;+use std::collections::BinaryHeap;use std::marker::PhantomData;use std::sync::atomic::{AtomicU64, Ordering};use std::time::{Duration, Instant};@@ -61,6 +136,13 @@ pub trait HasCost {None}+ /// Whether this item must be served in a batch of its own (long-form+ /// audio). Mirrors Python's `PreparedItem.runs_alone`; see point 5 of+ /// the module docs for how such items are ordered.+ fn runs_alone(&self) -> bool {+ false+ }+/// Original position within the originating request's item list./// Used by the adapter-side output router to zip results back to/// the correct request item.@@ -182,12 +264,60 @@ struct Inner<I: HasCost, T> {total_cost: u64,first_request_time: Option<Instant>,last_submit_time: Option<Instant>,+ /// Lane of the last batch taken: `Some(true)` when it was a runs-alone+ /// item, `None` before the first batch. Decides whose turn is next while+ /// both lanes are pending.+ last_batch_alone: Option<bool>,+ /// The batchable turn under way, if any. See point 5 of the module docs.+ batchable_turn: Option<BatchableTurn>,+ /// Latest cutoff of a batchable turn begun so far. A pending batchable+ /// request that arrived no later than it was left over by an earlier turn.+ last_turn_cutoff: Option<Instant>,/// Cached snapshot of the current knobs. Mutations happen via/// [`BatchFormer::update_config`] which takes the same lock so/// reads of `config` and reads of `pending` stay consistent.config: BatchConfig,}+/// A batchable turn of the runs-alone lane (point 5 of the module docs). It+/// serves the batchable requests that were pending when it began. Of those,+/// it owes the ones earlier turns left over, oldest first, as many as fit its+/// cost cap together and at least the oldest, and serves them whatever their+/// place in cost order; the rest it serves cheapest first while its budget+/// lasts.+#[derive(Debug, Clone, Copy)]+struct BatchableTurn {+ /// Latest arrival among the requests pending when the turn began.+ /// Requests that arrive later wait for the next turn.+ cutoff: Instant,+ /// Latest arrival among the requests the turn owes, while it still owes+ /// any: a request the turn serves that arrived no later than this was+ /// left over by an earlier turn and is owed.+ owed_cutoff: Option<Instant>,+ /// Cost the turn may still take: the cost cap it began with plus the+ /// cost of the oldest request it owes, less what its batches took.+ cost_left: u64,+ /// Whether the turn has taken a request it does not owe. Until it has,+ /// it takes its cheapest such request even above `cost_left`, as the+ /// first batch of a turn takes an oversize item (point 2).+ took_unowed: bool,+}++impl BatchableTurn {+ /// Whether `request` is one of the batchable requests this turn serves.+ fn serves<I: HasCost, T>(&self, request: &PendingRequest<I, T>) -> bool {+ !request.item.runs_alone() && request.arrival_time <= self.cutoff+ }++ /// Whether `request` is one the turn owes.+ fn owes<I: HasCost, T>(&self, request: &PendingRequest<I, T>) -> bool {+ self.serves(request)+ && self+ .owed_cutoff+ .is_some_and(|owed| request.arrival_time <= owed)+ }+}+/// Async batch former.////// Thread-safe for concurrent submits from many tasks. A single@@ -230,6 +360,9 @@ impl<I: HasCost, T> BatchFormer<I, T> {total_cost: 0,first_request_time: None,last_submit_time: None,+ last_batch_alone: None,+ batchable_turn: None,+ last_turn_cutoff: None,config,}),ready: Notify::new(),@@ -404,9 +537,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. 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.+ /// item; outside a batchable turn (module docs, point 5), 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;@@ -480,7 +614,8 @@ 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.+ /// cannot improve such a batch. Beside runs-alone items, only the+ /// batchable items count (see `full_reason`).pub full: Option<FlushReason>,/// The classic flush trigger that has fired, if any (caps, batch wait,/// coalesce window since the last arrival).@@ -584,16 +719,46 @@ fn flush_reason<I: HasCost, T>(inner: &Inner<I, T>, immediate: bool) -> Option<F/// 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.+///+/// Beside a pending runs-alone item, only the batchable items count: a+/// runs-alone item never joins their batch (point 5), so a long recording+/// must not make a clip batch that could still grow look full. With only+/// runs-alone items pending, the next batch is the oldest of them. Right+/// after a runs-alone item it is not full: held while the engine is busy,+/// it lets the clips that arrive meanwhile take their turn first. After a+/// batchable batch it goes next whatever arrives, so the whole queue counts.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)+ let alone_pending = inner.pending.iter().any(|r| r.item.runs_alone());+ let batchable_pending = inner.pending.iter().any(|r| !r.item.runs_alone());+ if alone_pending && !batchable_pending && inner.last_batch_alone == Some(true) {+ return None;+ }+ let batchable_only = alone_pending && batchable_pending;+ let (mut count, mut total, mut largest) = (0usize, 0u64, 0u64);+ for request in inner+ .pending+ .iter()+ .filter(|r| !batchable_only || !r.item.runs_alone()){- return reason;+ let cost = request.item.cost();+ count += 1;+ total = total.saturating_add(cost);+ largest = largest.max(cost);}- 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)+ if count == 0 {+ return None;+ }+ let max_cost = effective_max_cost(inner);+ if count == 1 && total > max_cost {+ return Some(FlushReason::SingleOversize);+ }+ if total >= max_cost {+ return Some(FlushReason::CostCap);+ }+ if count >= inner.config.max_batch_requests {+ return Some(FlushReason::CountCap);+ }+ (total.saturating_add(largest) > max_cost).then_some(FlushReason::CostCap)}/// Time remaining until the next guaranteed flush, given current@@ -619,6 +784,231 @@ fn wait_timeout<I: HasCost, T>(inner: &Inner<I, T>) -> Option<Duration> {Some(Duration::try_from_secs_f64(effective_ms.max(0.0) / 1000.0).unwrap_or(Duration::MAX))}+/// Decide the lane of the next batch, keeping the batchable turn in step,+/// and order pending requests so that packing takes the batch from the front.+/// Returns `true` when the next batch is a runs-alone item.+///+/// Lane decision (point 5 of the module docs): a batchable turn under way+/// goes on while it owes a request, while a request it serves still fits+/// what is left of its budget, or, until it has taken a request it does not+/// owe, while it serves any. Otherwise, while both lanes are pending, the+/// lane that did not take the last batch goes next, and before the first+/// batch the lane holding the oldest pending request. A batchable turn opens+/// with the first batchable batch after a runs-alone item ran, even if no+/// other runs-alone item is pending yet, and with the first batchable batch+/// while runs-alone items are pending.+///+/// Order: batchable requests first, those the turn serves ahead of later+/// arrivals, each group sorted by cost; runs-alone requests after them in+/// arrival order, the oldest moved to the front when it is its turn. The sort+/// is stable, so FIFO order holds within equal costs (Python's `list.sort` is+/// stable too). Then [`make_room_for_owed`] moves the requests the turn owes+/// forward where packing would otherwise leave no room for them. Outside+/// batchable turns, with no runs-alone request pending, this is point 3: the+/// oldest request that has waited `max_batch_wait_ms` first, the rest by+/// cost. Mirrors Python's+/// `BatchFormer._order_runs_alone_lane`, except that a batchable turn can+/// span several batches and serves the requests earlier turns left over.+///+/// `max_cost` is the batch cost cap before the turn's own budget, and the+/// cost cap a turn opened now begins with; `max_take` is the most requests+/// the batch may take.+fn order_for_next_batch<I: HasCost, T>(+ inner: &mut Inner<I, T>,+ max_cost: u64,+ max_take: usize,+) -> bool {+ let alone_pending = inner.pending.iter().any(|r| r.item.runs_alone());+ let batchable_pending = inner.pending.iter().any(|r| !r.item.runs_alone());+ if let Some(turn) = inner.batchable_turn {+ // Owed requests always fit (see `make_room_for_owed`).+ let goes_on = |r: &PendingRequest<I, T>| {+ turn.serves(r) && (!turn.took_unowed || r.item.cost() <= turn.cost_left)+ };+ if !inner.pending.iter().any(goes_on) {+ inner.batchable_turn = None;+ }+ }+ let alone_next = alone_pending+ && (!batchable_pending+ || (inner.batchable_turn.is_none()+ && match inner.last_batch_alone {+ Some(last_alone) => !last_alone,+ None => inner+ .pending+ .iter()+ .min_by_key(|r| r.arrival_time)+ .is_some_and(|oldest| oldest.item.runs_alone()),+ }));+ if !alone_next+ && inner.batchable_turn.is_none()+ && (alone_pending || inner.last_batch_alone == Some(true))+ {+ let cutoff = inner+ .pending+ .iter()+ .map(|r| r.arrival_time)+ .max()+ .expect("batchable requests are pending");+ let (owed_cutoff, oldest_cost) =+ owed_left_over(&inner.pending, inner.last_turn_cutoff, max_cost);+ inner.batchable_turn = Some(BatchableTurn {+ cutoff,+ owed_cutoff,+ cost_left: max_cost.saturating_add(oldest_cost),+ took_unowed: false,+ });+ inner.last_turn_cutoff = inner.last_turn_cutoff.max(Some(cutoff));+ }++ // Outside batchable turns, with no runs-alone request pending, packing is+ // point 3's: a timeout must give the oldest request an extraction+ // opportunity even while cheaper arrivals keep the queue full. Inside a+ // turn, what the turn owes bounds the wait instead (point 5). Select+ // before sorting so tied arrival timestamps retain their pending order.+ let oldest_aged = if inner.batchable_turn.is_none() && !alone_pending {+ 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)+ } else {+ None+ };+ let promoted = oldest_aged.map(|index| inner.pending.remove(index));++ // Cost order keeps each batch's items close in length, minimising+ // padding waste on the adapter side.+ let turn = inner.batchable_turn;+ let served = |r: &PendingRequest<I, T>| turn.is_some_and(|t| t.serves(r));+ inner.pending.sort_by(|a, b| {+ let alone = a.item.runs_alone();+ alone+ .cmp(&b.item.runs_alone())+ .then_with(|| served(b).cmp(&served(a)))+ .then_with(|| {+ if alone {+ a.arrival_time.cmp(&b.arrival_time)+ } else {+ a.item.cost().cmp(&b.item.cost())+ }+ })+ });+ if let Some(request) = promoted {+ inner.pending.insert(0, request);+ }+ if alone_next {+ if let Some(head) = inner.pending.iter().position(|r| r.item.runs_alone()) {+ inner.pending[..=head].rotate_right(1);+ }+ } else if let Some(turn) = inner+ .batchable_turn+ .as_mut()+ .filter(|t| t.owed_cutoff.is_some())+ {+ let room = max_cost.min(turn.cost_left);+ if !make_room_for_owed(&mut inner.pending, turn, room, max_take) {+ turn.owed_cutoff = None;+ }+ }+ alone_next+}++/// The requests a turn opened now owes: of those that arrived no later than+/// `carried_cutoff` (left over by earlier turns), the oldest and, oldest+/// first, as many more as fit `max_cost` together with them. Requests that+/// arrived at the same instant are owed together. Returns the latest arrival+/// among the owed requests and the cost of the oldest ones, which the turn+/// adds to its budget.+fn owed_left_over<I: HasCost, T>(+ pending: &[PendingRequest<I, T>],+ carried_cutoff: Option<Instant>,+ max_cost: u64,+) -> (Option<Instant>, u64) {+ let Some(carried_cutoff) = carried_cutoff else {+ return (None, 0);+ };+ // A min-heap by arrival: only the owed few are popped, so a long queue+ // costs one linear pass rather than a sort.+ let mut left_over: BinaryHeap<Reverse<(Instant, u64)>> = pending+ .iter()+ .filter(|r| !r.item.runs_alone() && r.arrival_time <= carried_cutoff)+ .map(|r| Reverse((r.arrival_time, r.item.cost())))+ .collect();+ // Pops the next group of requests that arrived at the same instant.+ let mut next_group = || {+ let Reverse((arrival, mut cost)) = left_over.pop()?;+ while let Some(&Reverse((next, next_cost))) = left_over.peek() {+ if next != arrival {+ break;+ }+ cost += next_cost;+ left_over.pop();+ }+ Some((arrival, cost))+ };+ let Some((mut owed_cutoff, oldest_cost)) = next_group() else {+ return (None, 0);+ };+ let mut owed_cost = oldest_cost;+ while let Some((arrival, cost)) = next_group() {+ if owed_cost + cost > max_cost {+ break;+ }+ owed_cost += cost;+ owed_cutoff = arrival;+ }+ (Some(owed_cutoff), oldest_cost)+}++/// Makes sure packing leaves room for the requests `turn` owes. `pending`+/// holds the requests the turn serves first, sorted by cost. Packing takes+/// them in that order while each next one still leaves what is left of the+/// turn's budget enough for the owed requests not yet taken; at the first+/// one that would not, the owed requests move ahead of it, still in cost+/// order, and go next. The batch therefore stays in cost order, a request the+/// turn owes is never left over again, and packing stops only where the+/// cost cap `room`, the request count `max_take` or what the turn owes stops+/// it. Returns whether the turn still owes a pending request.+fn make_room_for_owed<I: HasCost, T>(+ pending: &mut [PendingRequest<I, T>],+ turn: &BatchableTurn,+ room: u64,+ max_take: usize,+) -> bool {+ let mut owes_any = false;+ let mut owed_left: u64 = 0;+ for request in pending.iter().filter(|r| turn.owes(r)) {+ owes_any = true;+ owed_left += request.item.cost();+ }+ if !owes_any {+ return false;+ }+ let served = pending.iter().take_while(|r| turn.serves(r)).count();+ let mut batch_cost: u64 = 0;+ for (count, at) in (0..served).enumerate() {+ let request = &pending[at];+ let cost = request.item.cost();+ if count >= max_take || (batch_cost + cost > room && count > 0) {+ break;+ }+ if turn.owes(request) {+ owed_left -= cost;+ } else if batch_cost + cost + owed_left > turn.cost_left {+ pending[at..served].sort_by_key(|r| !turn.owes(r));+ break;+ }+ batch_cost += cost;+ }+ true+}+fn extract_batch<I: HasCost, T>(inner: &mut Inner<I, T>,flush_reason: FlushReason,@@ -632,40 +1022,35 @@ 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 pending_before = inner.pending.len();+ let pending_alone = inner.pending.iter().filter(|r| r.item.runs_alone()).count();let max_cost = effective_max_cost(inner);let max_requests = inner.config.max_batch_requests;+ let max_take = max_items.min(max_requests).max(1);+ let alone_next = order_for_next_batch(inner, max_cost, max_take);++ // A batch of a batchable turn takes only requests the turn serves, within+ // what is left of the turn's budget.+ let turn = if alone_next {+ None+ } else {+ inner.batchable_turn+ };+ let max_cost = turn.map_or(max_cost, |t| max_cost.min(t.cost_left));// 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);+ // than `max_request_items` items is packed item by item as before. Only+ // outside batchable turns with nothing flagged pending (point 6): a+ // turn's batches keep the item cap and the order the turn set.+ let head_request_len = if !alone_next && turn.is_none() && pending_alone == 0 {+ bring_head_request_forward(inner)+ } else {+ 0+ };// Greedy pack. Always take at least one item so a single large// request (cost ≥ max_cost) doesn't starve.@@ -675,6 +1060,16 @@ fn extract_batch_up_to<I: HasCost, T>(if take_count >= max_items {break;}+ let runs_alone = req.item.runs_alone();+ // A runs-alone item never shares a batch: stop in front of one+ // unless it is the first item taken.+ if runs_alone && take_count > 0 {+ break;+ }+ // Requests that arrived during a batchable turn wait for the next.+ if turn.is_some_and(|t| !t.serves(req)) && take_count > 0 {+ break;+ }let c = req.item.cost();// Stop if taking this item would exceed the cost cap — but// only if we already have at least one item in the batch.@@ -686,14 +1081,38 @@ fn extract_batch_up_to<I: HasCost, T>(}batch_cost += c;take_count += 1;- if take_count >= max_requests && take_count >= head_request_len {+ if runs_alone || (take_count >= max_requests && take_count >= head_request_len) {break;}}+ let alone = take_count > 0 && inner.pending[0].item.runs_alone();+ if take_count > 0 {+ // Whose turn is next when both lanes are pending.+ inner.last_batch_alone = Some(alone);+ if alone {+ inner.batchable_turn = None;+ } else if let Some(turn) = inner.batchable_turn.as_mut() {+ let snapshot = *turn;+ turn.took_unowed |= inner.pending[..take_count]+ .iter()+ .any(|r| !snapshot.owes(r));+ turn.cost_left = turn.cost_left.saturating_sub(batch_cost);+ }+ }// Drain the taken prefix into parallel vecs.let drained: Vec<PendingRequest<I, T>> = inner.pending.drain(..take_count).collect();inner.total_cost -= batch_cost;+ tracing::debug!(+ flush_reason = flush_reason.as_label(),+ lane = if alone { "alone" } else { "batched" },+ batch_size = take_count,+ total_cost = batch_cost,+ pending = pending_before,+ pending_alone,+ remaining = inner.pending.len(),+ "scheduler batch formed",+ );let mut items = Vec::with_capacity(drained.len());let mut metadata = Vec::with_capacity(drained.len());@@ -1571,6 +1990,9 @@ mod tests {total_cost: 1,first_request_time: Some(now - Duration::from_millis(5)),last_submit_time: Some(now),+ last_batch_alone: None,+ batchable_turn: None,+ last_turn_cutoff: None,config: cfg,};let t = wait_timeout(&inner).expect("pending → Some");@@ -1596,6 +2018,9 @@ mod tests {total_cost: 1,first_request_time: Some(now),last_submit_time: Some(now),+ last_batch_alone: None,+ batchable_turn: None,+ last_turn_cutoff: None,config: cfg,};assert_eq!(wait_timeout(&inner), Some(Duration::MAX));@@ -1609,6 +2034,9 @@ mod tests {total_cost: 0,first_request_time: None,last_submit_time: None,+ last_batch_alone: None,+ batchable_turn: None,+ last_turn_cutoff: None,config: cfg,};assert!(wait_timeout(&inner).is_none());@@ -1625,4 +2053,1308 @@ mod tests {};assert!((cfg.effective_coalesce_ms() - 2.0).abs() < f64::EPSILON);}++ // ---- Runs-alone lane (long-form audio, #585) ----++ /// Audio stub: cost is duration in ms and the hard cap is the audio batch+ /// cap, as `SchedulerItem` sets them for prepared audio. `alone` marks+ /// long-form audio.+ #[derive(Debug, Clone, Copy)]+ struct LaneItem {+ cost: u64,+ alone: bool,+ hard_cap: Option<u64>,+ request: Option<&'static str>,+ }++ impl HasCost for LaneItem {+ fn cost(&self) -> u64 {+ self.cost+ }+ fn hard_batch_cost_cap(&self) -> Option<u64> {+ self.hard_cap+ }+ fn runs_alone(&self) -> bool {+ self.alone+ }+ fn original_index(&self) -> usize {+ 0+ }+ fn request_key(&self) -> Option<&str> {+ self.request+ }+ }++ fn clip_ms(cost: u64) -> LaneItem {+ LaneItem {+ cost,+ alone: false,+ hard_cap: Some(crate::audio_prep::MAX_AUDIO_BATCH_DURATION_MS),+ request: None,+ }+ }++ fn long_form_ms(cost: u64) -> LaneItem {+ LaneItem {+ alone: true,+ ..clip_ms(cost)+ }+ }++ fn clip(seconds: u64) -> LaneItem {+ clip_ms(seconds * 1_000)+ }++ fn long_form(seconds: u64) -> LaneItem {+ long_form_ms(seconds * 1_000)+ }++ /// A batcher queue driven with explicit arrival times, in ms after `epoch`.+ struct Lanes {+ inner: Inner<LaneItem, String>,+ epoch: Instant,+ }++ impl Lanes {+ fn new(max_batch_cost: u64) -> Self {+ Self {+ inner: Inner {+ pending: Vec::new(),+ total_cost: 0,+ first_request_time: None,+ last_submit_time: None,+ last_batch_alone: None,+ batchable_turn: None,+ last_turn_cutoff: None,+ config: BatchConfig {+ max_batch_cost,+ // Arrival times here are simulated, while point 3's+ // aging reads the real clock: keep it out of reach+ // unless a test opts in (see `Lanes::aged`).+ max_batch_wait_ms: f64::INFINITY,+ ..BatchConfig::default()+ },+ },+ epoch: Instant::now(),+ }+ }++ /// Like [`Lanes::new`], but every request counts as having waited+ /// `max_batch_wait_ms`, so point 3's aged promotion applies wherever+ /// it may.+ fn aged(max_batch_cost: u64) -> Self {+ let mut lanes = Self::new(max_batch_cost);+ lanes.inner.config.max_batch_wait_ms = 0.0;+ lanes+ }++ fn with_aging(max_batch_cost: u64, aged: bool) -> Self {+ if aged {+ Self::aged(max_batch_cost)+ } else {+ Self::new(max_batch_cost)+ }+ }++ /// Queue `item` as if it arrived `at_ms` after the epoch.+ fn arrive(&mut self, item: LaneItem, name: &str, at_ms: u64) {+ append_item(&mut self.inner, item, name.to_string());+ let request = self.inner.pending.last_mut().expect("just appended");+ request.arrival_time = self.epoch + Duration::from_millis(at_ms);+ }++ fn take_up_to(&mut self, max_items: usize) -> FormattedBatch<LaneItem, String> {+ extract_batch_up_to(&mut self.inner, FlushReason::Drain, max_items)+ }++ fn take(&mut self) -> Vec<String> {+ self.take_up_to(usize::MAX).metadata+ }++ fn pending_names(&self) -> Vec<String> {+ self.inner+ .pending+ .iter()+ .map(|request| request.metadata.clone())+ .collect()+ }+ }++ /// SplitMix64: reproducible test data without a `rand` dependency.+ struct TestRng(u64);++ impl TestRng {+ fn next_u64(&mut self) -> u64 {+ self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);+ let mut z = self.0;+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ z ^ (z >> 31)+ }++ /// Uniform in `low..=high`.+ fn range(&mut self, low: u64, high: u64) -> u64 {+ low + self.next_u64() % (high - low + 1)+ }++ fn chance(&mut self, percent: u64) -> bool {+ self.range(0, 99) < percent+ }++ fn pick<T: Copy>(&mut self, choices: &[T]) -> T {+ choices[self.range(0, choices.len() as u64 - 1) as usize]+ }+ }++ /// Greedy packing exactly as `extract_batch_up_to` does without the+ /// runs-alone lane and with whole requests off (points 3 and 6): with+ /// `aged`, every request has waited out the batch window, so the oldest+ /// goes first and the rest by cost; otherwise all by cost. `pending`+ /// holds `(cost, hard_cap, name, arrival_ms)` in queue order and is+ /// updated in place, as the batcher updates its own queue.+ fn previous_packing(+ pending: &mut Vec<(u64, Option<u64>, String, u64)>,+ config: &BatchConfig,+ max_items: usize,+ aged: bool,+ ) -> (Vec<String>, u64) {+ let oldest = aged+ .then(|| {+ pending+ .iter()+ .enumerate()+ .min_by_key(|(_, (_, _, _, arrival))| *arrival)+ .map(|(index, _)| index)+ })+ .flatten();+ let promoted = oldest.map(|index| pending.remove(index));+ pending.sort_by_key(|(cost, _, _, _)| *cost);+ if let Some(request) = promoted {+ pending.insert(0, request);+ }+ let max_cost = pending+ .iter()+ .filter_map(|(_, cap, _, _)| *cap)+ .fold(config.max_batch_cost, u64::min);+ let mut batch_cost = 0;+ let mut take_count = 0;+ for (cost, _, _, _) in pending.iter() {+ if take_count >= max_items {+ break;+ }+ if batch_cost + cost > max_cost && take_count > 0 {+ break;+ }+ batch_cost += cost;+ take_count += 1;+ if take_count >= config.max_batch_requests {+ break;+ }+ }+ let taken = pending.drain(..take_count).map(|(_, _, name, _)| name);+ (taken.collect(), batch_cost)+ }++ #[test]+ fn unflagged_batches_match_previous_cost_sorted_packing() {+ for (seed, aged) in (0..20).flat_map(|seed| [(seed, false), (seed, true)]) {+ let mut rng = TestRng(seed);+ let mut lanes = Lanes::with_aging(rng.range(1, 4_000), aged);+ lanes.inner.config.max_batch_requests = rng.range(1, 8) as usize;+ let config = lanes.inner.config;+ let mut reference: Vec<(u64, Option<u64>, String, u64)> = Vec::new();+ let mut now_ms = 0;+ let mut next_id = 0;++ for _ in 0..60 {+ for _ in 0..rng.range(0, 5) {+ now_ms += rng.range(0, 3);+ let cost = rng.range(1, 1_500);+ let hard_cap = rng.chance(20).then(|| rng.range(500, 4_000));+ let name = format!("item-{next_id}");+ next_id += 1;+ let item = LaneItem {+ cost,+ alone: false,+ hard_cap,+ request: None,+ };+ lanes.arrive(item, &name, now_ms);+ reference.push((cost, hard_cap, name, now_ms));+ }+ if reference.is_empty() {+ continue;+ }+ let max_items = rng.pick(&[usize::MAX, usize::MAX, 1, 2, 5]);++ let batch = lanes.take_up_to(max_items);++ let (expected, expected_cost) =+ previous_packing(&mut reference, &config, max_items, aged);+ assert_eq!(batch.metadata, expected, "seed {seed}, aged {aged}");+ assert_eq!(batch.total_cost, expected_cost, "seed {seed}, aged {aged}");+ let remaining: Vec<&String> =+ reference.iter().map(|(_, _, name, _)| name).collect();+ assert_eq!(+ lanes.pending_names().iter().collect::<Vec<_>>(),+ remaining,+ "seed {seed}, aged {aged}"+ );+ let remaining_cost: u64 = reference.iter().map(|(cost, _, _, _)| cost).sum();+ assert_eq!(+ lanes.inner.total_cost, remaining_cost,+ "seed {seed}, aged {aged}"+ );+ }+ }+ }++ #[test]+ fn long_form_runs_alone_after_clips_that_arrived_around_it() {+ // Clips are not held in a long recording's batch (head-of-line wait).+ let mut lanes = Lanes::new(720_000);+ lanes.arrive(clip(5), "clip-5s", 0);+ lanes.arrive(long_form(240), "long-240s", 1_000);+ lanes.arrive(clip(8), "clip-8s", 2_000);++ assert_eq!(lanes.take(), ["clip-5s", "clip-8s"]);+ assert_eq!(lanes.take(), ["long-240s"]);+ assert!(lanes.inner.pending.is_empty());+ assert_eq!(lanes.inner.total_cost, 0);+ }++ #[test]+ fn long_form_items_run_in_arrival_order() {+ // An older long recording is not starved by a newer, shorter one.+ let mut lanes = Lanes::new(720_000);+ lanes.arrive(long_form(250), "long-250s", 0);+ lanes.arrive(long_form(190), "long-190s", 1_000);++ assert_eq!(lanes.take(), ["long-250s"]);+ assert_eq!(lanes.take(), ["long-190s"]);+ }++ #[test]+ fn first_batch_comes_from_the_lane_of_the_oldest_request() {+ for (long_arrival_ms, order) in [(0, ["long", "clip"]), (2_000, ["clip", "long"])] {+ let mut lanes = Lanes::new(720_000);+ lanes.arrive(clip(5), "clip", 1_000);+ lanes.arrive(long_form(240), "long", long_arrival_ms);++ let first = lanes.take();+ let second = lanes.take();+ assert_eq!([first, second].concat(), order);+ }+ }++ #[test]+ fn lanes_take_turns_while_both_are_pending() {+ // Two long recordings and clips that keep arriving: clips, long, clips, long.+ let mut lanes = Lanes::new(720_000);+ lanes.arrive(clip(4), "clip-a", 0);+ lanes.arrive(clip(6), "clip-b", 1_000);+ lanes.arrive(long_form(240), "long-1", 2_000);+ lanes.arrive(long_form(200), "long-2", 3_000);++ let mut served = Vec::new();+ for second in 4..9 {+ served.push(lanes.take());+ // One clip lands while each batch runs.+ lanes.arrive(clip(5), &format!("clip@{second}"), second * 1_000);+ }++ assert_eq!(+ served,+ [+ vec!["clip-a", "clip-b"],+ vec!["long-1"],+ vec!["clip@4", "clip@5"],+ vec!["long-2"],+ vec!["clip@6", "clip@7"],+ ]+ );+ assert_eq!(lanes.pending_names(), ["clip@8"]);+ }++ /// What a closed-loop run served: per client, how many requests were+ /// served and the most clip turns one of them waited. A request waits one+ /// turn when the first clip turn that begins after it arrives serves it.+ struct ClosedLoopTurns {+ served: Vec<usize>,+ worst_wait_turns: Vec<usize>,+ clip_turns: usize,+ }++ /// Extracts `batches` batches from `lanes`, whose pending requests are+ /// named by client index; every served client resubmits its item at once.+ /// Clip turns are counted as runs of clip batches, so this needs a long+ /// recording pending throughout: then every clip turn is followed by one.+ fn closed_loop_turns(+ lanes: &mut Lanes,+ clients: &[LaneItem],+ batches: usize,+ now_ms: &mut u64,+ ) -> ClosedLoopTurns {+ let mut run = ClosedLoopTurns {+ served: vec![0; clients.len()],+ worst_wait_turns: vec![0; clients.len()],+ clip_turns: 0,+ };+ // Clip turns begun before each pending client's request arrived.+ let mut turns_at_submit = vec![0; clients.len()];+ let mut last_alone = None;+ for _ in 0..batches {+ assert!(+ lanes.inner.pending.iter().any(|r| r.item.alone),+ "a long recording stays pending"+ );+ let batch = lanes.take_up_to(usize::MAX);+ let alone = batch.items[0].alone;+ if !alone && last_alone != Some(false) {+ run.clip_turns += 1;+ }+ last_alone = Some(alone);+ *now_ms += 1;+ for name in &batch.metadata {+ let client: usize = name.parse().expect("client index");+ run.served[client] += 1;+ if !alone {+ let waited = run.clip_turns - turns_at_submit[client];+ run.worst_wait_turns[client] = run.worst_wait_turns[client].max(waited);+ }+ turns_at_submit[client] = run.clip_turns;+ lanes.arrive(clients[client], name, *now_ms);+ }+ }+ // Requests still pending have waited at least the turns begun since.+ for request in &lanes.inner.pending {+ let client: usize = request.metadata.parse().expect("client index");+ let waited = run.clip_turns - turns_at_submit[client];+ run.worst_wait_turns[client] = run.worst_wait_turns[client].max(waited);+ }+ run+ }++ #[test]+ fn aged_recording_waits_while_a_clip_turn_is_under_way() {+ // Every request has waited out the batch window, so outside clip+ // turns the oldest would go first (point 3). A clip turn still serves+ // the clips that waited behind the last recording before the next+ // recording runs, however long that recording has waited.+ let mut lanes = Lanes::aged(720_000);+ lanes.arrive(long_form(60), "first-recording", 0);+ lanes.arrive(long_form(60), "second-recording", 1);+ lanes.arrive(clip(10), "clip", 2);++ assert_eq!(lanes.take(), ["first-recording"]);+ assert_eq!(lanes.take(), ["clip"]);+ assert_eq!(lanes.take(), ["second-recording"]);+ }++ #[test]+ fn aged_promotion_resumes_once_the_turn_after_the_last_recording_ends() {+ // The clip turn after the last recording serves its clips cheapest+ // first, like every clip turn, and leaves the 20 s clip over. Once+ // that turn ends and nothing flagged is pending, packing is point 3's+ // again: the 20 s clip, now the oldest request, goes before a cheaper+ // clip that arrived since.+ let mut lanes = Lanes::aged(10_000);+ lanes.arrive(long_form(60), "recording", 0);+ lanes.arrive(clip(20), "long-clip", 1);+ lanes.arrive(clip(5), "short-clip-1", 2);+ lanes.arrive(clip(5), "short-clip-2", 3);++ assert_eq!(lanes.take(), ["recording"]);+ assert_eq!(lanes.take(), ["short-clip-1", "short-clip-2"]);+ lanes.arrive(clip(1), "late-clip", 4);+ assert_eq!(lanes.take(), ["long-clip"]);+ assert_eq!(lanes.take(), ["late-clip"]);++ // Without aging, cost order alone would keep passing the 20 s clip+ // over.+ let mut lanes = Lanes::new(10_000);+ lanes.arrive(clip(20), "long-clip", 1);+ lanes.arrive(clip(1), "late-clip", 4);+ assert_eq!(lanes.take(), ["late-clip"]);+ }++ #[test]+ fn whole_requests_keep_the_item_cap_inside_a_clip_turn() {+ // A request of four clips arrives behind a recording, with whole+ // requests on and an item cap of 2. The clip turn after the+ // recording keeps the item cap (point 6). With nothing flagged+ // pending and no turn under way, the same request leaves whole.+ let request = |seconds| LaneItem {+ request: Some("four-clips"),+ ..clip(seconds)+ };+ let mut lanes = Lanes::new(720_000);+ lanes.inner.config.max_batch_requests = 2;+ lanes.inner.config.max_request_items = 64;+ lanes.arrive(long_form(60), "recording", 0);+ for (name, seconds) in [("a", 4), ("b", 3), ("c", 2), ("d", 1)] {+ lanes.arrive(request(seconds), name, 1);+ }+ assert_eq!(lanes.take(), ["recording"]);+ assert_eq!(lanes.take(), ["d", "c"]);+ assert_eq!(lanes.take(), ["b", "a"]);++ let mut lanes = Lanes::new(720_000);+ lanes.inner.config.max_batch_requests = 2;+ lanes.inner.config.max_request_items = 64;+ for (name, seconds) in [("a", 4), ("b", 3), ("c", 2), ("d", 1)] {+ lanes.arrive(request(seconds), name, 1);+ }+ assert_eq!(lanes.take(), ["d", "c", "b", "a"]);+ }++ #[test]+ fn clip_left_over_by_a_turn_is_served_by_the_next_turn() {+ // At a speech model's adaptive floor (180000 ms), 18 clips of 10 s+ // fill a clip turn's cost cap, and their clients resubmit at once. The+ // 30 s clip, costliest, is left over by its first turn. The next turn+ // owes it, so the 10 s clips that arrived since cannot pass it over+ // again; that turn's budget grows by its 30 s, so it still serves all+ // 18 of them. A long recording still runs after every clip turn.+ let mut lanes = Lanes::new(180_000);+ let mut clients = vec![long_form_ms(240_000), clip_ms(30_000)];+ clients.extend([clip_ms(10_000); 18]);+ let mut now_ms = 0;+ for (client, item) in clients.iter().enumerate() {+ lanes.arrive(*item, &client.to_string(), now_ms);+ now_ms += 1;+ }++ let run = closed_loop_turns(&mut lanes, &clients, 300, &mut now_ms);++ // One recording, then 100 rounds of a clip turn of two batches and a+ // recording, the last round cut short by the 300-batch horizon.+ assert_eq!(run.clip_turns, 100);+ assert_eq!(run.served[0], 100, "a recording runs after every clip turn");+ assert_eq!(run.worst_wait_turns[0], 1);+ // The 30 s clip's client resubmits during a turn, so each request has+ // a first turn that leaves it over and is served by the next.+ assert_eq!(run.served[1], 50, "the 30 s clip is served every 2 turns");+ assert_eq!(run.worst_wait_turns[1], 2);+ for client in 2..clients.len() {+ assert_eq!(run.served[client], 100, "10 s clip client {client}");+ assert_eq!(run.worst_wait_turns[client], 1, "10 s clip client {client}");+ }+ }++ #[test]+ fn turn_batches_stay_in_cost_order_and_full_around_owed_clips() {+ // Two costly clips are left over by a turn. The next turn owes the+ // older one (L1); the other (L2) does not fit the cost cap with it,+ // so it is served cheapest first like the newer 5 s clips. Its first+ // batch takes the 5 s clips and L2, in cost order, and stops only at+ // the cost cap; L1 follows in the same turn, before the next+ // recording. Arrival-order leaders would instead stop the first batch+ // at L2 and take three batches.+ let mut lanes = Lanes::new(180_000);+ lanes.arrive(long_form(240), "r0", 0);+ lanes.arrive(clip_ms(100_000), "L1", 1);+ lanes.arrive(clip_ms(90_000), "L2", 2);+ lanes.arrive(long_form(240), "r1", 3);+ lanes.arrive(long_form(240), "r2", 4);+ for i in 0..9 {+ lanes.arrive(clip(20), &format!("m{i}"), 5 + i);+ }+ assert_eq!(lanes.take(), ["r0"]);+ let turn_1: Vec<String> = (0..9).map(|i| format!("m{i}")).collect();+ assert_eq!(lanes.take(), turn_1, "20 s clips fill the cost cap");+ assert_eq!(lanes.take(), ["r1"]);+ for i in 0..10 {+ lanes.arrive(clip(5), &format!("s{i}"), 100 + i);+ }++ let mut first: Vec<String> = (0..10).map(|i| format!("s{i}")).collect();+ first.push("L2".into());+ assert_eq!(lanes.take(), first);+ assert_eq!(lanes.take(), ["L1"]);+ assert_eq!(lanes.take(), ["r2"]);+ assert!(lanes.inner.pending.is_empty());+ }++ #[test]+ fn oversize_left_over_clip_runs_alone_beside_the_turn() {+ // At 16384 ms (the cost cap for a backend that reports no budget) a+ // 20 s clip runs alone. Left over, it is owed by the next turn, whose+ // budget grows by its cost, so the 2 s clips still get the turn's+ // whole cost cap instead of losing the turn to it.+ let mut lanes = Lanes::new(16_384);+ lanes.arrive(long_form(240), "r0", 0);+ lanes.arrive(clip(20), "big", 1);+ lanes.arrive(long_form(240), "r1", 2);+ for i in 0..8 {+ lanes.arrive(clip(2), &format!("a{i}"), 3 + i);+ }+ assert_eq!(lanes.take(), ["r0"]);+ let turn_1: Vec<String> = (0..8).map(|i| format!("a{i}")).collect();+ assert_eq!(lanes.take(), turn_1, "8 clips of 2 s fit 16384 ms");+ assert_eq!(lanes.take(), ["r1"]);+ lanes.arrive(long_form(240), "r2", 50);+ for i in 0..8 {+ lanes.arrive(clip(2), &format!("b{i}"), 100 + i);+ }++ let turn_2: Vec<String> = (0..8).map(|i| format!("b{i}")).collect();+ assert_eq!(lanes.take(), turn_2, "the cheaper clips keep the cost cap");+ assert_eq!(lanes.take(), ["big"], "the owed clip runs alone");+ assert_eq!(lanes.take(), ["r2"]);+ }++ #[test]+ fn clip_left_over_before_the_last_recording_is_owed_after_it() {+ // The batch after the last recording opens a turn although nothing+ // flagged is pending any more, so a clip left over before it is still+ // owed: cheaper clips that arrive during that turn wait for the next+ // one, while plain cost-sorted packing (point 3) would take them+ // ahead of it.+ let mut lanes = Lanes::new(180_000);+ lanes.arrive(clip(30), "x", 0);+ for i in 0..18 {+ lanes.arrive(clip(10), &format!("c{i}"), 1 + i);+ }+ lanes.arrive(long_form(240), "r", 100);+ assert_eq!(lanes.take().len(), 12);+ assert_eq!(lanes.take().len(), 6);+ assert_eq!(lanes.pending_names(), ["x", "r"]);+ assert_eq!(lanes.take(), ["r"]);++ for i in 0..12 {+ lanes.arrive(clip(1), &format!("n{i}"), 200 + i);+ }+ let n: Vec<String> = (0..12).map(|i| format!("n{i}")).collect();+ assert_eq!(lanes.take(), n, "the request count cap splits the turn");+ for i in 0..12 {+ lanes.arrive(clip(1), &format!("k{i}"), 300 + i);+ }+ assert_eq!(lanes.take(), ["x"], "the turn still owes x");+ let k: Vec<String> = (0..12).map(|i| format!("k{i}")).collect();+ assert_eq!(lanes.take(), k);+ }++ #[test]+ fn long_form_amid_steady_clips_waits_for_one_clip_batch() {+ // Clip traffic that never lets up delays a flagged recording just+ // over 30 s by one clip batch, not for as long as clips keep coming.+ let mut lanes = Lanes::new(720_000);+ lanes.arrive(long_form(240), "long-240s", 0);+ assert_eq!(lanes.take(), ["long-240s"]);++ // A clip and a 31 s recording land while long-240s runs, and one more+ // clip lands while each later batch runs.+ lanes.arrive(clip(4), "clip@1", 1_000);+ lanes.arrive(long_form(31), "long-31s", 2_000);+ let mut served = Vec::new();+ for second in 3..7 {+ lanes.arrive(clip(4), &format!("clip@{second}"), second * 1_000);+ served.push(lanes.take());+ }++ assert_eq!(+ served,+ [+ vec!["clip@1", "clip@3"],+ vec!["long-31s"],+ vec!["clip@4", "clip@5"],+ vec!["clip@6"],+ ]+ );+ }++ #[tokio::test]+ async fn try_drain_takes_turns_and_keeps_counts_consistent() {+ let b = BatchFormer::<LaneItem, &str>::new(BatchConfig {+ max_batch_cost: 720_000,+ ..BatchConfig::default()+ });+ b.submit_many(vec![+ (clip(5), "clip-5s"),+ (long_form(240), "long-240s"),+ (clip(8), "clip-8s"),+ (long_form(200), "long-200s"),+ (clip(3), "clip-3s"),+ ])+ .await;++ // A drain budget of one item cuts the first clip turn short; the+ // turn goes on with the clips it began with before long-240s runs,+ // while a clip that lands meanwhile waits for the next turn.+ let expected: [(usize, &[&str], usize, u64); 5] = [+ (1, &["clip-3s"], 4, 453_000),+ (4, &["clip-5s", "clip-8s"], 3, 441_000),+ (2, &["long-240s"], 2, 201_000),+ (usize::MAX, &["clip-1s"], 1, 200_000),+ (usize::MAX, &["long-200s"], 0, 0),+ ];+ for (step, (max_items, names, pending_count, pending_cost)) in+ expected.into_iter().enumerate()+ {+ if step == 1 {+ tsleep(TDuration::from_millis(2)).await;+ b.submit(clip(1), "clip-1s").await;+ }+ let batch = b.try_drain_up_to(max_items).await.expect("work is pending");+ assert_eq!(batch.metadata, names, "step {step}");+ assert_eq!(+ batch.total_cost,+ batch.items.iter().map(|item| item.cost).sum::<u64>()+ );+ assert_eq!(b.pending_count().await, pending_count, "step {step}");+ assert_eq!(b.pending_cost().await, pending_cost, "step {step}");+ }+ assert!(b.try_drain().await.is_none());+ assert!(b.first_request_time().await.is_none());+ assert_eq!(b.fcfs_head_ns(), 0);+ }++ #[tokio::test]+ async fn runs_alone_batch_keeps_flush_reason_and_reanchors_timers() {+ let b = BatchFormer::<LaneItem, &str>::new(BatchConfig {+ max_batch_cost: 16_384,+ max_batch_wait_ms: 10_000.0,+ coalesce_ms: 10_000.0,+ coalesce_ratio: 1.0,+ ..BatchConfig::default()+ });+ b.submit(long_form(240), "long").await;+ // Keep the two arrivals distinct so the long recording is the oldest.+ tsleep(TDuration::from_millis(2)).await;+ b.submit(clip(5), "clip").await;+ let clip_arrival = b.inner.lock().await.pending[1].arrival_time;++ // 245 s pending reaches the cost cap; the oldest request's lane goes first.+ let batch = b.try_get_batch().await.expect("cost cap should trigger");+ assert_eq!(batch.metadata, ["long"]);+ assert_eq!(batch.flush_reason, FlushReason::CostCap);+ {+ let guard = b.inner.lock().await;+ assert_eq!(guard.first_request_time, Some(clip_arrival));+ assert_eq!(guard.last_submit_time, Some(clip_arrival));+ }+ assert_ne!(b.fcfs_head_ns(), 0, "the clip stays visible to FCFS");+ assert!(+ b.try_get_batch().await.is_none(),+ "the clip waits for its own window"+ );+ }++ /// What a closed-loop run measured: completion latencies, in ms, of clips+ /// and of long recordings. Requests still pending at the end count as+ /// waiting until then.+ struct ClosedLoopLatency {+ clips: Vec<u64>,+ recordings: Vec<u64>,+ }++ impl ClosedLoopLatency {+ fn worst_clip_ms(&self) -> u64 {+ self.clips.iter().copied().max().unwrap_or(0)+ }++ fn worst_recording_ms(&self) -> u64 {+ self.recordings.iter().copied().max().unwrap_or(0)+ }++ fn median_clip_ms(&self) -> u64 {+ let mut clips = self.clips.clone();+ clips.sort_unstable();+ clips[clips.len() / 2]+ }+ }++ /// Closed-loop clients keep one request each in flight on one speech+ /// model served one batch at a time with the cost cap `max_batch_cost`,+ /// for 30 minutes.+ ///+ /// Clips are 2-30 s and mostly short; recordings are 240 s and take+ /// 11.3 s of GPU time each; a clip batch takes 0.3 s plus 0.12 s per+ /// clip. Some extracts are cut short by a drain's item budget, as the+ /// dispatcher's continuation waves do.+ fn closed_loop_latency(+ clip_clients: usize,+ long_clients: usize,+ seed: u64,+ max_batch_cost: u64,+ ) -> ClosedLoopLatency {+ const HORIZON_MS: u64 = 1_800_000;+ let mut rng = TestRng(seed);+ let mut lanes = Lanes::new(max_batch_cost);+ let total = clip_clients + long_clients;+ // Next submit time per client; a client is idle while its request is pending.+ let mut next_submit: Vec<Option<u64>> =+ (0..total).map(|client| Some(client as u64)).collect();+ let mut submitted_at = vec![0u64; total];+ let mut run = ClosedLoopLatency {+ clips: Vec::new(),+ recordings: Vec::new(),+ };+ let mut now_ms = 0u64;+ while now_ms < HORIZON_MS {+ for client in 0..total {+ if next_submit[client].is_some_and(|at| at <= now_ms) {+ let at = next_submit[client].take().expect("checked above");+ let item = if client < clip_clients {+ let seconds = match rng.range(0, 99) {+ 0..=79 => rng.range(2, 10),+ 80..=92 => rng.range(10, 20),+ _ => rng.range(20, 30),+ };+ clip(seconds)+ } else {+ long_form(240)+ };+ lanes.arrive(item, &client.to_string(), at);+ submitted_at[client] = at;+ }+ }+ if lanes.inner.pending.is_empty() {+ now_ms = next_submit+ .iter()+ .flatten()+ .copied()+ .min()+ .expect("a client is idle");+ continue;+ }+ let max_items = rng.pick(&[usize::MAX, usize::MAX, usize::MAX, 1, 3]);+ let batch = lanes.take_up_to(max_items);+ now_ms += if batch.items[0].alone {+ 11_300+ } else {+ 300 + 120 * batch.size() as u64+ };+ for name in &batch.metadata {+ let client: usize = name.parse().expect("client index");+ let latency = now_ms - submitted_at[client];+ if client < clip_clients {+ run.clips.push(latency);+ } else {+ run.recordings.push(latency);+ }+ next_submit[client] = Some(now_ms + rng.range(1, 50));+ }+ }+ for request in &lanes.inner.pending {+ let client: usize = request.metadata.parse().expect("client index");+ let waited = now_ms - submitted_at[client];+ if client < clip_clients {+ run.clips.push(waited);+ } else {+ run.recordings.push(waited);+ }+ }+ run+ }++ #[test]+ fn closed_loop_clips_and_recordings_are_served_within_a_few_turns() {+ // More clips pend at a clip turn than the request count cap (12)+ // takes in one batch. A turn still serves every clip that was+ // pending when it began, so the longest clips are not passed over+ // turn after turn, and recordings keep their turns.+ for (clip_clients, long_clients) in [(16, 4), (16, 1), (32, 4), (48, 4)] {+ for seed in 0..3 {+ let run = closed_loop_latency(clip_clients, long_clients, seed, 720_000);+ let case =+ format!("{clip_clients} clip / {long_clients} long clients, seed {seed}");+ let (clip_ms, long_ms) = (run.worst_clip_ms(), run.worst_recording_ms());+ assert!(clip_ms < 60_000, "{case}: a clip waited {clip_ms} ms");+ assert!(long_ms < 120_000, "{case}: a recording waited {long_ms} ms");+ }+ }+ }++ #[test]+ fn closed_loop_clips_are_served_at_the_adaptive_floor_too() {+ // At a speech model's adaptive floor (180000 ms) a clip turn takes a+ // quarter of what it takes at 720000 ms, so a turn leaves clips over+ // whenever those pending add up to more than 180 s. The next turn+ // owes them, so the costliest clips are not passed over turn after+ // turn by the clips their clients resubmit. Without that, with 32 or+ // more clip clients a clip waited most of the 30-minute run.+ for (clip_clients, long_clients) in [(16, 4), (16, 1), (32, 4), (48, 4)] {+ for seed in 0..3 {+ let run = closed_loop_latency(clip_clients, long_clients, seed, 180_000);+ let case =+ format!("{clip_clients} clip / {long_clients} long clients, seed {seed}");+ let (clip_ms, long_ms) = (run.worst_clip_ms(), run.worst_recording_ms());+ assert!(clip_ms < 90_000, "{case}: a clip waited {clip_ms} ms");+ assert!(long_ms < 120_000, "{case}: a recording waited {long_ms} ms");+ }+ }+ }++ #[test]+ fn closed_loop_at_small_cost_caps_bounds_waits_and_keeps_short_clips_quick() {+ // A cost cap below the longer clips: 16384 ms, the cap for a backend+ // that reports no budget, and 4096 ms, its adaptive floor. Clips+ // above the cap run alone, and the load is more than the lanes can+ // serve. Cost-first packing alone then served the costliest clips+ // only when nothing cheaper was pending, so some waited the whole+ // 30-minute run. Serving every left-over clip first instead served+ // clips in about arrival order, so most waited minutes. Owing the+ // oldest left-over clips, with the turn's budget raised by the+ // oldest one's cost, bounds every wait and keeps cheaper clips first+ // otherwise: at 16384 ms the median clip stays within seconds of+ // what cost-first packing gives.+ for (clip_clients, long_clients) in [(16, 4), (32, 4), (48, 4)] {+ for seed in 0..3 {+ let case =+ format!("{clip_clients} clip / {long_clients} long clients, seed {seed}");+ let run = closed_loop_latency(clip_clients, long_clients, seed, 16_384);+ let (worst, median) = (run.worst_clip_ms(), run.median_clip_ms());+ assert!(+ worst < 600_000,+ "{case}, 16384 ms: a clip waited {worst} ms"+ );+ assert!(median < 60_000, "{case}, 16384 ms: median clip {median} ms");+ assert!(+ run.clips.len() > 450,+ "{case}, 16384 ms: {} clips",+ run.clips.len()+ );++ let run = closed_loop_latency(clip_clients, long_clients, seed, 4_096);+ let worst = run.worst_clip_ms();+ assert!(worst < 900_000, "{case}, 4096 ms: a clip waited {worst} ms");+ assert!(+ run.clips.len() > 280,+ "{case}, 4096 ms: {} clips",+ run.clips.len()+ );+ }+ }+ }++ /// The batchable turn the audit sees under way.+ struct AuditTurn {+ /// Turns begun so far, this one included.+ index: usize,+ /// The clips it may still serve, by name with their cost.+ clips: std::collections::HashMap<String, u64>,+ /// The clips it owes and has not served yet, by name with their cost.+ owed: std::collections::HashMap<String, u64>,+ /// What is left of its budget.+ cost_left: u64,+ /// Whether it has taken a clip it does not owe.+ took_unowed: bool,+ }++ /// A pending clip that a turn's cutoff covered.+ struct AuditClip {+ arrival: Instant,+ /// The first turn whose cutoff covered it.+ first_turn: usize,+ /// The turn by which it must be served, set when its first turn+ /// leaves it over: the first turn's index plus the number of clips,+ /// itself included, that arrived no later than it and were still+ /// pending then (point 5 of the module docs).+ serve_by: Option<usize>,+ }++ /// Checks each extract against the lane rules (point 5 of the module+ /// docs) and the per-batch caps while a randomized load runs.+ #[derive(Default)]+ struct LaneAudit {+ served: Vec<String>,+ last_alone: Option<bool>,+ turn: Option<AuditTurn>,+ turns_begun: usize,+ /// Turns that began with clips left over by an earlier turn pending.+ turns_with_left_over: usize,+ /// Pending clips that a turn's cutoff covered, by name.+ clips: std::collections::HashMap<String, AuditClip>,+ /// Pending flagged item -> (flagged items ahead of it on arrival,+ /// clip turns begun since it arrived).+ flagged_waits: std::collections::HashMap<String, (usize, usize)>,+ }++ impl LaneAudit {+ /// Takes one batch of at most `max_items` and returns its names.+ fn extract(&mut self, lanes: &mut Lanes, max_items: usize) -> Vec<String> {+ // Every stub carries the hard audio cap.+ let max_cost = lanes+ .inner+ .config+ .max_batch_cost+ .min(crate::audio_prep::MAX_AUDIO_BATCH_DURATION_MS);+ let max_requests = lanes.inner.config.max_batch_requests;+ let pending: Vec<(String, bool, u64, Instant)> = lanes+ .inner+ .pending+ .iter()+ .map(|r| {+ (+ r.metadata.clone(),+ r.item.alone,+ r.item.cost,+ r.arrival_time,+ )+ })+ .collect();+ let batch = lanes.take_up_to(max_items);+ assert!(batch.size() > 0 && batch.size() <= max_items.min(max_requests));+ assert!(+ batch.total_cost <= max_cost || batch.size() == 1,+ "a batch of {} items costs {} ms, over the {max_cost} ms cap",+ batch.size(),+ batch.total_cost+ );+ let alone = batch.items[0].alone;+ assert!(+ batch.items.iter().all(|item| item.alone == alone),+ "lanes never share a batch"+ );+ let alone_pending = pending.iter().any(|(_, a, _, _)| *a);+ let clips_pending = pending.iter().any(|(_, a, _, _)| !*a);++ // A turn is over once none of its clips fits what is left of its+ // budget, or, before it has taken a clip it does not owe, once+ // none is pending.+ if let Some(turn) = &self.turn {+ let goes_on = pending.iter().any(|(name, _, cost, _)| {+ turn.clips.contains_key(name) && (!turn.took_unowed || *cost <= turn.cost_left)+ });+ if !goes_on {+ self.end_turn(&pending);+ }+ }+ if alone_pending && clips_pending {+ // The lanes take turns, starting with the lane of the oldest request.+ let expected = self.turn.is_none()+ && self.last_alone.map_or_else(+ || pending.iter().min_by_key(|r| r.3).unwrap().1,+ |last| !last,+ );+ assert_eq!(alone, expected, "lane of the next batch");+ }++ if alone {+ assert_eq!(batch.size(), 1, "a flagged item runs alone");+ let oldest = pending.iter().filter(|r| r.1).min_by_key(|r| r.3).unwrap();+ assert_eq!(+ batch.metadata[0], oldest.0,+ "flagged items run in arrival order"+ );+ let (ahead, clip_turns) = self+ .flagged_waits+ .remove(&batch.metadata[0])+ .expect("flagged item was pending");+ assert!(+ clip_turns <= ahead + 1,+ "{clip_turns} clip turns with {ahead} ahead"+ );+ assert!(self.turn.is_none(), "a flagged item runs between turns");+ } else {+ if self.turn.is_none() && (alone_pending || self.last_alone == Some(true)) {+ self.begin_turn(&pending, max_cost);+ }+ if let Some(turn) = &mut self.turn {+ Self::check_turn_batch(turn, &batch, max_cost, max_items.min(max_requests));+ }+ }+ for name in &batch.metadata {+ self.clips.remove(name);+ }+ self.last_alone = Some(alone);+ self.served.extend(batch.metadata.iter().cloned());+ batch.metadata+ }++ /// Checks a batch of the turn under way and books it to the turn.+ fn check_turn_batch(+ turn: &mut AuditTurn,+ batch: &FormattedBatch<LaneItem, String>,+ max_cost: u64,+ max_take: usize,+ ) {+ for name in &batch.metadata {+ assert!(+ turn.clips.contains_key(name),+ "{name}: a turn serves only the clips pending when it began"+ );+ }+ let costs: Vec<u64> = batch.items.iter().map(|item| item.cost).collect();+ assert!(+ costs.windows(2).all(|pair| pair[0] <= pair[1]),+ "a turn's batch is in cost order: {costs:?}"+ );+ // Clips the turn does not owe go cheapest first.+ let unowed = |name: &String| !turn.owed.contains_key(name);+ let dearest_taken = batch+ .metadata+ .iter()+ .filter(|n| unowed(n))+ .map(|n| turn.clips[n])+ .max();+ let cheapest_left = turn+ .clips+ .iter()+ .filter(|(name, _)| unowed(name) && !batch.metadata.contains(name))+ .map(|(_, cost)| *cost)+ .min();+ if let (Some(taken), Some(left)) = (dearest_taken, cheapest_left) {+ assert!(+ taken <= left,+ "took a {taken} ms clip before a {left} ms one"+ );+ }+ // Within what is left of the budget, except for a single clip the+ // turn owes or, before it has taken a clip it does not owe, the+ // cheapest such clip.+ let owed_taken = batch+ .metadata+ .iter()+ .filter(|n| turn.owed.contains_key(*n))+ .count();+ assert!(+ batch.total_cost <= turn.cost_left+ || (batch.size() == 1 && (owed_taken == 1 || !turn.took_unowed)),+ "turn batch of {} ms with {} ms left",+ batch.total_cost,+ turn.cost_left+ );+ let room = max_cost+ .min(turn.cost_left)+ .saturating_sub(batch.total_cost);+ for name in &batch.metadata {+ turn.clips.remove(name);+ turn.owed.remove(name);+ }+ turn.took_unowed |= owed_taken < batch.size();+ turn.cost_left = turn.cost_left.saturating_sub(batch.total_cost);+ let owed_left: u64 = turn.owed.values().sum();+ assert!(+ owed_left <= turn.cost_left,+ "the turn keeps room for the {owed_left} ms it owes"+ );+ // A batch stops short of its request limit only where no clip the+ // turn could still take fits.+ if batch.size() < max_take {+ for (name, cost) in &turn.clips {+ let fits = *cost <= room+ && (turn.owed.contains_key(name) || cost + owed_left <= turn.cost_left);+ assert!(+ !fits,+ "a batch of {} stopped with {name} ({cost} ms) still fitting",+ batch.size()+ );+ }+ }+ }++ /// A turn begins: it serves the clips pending now and owes those that+ /// earlier turns left over: the oldest (and any that arrived at the+ /// same instant), then oldest first as many as fit its cost cap+ /// together. Its budget is the cost cap plus the oldest ones' cost.+ fn begin_turn(&mut self, pending: &[(String, bool, u64, Instant)], max_cost: u64) {+ self.turns_begun += 1;+ let index = self.turns_begun;+ for (name, clip) in &self.clips {+ if let Some(serve_by) = clip.serve_by {+ assert!(+ index <= serve_by,+ "{name} is still pending at turn {index}, past turn {serve_by}"+ );+ }+ }+ if !self.clips.is_empty() {+ self.turns_with_left_over += 1;+ }+ let mut left_over: Vec<(Instant, &String, u64)> = pending+ .iter()+ .filter(|r| !r.1 && self.clips.contains_key(&r.0))+ .map(|r| (r.3, &r.0, r.2))+ .collect();+ left_over.sort();+ let mut owed = std::collections::HashMap::new();+ let (mut owed_cost, mut extra) = (0, 0);+ for group in left_over.chunk_by(|a, b| a.0 == b.0) {+ let cost: u64 = group.iter().map(|&(_, _, cost)| cost).sum();+ if owed.is_empty() {+ extra = cost;+ } else if owed_cost + cost > max_cost {+ break;+ }+ owed_cost += cost;+ owed.extend(group.iter().map(|&(_, name, cost)| (name.clone(), cost)));+ }+ let mut clips = std::collections::HashMap::new();+ for (name, _, cost, arrival) in pending.iter().filter(|r| !r.1) {+ clips.insert(name.clone(), *cost);+ self.clips.entry(name.clone()).or_insert(AuditClip {+ arrival: *arrival,+ first_turn: index,+ serve_by: None,+ });+ }+ for wait in self.flagged_waits.values_mut() {+ wait.1 += 1;+ }+ self.turn = Some(AuditTurn {+ index,+ clips,+ owed,+ cost_left: max_cost + extra,+ took_unowed: false,+ });+ }++ /// The turn under way is over: it served everything it owed. Set the+ /// bound of each clip it was the first turn of and left over.+ fn end_turn(&mut self, pending: &[(String, bool, u64, Instant)]) {+ let turn = self.turn.take().expect("a turn is under way");+ assert!(+ turn.owed.is_empty(),+ "turn {} ended owing {:?}",+ turn.index,+ turn.owed.keys().collect::<Vec<_>>()+ );+ let arrivals: Vec<Instant> = pending.iter().filter(|r| !r.1).map(|r| r.3).collect();+ for clip in self.clips.values_mut() {+ if clip.first_turn == turn.index {+ let ahead = arrivals.iter().filter(|a| **a <= clip.arrival).count();+ clip.serve_by = Some(turn.index + ahead);+ }+ }+ }+ }++ #[test]+ fn lanes_never_mix_and_take_turns_at_any_cost_cap() {+ // The default adaptive cost range (4096-65536 ms) and its 16384 ms+ // start, for backends that report no budget; a speech model's floor+ // (180000 ms) and its 720000 ms start, which is also the hard audio+ // cap.+ // Each runs with and without point 3's aged promotion, which applies+ // only between clip turns while nothing flagged is pending.+ let caps = [4_096, 16_384, 65_536, 180_000, 720_000];+ for (max_batch_cost, aged) in caps.into_iter().flat_map(|cap| [(cap, false), (cap, true)]) {+ let mut rng = TestRng(max_batch_cost);+ let mut lanes = Lanes::with_aging(max_batch_cost, aged);+ let mut audit = LaneAudit::default();+ let mut submitted = Vec::new();+ let mut now_ms = 0;++ for index in 0..300 {+ now_ms += rng.range(1, 2_000);+ if rng.chance(60) {+ let name = format!("item-{index}");+ let item = if rng.chance(30) {+ let ahead = audit.flagged_waits.len();+ audit.flagged_waits.insert(name.clone(), (ahead, 0));+ long_form_ms(rng.range(30_001, 300_000))+ } else {+ clip_ms(rng.range(1_000, 30_000))+ };+ lanes.arrive(item, &name, now_ms);+ submitted.push(name);+ }+ if !lanes.inner.pending.is_empty() && rng.chance(50) {+ let max_items = rng.pick(&[usize::MAX, 1, 3]);+ audit.extract(&mut lanes, max_items);+ }+ }+ while !lanes.inner.pending.is_empty() {+ let max_items = rng.pick(&[usize::MAX, 1, 3]);+ audit.extract(&mut lanes, max_items);+ }++ audit.served.sort();+ submitted.sort();+ assert_eq!(audit.served, submitted, "cap {max_batch_cost}, aged {aged}");+ assert!(audit.flagged_waits.is_empty());+ assert_eq!(lanes.inner.total_cost, 0);+ }+ }++ /// Queues `item` one ms after the previous arrival, under a fresh name+ /// that starts with `kind`.+ fn arrive_next(+ lanes: &mut Lanes,+ audit: &mut LaneAudit,+ item: LaneItem,+ kind: &str,+ now_ms: &mut u64,+ ) {+ *now_ms += 1;+ let name = format!("{kind}-{now_ms}");+ if item.alone {+ let ahead = audit.flagged_waits.len();+ audit.flagged_waits.insert(name.clone(), (ahead, 0));+ }+ lanes.arrive(item, &name, *now_ms);+ }++ #[test]+ fn every_clip_is_served_within_its_turn_bound_under_replenishment() {+ // Long recordings stay pending throughout (their clients resubmit at+ // once), so clip turns never stop. Clip clients resubmit at once too,+ // and one-off bursts add more clips. Clips cost up to 30 s, above the+ // cap at the lower caps; drain budgets cut some batches short, and the+ // cost cap moves between batches as the adaptive controller moves it.+ // The audit checks every batch against the caps and the lane rules,+ // and every clip against its bound: a clip its first turn leaves over+ // is served by the turn numbered that turn plus the clips, itself+ // included, that arrived no later than it and were still pending then.+ // Recordings stay pending, so every batch belongs to a clip turn or a+ // recording, and point 3's aged promotion never applies: the aged+ // runs must match the others batch for batch.+ let caps = [4_096, 16_384, 65_536, 180_000, 720_000];+ let mut turns_with_left_over = 0;+ let mut unaged_served = Vec::new();+ for (seed, aged) in (0..24).flat_map(|seed| [(seed, false), (seed, true)]) {+ let mut rng = TestRng(1_000 + seed);+ let mut lanes = Lanes::with_aging(rng.pick(&caps), aged);+ let mut audit = LaneAudit::default();+ let mut now_ms = 0;+ for _ in 0..rng.range(1, 3) {+ let item = long_form_ms(rng.range(30_001, 300_000));+ arrive_next(&mut lanes, &mut audit, item, "recording", &mut now_ms);+ }+ for _ in 0..rng.range(4, 48) {+ let item = clip_ms(rng.range(1_000, 30_000));+ arrive_next(&mut lanes, &mut audit, item, "client", &mut now_ms);+ }++ for _ in 0..400 {+ if rng.chance(10) {+ lanes.inner.config.max_batch_cost = rng.pick(&caps);+ }+ if rng.chance(10) {+ for _ in 0..rng.range(1, 8) {+ let item = clip_ms(rng.range(1_000, 30_000));+ arrive_next(&mut lanes, &mut audit, item, "burst", &mut now_ms);+ }+ }+ let max_items = rng.pick(&[usize::MAX, usize::MAX, 1, 3, 5]);+ for name in audit.extract(&mut lanes, max_items) {+ if name.starts_with("recording") {+ let item = long_form_ms(rng.range(30_001, 300_000));+ arrive_next(&mut lanes, &mut audit, item, "recording", &mut now_ms);+ } else if name.starts_with("client") {+ let item = clip_ms(rng.range(1_000, 30_000));+ arrive_next(&mut lanes, &mut audit, item, "client", &mut now_ms);+ }+ }+ }+ assert!(+ audit.turns_begun >= 70,+ "seed {seed}, aged {aged}: clip turns keep coming"+ );+ turns_with_left_over += audit.turns_with_left_over;+ if aged {+ assert_eq!(audit.served, unaged_served, "seed {seed}");+ } else {+ unaged_served = audit.served;+ }+ }+ assert!(+ turns_with_left_over >= 3_000,+ "the load leaves clips over: {turns_with_left_over} turns began with some"+ );+ }}diff --git a/packages/sie_server_sidecar/src/scheduler/engine.rs b/packages/sie_server_sidecar/src/scheduler/engine.rsindex 7000ef15d..4780c7e4e 100644--- a/packages/sie_server_sidecar/src/scheduler/engine.rs+++ b/packages/sie_server_sidecar/src/scheduler/engine.rs@@ -48,7 +48,7 @@ use tokio::sync::{Mutex, Notify, RwLock};use crate::latency::LatencyTracker;use super::adaptive::AdaptiveBatchController;-use super::batch_config::BatchConfig;+use super::batch_config::{process_env, BatchConfig, EnvLookup};use super::batch_former::{BatchFormer, FormattedBatch, HasCost};use super::lane::{Lane, Verdict};use super::trackers::BatchEfficiencyTracker;@@ -204,6 +204,17 @@ 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>,+ /// Caps the scheduler was built with, before any controller step.+ /// [`Scheduler::adopt_cost_budget`] re-bases from these so a new+ /// budget starts from the configured wait, not a stepped one.+ initial_config: BatchConfig,+ /// The batch cost budget (`max_batch_tokens`) the static cost cap and+ /// the adaptive cost range currently derive from. Written only while+ /// the controller lock is held; read lock-free on the hot path.+ cost_budget: AtomicU64,+ /// Where the `SIE_ADAPTIVE_BATCH_*` overrides are read when the+ /// controller is derived from a budget, at build time and on re-base.+ env: EnvLookup,/// Fired on every submit, and on every batch return reported through/// [`Scheduler::note_return`]. [`Scheduler::consume_next`] and/// [`Scheduler::next_dispatch`] use this to wake without polling.@@ -254,6 +265,58 @@ where*self.config.read().await}+ /// The batch cost budget (`max_batch_tokens`) the static cost cap and+ /// the adaptive cost range currently derive from.+ pub fn cost_budget(&self) -> u64 {+ self.cost_budget.load(Ordering::Acquire)+ }++ /// Re-base the cost cap and the adaptive cost range on a new model+ /// batch cost budget (`max_batch_tokens`).+ ///+ /// A no-op returning `false` when the budget is unchanged, which is+ /// every call after the first in steady state. Otherwise the adaptive+ /// controller is rebuilt from `max_batch_tokens` exactly as+ /// [`SchedulerBuilder::build`] builds one (Python's production range+ /// plus `SIE_ADAPTIVE_BATCH_*` overrides), the static cost cap becomes+ /// the rebuilt controller's starting cost (the budget, unless an+ /// override clamps it), the fill-ratio window restarts, and every live+ /// batcher gets the new caps. The rebuilt controller re-calibrates its+ /// latency target.+ ///+ /// This runs when the backend reports a different budget for a model+ /// whose scheduler already exists, for example after the engine+ /// restarted with a newer image or applied a changed model config.+ pub async fn adopt_cost_budget(&self, max_batch_tokens: u64) -> bool {+ if self.cost_budget() == max_batch_tokens {+ return false;+ }+ // Same lock order as `record_completion` (controller, then config),+ // so a concurrent controller step cannot publish caps derived from+ // the old budget after this re-base.+ let mut controller = self.controller.lock().await;+ if self.cost_budget() == max_batch_tokens {+ return false;+ }+ let budget_cfg = BatchConfig {+ max_batch_cost: max_batch_tokens,+ ..self.initial_config+ };+ *controller =+ AdaptiveBatchController::from_batch_config_and_lookup(&budget_cfg, &*self.env);+ // Batches formed before the first controller step already honour+ // the operator's `SIE_ADAPTIVE_BATCH_*_COST` range.+ let new_cfg = BatchConfig {+ max_batch_cost: controller.current_batch_cost(),+ ..budget_cfg+ };+ *self.config.write().await = new_cfg;+ self.efficiency.lock().await.reset();+ self.cost_budget.store(max_batch_tokens, Ordering::Release);+ self.propagate_config(new_cfg).await;+ true+ }+/// Sum of pending items across every (op, lora) batcher.pub async fn total_pending_count(&self) -> usize {let map = self.batchers.read().await;@@ -550,6 +613,13 @@ wherebatch_cost: u64,batch_size: usize,) -> RecordCompletionOutcome {+ // The whole step runs under the controller lock, taken first, so it+ // cannot interleave with `adopt_cost_budget`: caps derived from a+ // replaced budget are never published after the re-base. Lock order+ // is controller, then config, then the batcher map; no path takes+ // the controller while holding one of the others.+ let mut ctrl = self.controller.lock().await;+let current_cap = self.config.read().await.max_batch_cost;self.efficiency.lock().await.record(batch_cost, current_cap);@@ -561,19 +631,11 @@ wherelet observed_p50 = self.latency.lock().await.p50();let fill = self.efficiency.lock().await.mean_fill_ratio();- let (new_wait, new_cost, target_p50, starvation_streak, starvation_resets_delta) = {- let mut ctrl = self.controller.lock().await;- let prev_resets = ctrl.starvation_resets();- let (w, c) = ctrl.step(observed_p50, fill, Some(batch_size));- let new_resets = ctrl.starvation_resets();- (- w,- c,- ctrl.target_p50_ms(),- ctrl.starvation_streak(),- new_resets.saturating_sub(prev_resets),- )- };+ let prev_resets = ctrl.starvation_resets();+ let (new_wait, new_cost) = ctrl.step(observed_p50, fill, Some(batch_size));+ let target_p50 = ctrl.target_p50_ms();+ let starvation_streak = ctrl.starvation_streak();+ let starvation_resets_delta = ctrl.starvation_resets().saturating_sub(prev_resets);// Update the shared snapshot. Short critical section under// the write lock — we only mutate two fields.@@ -583,26 +645,8 @@ 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- // `update_config` calls so a concurrent submit that creates a- // new batcher doesn't deadlock. A batcher created *after*- // this snapshot sees `new_cfg` via `config.read()` in- // `get_or_create`, so we don't lose the update.- let entries: Vec<Arc<BatcherEntry<I, T>>> = {- let map = self.batchers.read().await;- map.values().cloned().collect()- };- for entry in entries {- entry.former.update_config(new_cfg).await;- }+ self.propagate_config(new_cfg).await;+ drop(ctrl);RecordCompletionOutcome {new_wait_ms: new_wait,@@ -616,6 +660,29 @@ where}}+ /// Push `cfg` to every live batcher, and to the gather windows the lane+ /// waits on after a return.+ ///+ /// We snapshot the Vec of Arcs under the read lock and drop it+ /// before the async `update_config` calls so a concurrent submit+ /// that creates a new batcher doesn't deadlock. A batcher created+ /// *after* this snapshot sees `cfg` via `config.read()` in+ /// `get_or_create`, so we don't lose the update. Callers write+ /// `self.config` before calling this.+ async fn propagate_config(&self, cfg: BatchConfig) {+ self.gather_quiet_us+ .store(whole_micros(cfg.effective_coalesce_ms()), Ordering::Release);+ self.gather_longest_us+ .store(whole_micros(cfg.max_batch_wait_ms), Ordering::Release);+ let entries: Vec<Arc<BatcherEntry<I, T>>> = {+ let map = self.batchers.read().await;+ map.values().cloned().collect()+ };+ for entry in entries {+ entry.former.update_config(cfg).await;+ }+ }+// ---- Internal helpers ----fn lane(&self) -> std::sync::MutexGuard<'_, Lane> {@@ -698,6 +765,7 @@ impl<I: HasCost, T> std::fmt::Debug for Scheduler<I, T> {pub struct SchedulerBuilder<I: HasCost, T> {config: BatchConfig,controller: Option<AdaptiveBatchController>,+ env: Option<EnvLookup>,latency_window: usize,latency_min_samples: usize,efficiency_window: usize,@@ -709,6 +777,7 @@ impl<I: HasCost, T> Default for SchedulerBuilder<I, T> {Self {config: BatchConfig::default(),controller: None,+ env: None,// Python's `LatencyTracker(window_size=200, min_samples=10)`.latency_window: 200,latency_min_samples: 10,@@ -738,6 +807,16 @@ whereself}+ /// Read the `SIE_ADAPTIVE_BATCH_*` overrides through `env` instead of+ /// the process environment. They apply when the builder derives the+ /// controller (no [`Self::controller`] supplied) and when the scheduler+ /// re-bases on a new budget.+ #[must_use]+ pub fn env_lookup(mut self, env: EnvLookup) -> Self {+ self.env = Some(env);+ self+ }+/// Override the latency tracker window. Default 200 samples,/// 10-sample warm-up.#[must_use]@@ -759,7 +838,8 @@ where// Default controller mirrors Python's// `ModelWorker.__init__` *production* wiring against the// current `BatchConfig` (model `max_batch_tokens` =- // `cfg.max_batch_cost`, initial wait = `cfg.max_batch_wait_ms`,+ // `cfg.max_batch_cost`, which the registry sets to the model's+ // own budget; initial wait = `cfg.max_batch_wait_ms`,// cost floor / ceiling = `max_batch_tokens // 4` ..// `max_batch_tokens * 4`, `cost_gain = gain * 0.5`,// `min_wait_ms = 15.0`). The bare `default()` / module-level@@ -768,22 +848,36 @@ where// worker has been deploying.//// `SIE_ADAPTIVE_BATCH_*` env vars override on top, so- // operators can pin individual knobs without a recompile.+ // operators can pin individual knobs without a recompile, and+ // the static cost cap starts at the derived controller's starting+ // cost, so batches formed before the first controller step honour+ // an overridden range too. Without overrides that is the configured+ // cost cap itself.// Tests using `.controller(...)` continue to bypass both env// and BatchConfig derivation entirely (deterministic).- let cfg = self.config;+ let env = self.env.unwrap_or_else(process_env);+ let mut config = self.config;+ let controller = match self.controller {+ Some(controller) => controller,+ None => {+ let derived =+ AdaptiveBatchController::from_batch_config_and_lookup(&self.config, &*env);+ config.max_batch_cost = derived.current_batch_cost();+ derived+ }+ };Scheduler {batchers: RwLock::new(HashMap::new()),- controller: Mutex::new(- self.controller- .unwrap_or_else(|| AdaptiveBatchController::from_batch_config_and_env(&cfg)),- ),+ controller: Mutex::new(controller),latency: Mutex::new(LatencyTracker::new(self.latency_window,self.latency_min_samples,)),efficiency: Mutex::new(BatchEfficiencyTracker::new(self.efficiency_window)),- config: RwLock::new(self.config),+ config: RwLock::new(config),+ initial_config: self.config,+ cost_budget: AtomicU64::new(self.config.max_batch_cost),+ env,new_item: Notify::new(),lane: std::sync::Mutex::new(Lane::default()),gather_quiet_us: AtomicU64::new(whole_micros(self.config.effective_coalesce_ms())),@@ -1838,6 +1932,234 @@ mod tests {assert!(snap.target_p50_ms.is_none());}+ #[tokio::test]+ async fn adopt_cost_budget_rebases_every_batcher_and_rebuilds_the_controller() {+ let s: Scheduler<StubItem, u32> = Scheduler::new(BatchConfig::default());+ assert_eq!(s.cost_budget(), 16_384);+ for lora in ["a", "b"] {+ s.submit(+ Op::Extract,+ LoraKey::from_name(lora),+ StubItem { cost: 1, idx: 0 },+ 0,+ )+ .await;+ }+ // Mark the controller, then move the caps off their initial values+ // as controller steps do.+ for _ in 0..3 {+ let _ = s.record_completion(1, 1).await;+ }+ assert_eq!(s.controller_snapshot().await.starvation_streak, 3);+ {+ let mut cfg = s.config.write().await;+ cfg.max_batch_wait_ms = 42.0;+ cfg.max_batch_cost = 9_000;+ }++ assert!(s.adopt_cost_budget(720_000).await);++ let expected = BatchConfig {+ max_batch_cost: 720_000,+ ..BatchConfig::default()+ };+ assert_eq!(s.config().await, expected, "re-based from the initial caps");+ assert_eq!(s.cost_budget(), 720_000);+ for lora in ["a", "b"] {+ let former = {+ let map = s.batchers.read().await;+ Arc::clone(&map[&(Op::Extract, LoraKey::from_name(lora))].former)+ };+ assert_eq!(former.config().await, expected, "batcher {lora}");+ }+ {+ let ctrl = s.controller.lock().await;+ assert_eq!(+ (+ ctrl.min_batch_cost,+ ctrl.max_batch_cost,+ ctrl.current_batch_cost()+ ),+ (180_000, 2_880_000, 720_000)+ );+ assert_eq!(ctrl.starvation_streak(), 0, "a fresh controller");+ }+ assert_eq!(s.efficiency.lock().await.sample_count(), 0);++ // The same budget again changes nothing.+ let _ = s.record_completion(1, 1).await;+ assert!(!s.adopt_cost_budget(720_000).await);+ assert_eq!(s.controller_snapshot().await.starvation_streak, 1);+ }++ #[tokio::test]+ async fn adopt_cost_budget_rebases_the_gather_windows_after_a_return() {+ let s: Scheduler<StubItem, u32> = Scheduler::new(BatchConfig::default());+ // Windows a controller step left behind.+ s.gather_quiet_us.store(1, Ordering::Release);+ s.gather_longest_us.store(2, Ordering::Release);++ assert!(s.adopt_cost_budget(720_000).await);++ let initial = BatchConfig::default();+ assert_eq!(+ s.gather_quiet_us.load(Ordering::Acquire),+ whole_micros(initial.effective_coalesce_ms())+ );+ assert_eq!(+ s.gather_longest_us.load(Ordering::Acquire),+ whole_micros(initial.max_batch_wait_ms)+ );+ }++ // ---- The lane beside the runs-alone lane ----++ /// Prepared audio: clips batch together, recordings over 30 s run alone+ /// (`batch_former` point 5).+ #[derive(Debug, Clone)]+ struct Audio {+ ms: u64,+ alone: bool,+ key: &'static str,+ }++ impl HasCost for Audio {+ fn cost(&self) -> u64 {+ self.ms+ }+ fn hard_batch_cost_cap(&self) -> Option<u64> {+ Some(crate::audio_prep::MAX_AUDIO_BATCH_DURATION_MS)+ }+ fn runs_alone(&self) -> bool {+ self.alone+ }+ fn original_index(&self) -> usize {+ 0+ }+ fn request_key(&self) -> Option<&str> {+ Some(self.key)+ }+ }++ fn audio_clip(key: &'static str, seconds: u64) -> Audio {+ Audio {+ ms: seconds * 1_000,+ alone: false,+ key,+ }+ }++ fn recording(key: &'static str, seconds: u64) -> Audio {+ Audio {+ ms: seconds * 1_000,+ alone: true,+ key,+ }+ }++ /// Whisper's budget (720000 ms) and the default item cap, with batch+ /// wait and coalesce windows that do not fire by themselves in a test.+ fn audio_lane() -> Arc<Scheduler<Audio, &'static str>> {+ Arc::new(+ Scheduler::builder()+ .config(BatchConfig {+ max_batch_cost: 720_000,+ max_batch_wait_ms: 10_000.0,+ coalesce_ms: 40.0,+ coalesce_ratio: 1.0,+ ..BatchConfig::default()+ })+ .env_lookup(Arc::new(|_| None))+ .build(),+ )+ }++ async fn put(s: &Scheduler<Audio, &'static str>, item: Audio) {+ let key = item.key;+ s.submit(Op::Extract, LoraKey::base(), item, key).await;+ }++ /// The names in the next batch the lane sends within `ms`, if any.+ async fn sent_within(+ s: &Arc<Scheduler<Audio, &'static str>>,+ ms: u64,+ ) -> Option<Vec<&'static str>> {+ timeout(TDuration::from_millis(ms), s.next_dispatch(true))+ .await+ .ok()+ .map(|dispatch| {+ let mut names = dispatch.batch.metadata;+ names.sort_unstable();+ names+ })+ }++ #[tokio::test]+ async fn a_long_recording_pending_does_not_send_a_clip_batch_ahead() {+ // r2 (7 min) is longer than half the cap, so the whole queue would+ // count as full. The clips' batch can still grow, so the lane holds+ // it while r1 is with the engine, and the clip that arrives during+ // r1's forward joins it, ahead of r2.+ let s = audio_lane();+ put(&s, recording("r1", 40)).await;+ assert_eq!(sent_within(&s, 200).await, Some(vec!["r1"]));+ put(&s, recording("r2", 420)).await;+ put(&s, audio_clip("c1", 5)).await;+ assert_eq!(sent_within(&s, 30).await, None, "held while r1 is out");+ put(&s, audio_clip("c2", 5)).await;++ s.note_return(1, Duration::from_millis(200));+ assert_eq!(sent_within(&s, 300).await, Some(vec!["c1", "c2"]));+ s.note_return(2, Duration::from_millis(200));+ assert_eq!(sent_within(&s, 300).await, Some(vec!["r2"]));+ }++ #[tokio::test]+ async fn a_long_recording_waits_for_clips_that_arrive_during_a_recording() {+ // r2 queued behind r1 cannot grow, but sending it into the second+ // slot would make a clip that arrives during r1 wait for both. Held,+ // r2 lets that clip take its turn first.+ let s = audio_lane();+ put(&s, recording("r1", 40)).await;+ assert_eq!(sent_within(&s, 200).await, Some(vec!["r1"]));+ put(&s, recording("r2", 420)).await;+ assert_eq!(sent_within(&s, 30).await, None, "held while r1 is out");+ put(&s, audio_clip("c", 5)).await;++ s.note_return(1, Duration::from_millis(200));+ assert_eq!(sent_within(&s, 300).await, Some(vec!["c"]));+ s.note_return(1, Duration::from_millis(200));+ assert_eq!(sent_within(&s, 300).await, Some(vec!["r2"]));+ }++ #[tokio::test]+ async fn a_long_recording_after_a_clip_batch_still_leaves_at_once() {+ // After a clip batch the recording goes next whatever arrives (point+ // 5), so holding it gains nothing: a 7 min one is full, as on main.+ let s = audio_lane();+ put(&s, audio_clip("c", 5)).await;+ assert_eq!(sent_within(&s, 200).await, Some(vec!["c"]));+ put(&s, recording("r", 420)).await;+ assert_eq!(sent_within(&s, 30).await, Some(vec!["r"]));+ }++ #[tokio::test]+ async fn a_full_clip_batch_still_leaves_while_a_recording_is_out() {+ // Twelve clips fill a batch whatever the recordings pending, so the+ // lane sends them into the second slot, as for any other full batch.+ let s = audio_lane();+ put(&s, recording("r1", 40)).await;+ assert_eq!(sent_within(&s, 200).await, Some(vec!["r1"]));+ put(&s, recording("r2", 60)).await;+ const CLIPS: [&str; 12] = [+ "c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12",+ ];+ for name in CLIPS {+ put(&s, audio_clip(name, 2)).await;+ }+ assert_eq!(sent_within(&s, 30).await, Some(CLIPS.to_vec()));+ }+// ---- Aggregates ----#[tokio::test]diff --git a/packages/sie_server_sidecar/src/scheduler/item.rs b/packages/sie_server_sidecar/src/scheduler/item.rsindex da75a8a23..af9afa690 100644--- a/packages/sie_server_sidecar/src/scheduler/item.rs+++ b/packages/sie_server_sidecar/src/scheduler/item.rs@@ -39,7 +39,11 @@//! character count plus 1024 per media input, summed per//! `(query, document)` pair (so query cost repeats for each document).//! This is batching cost only, never a billable token count.-//! * **Extract**: unit cost; Python owns extract preparation today.+//! * **Extract**: duration in milliseconds when the sidecar prepared the+//! item's audio (as Python's audio preprocessor sets it), otherwise unit+//! cost. Prepared audio longer than+//! [`crate::audio_prep::RUNS_ALONE_ABOVE_SAMPLES`] also runs alone: it+//! never shares a batch (see [`HasCost::runs_alone`]).//!//! The adaptive controller auto-calibrates against observed latency,//! so being "approximately right" on cost is enough; what matters is@@ -244,6 +248,15 @@ impl HasCost for SchedulerItem {}}+ fn runs_alone(&self) -> bool {+ match self {+ Self::Extract(e) => e.prepared_audio.as_ref().is_some_and(|audio| {+ audio.sample_count > crate::audio_prep::RUNS_ALONE_ABOVE_SAMPLES+ }),+ _ => false,+ }+ }+fn request_key(&self) -> Option<&str> {let request_id = match self {Self::Encode(e) => e.request_id.as_str(),@@ -603,6 +616,80 @@ mod tests {assert_eq!(it.hard_batch_cost_cap(), Some(720_000));}+ /// Extract item carrying sidecar-prepared 16 kHz audio of `sample_count`+ /// samples (the PCM bytes themselves are irrelevant to scheduling).+ fn audio_extract_item(sample_count: u64) -> SchedulerItem {+ SchedulerItem::Extract(ExtractBatchItem {+ work_item_id: "r.0".into(),+ request_id: "r".into(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ item: text_item("x"),+ labels: None,+ output_schema: None,+ instruction: None,+ options: None,+ profile_id: None,+ bundle_config_hash: None,+ payload_fetch_ms: 0.0,+ prepared_audio: Some(crate::ipc_types::PreparedAudioPcm16 {+ pcm_s16le: vec![],+ sample_rate: 16_000,+ sample_count,+ duration_ms: sample_count.div_ceil(16),+ source_sample_rate: 16_000,+ source_sample_count: sample_count,+ source_channels: 1,+ container: "wav".into(),+ }),+ })+ }++ #[test]+ fn audio_extract_runs_alone_only_past_thirty_seconds() {+ assert_eq!(crate::audio_prep::RUNS_ALONE_ABOVE_SAMPLES, 480_000);+ let at_window = audio_extract_item(480_000);+ let past_window = audio_extract_item(480_001);++ assert!(!at_window.runs_alone(), "exactly 30 s fits one window");+ assert!(past_window.runs_alone(), "30 s + 1 sample is long-form");+ assert!(!audio_extract_item(16_000).runs_alone());+ // Cost stays the duration either way.+ assert_eq!(at_window.cost(), 30_000);+ assert_eq!(past_window.cost(), 30_001);+ }++ #[test]+ fn only_prepared_audio_runs_alone() {+ let text_extract = SchedulerItem::Extract(ExtractBatchItem {+ work_item_id: "r.0".into(),+ request_id: "r".into(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ item: text_item("x"),+ labels: None,+ output_schema: None,+ instruction: None,+ options: None,+ profile_id: None,+ bundle_config_hash: None,+ payload_fetch_ms: 0.0,+ prepared_audio: None,+ });+ let encode = SchedulerItem::Encode(encode_item(0, Some(pt_with_lens(&[480_001]))));+ let score = SchedulerItem::score(score_batch_item(+ text_item(&"q".repeat(480_001)),+ vec![text_item("d")],+ None,+ ));++ assert!(!text_extract.runs_alone());+ assert!(!encode.runs_alone());+ assert!(!score.runs_alone());+ }+#[test]fn original_index_matches_item_index() {let it = SchedulerItem::Encode(encode_item(7, None));diff --git a/packages/sie_server_sidecar/src/scheduler/registry.rs b/packages/sie_server_sidecar/src/scheduler/registry.rsindex 61689d32a..ef7e3c055 100644--- a/packages/sie_server_sidecar/src/scheduler/registry.rs+++ b/packages/sie_server_sidecar/src/scheduler/registry.rs@@ -13,6 +13,26 @@//! * Schedulers are lazily created — models that never receive//! traffic never allocate one.//!+//! ## Per-model batch cost budget+//!+//! Each scheduler's static cost cap and adaptive cost range derive from+//! the model's own `max_batch_tokens`, which the backend reports with+//! `EnsureModelReady`, as Python's `ModelWorker` derives them from the+//! model's profile. Precedence:+//!+//! 1. `SIE_BATCHER_MAX_BATCH_COST`, when set: [`SchedulerRegistry::from_env`]+//! builds the registry cost-pinned and every model keeps that cap,+//! ignoring the reported budget.+//! 2. Otherwise the budget the backend reported for the model.+//! 3. Otherwise (a backend that does not report one) the default+//! config's cap, 16384.+//!+//! `SIE_ADAPTIVE_BATCH_*` overrides still apply on top of whichever+//! budget wins (see+//! [`crate::scheduler::AdaptiveBatchController::from_batch_config_and_env`]),+//! and the static cost cap starts at the controller's starting cost, so an+//! overridden cost range holds from a scheduler's first batch.+//!//! There is no per-model scheduler env list any more. Active models route//! through the Rust scheduler when their worker pool is the sidecar pool.//! Every model that lands on a worker-sidecar goes through the@@ -26,18 +46,25 @@ use std::collections::HashMap;use std::sync::Arc;use tokio::sync::RwLock;+use tracing::info;-use super::batch_config::BatchConfig;+use super::batch_config::{process_env, BatchConfig, EnvLookup};use super::batch_former::HasCost;use super::engine::Scheduler;/// Per-model scheduler registry.pub struct SchedulerRegistry<I: HasCost, T> {/// Default caps + per-scheduler defaults every lazily created- /// [`Scheduler`] starts with. Operators override by setting- /// model-specific tunables at the `Scheduler::builder()` seam- /// when per-model tuning lands.+ /// [`Scheduler`] starts with. Its `max_batch_cost` is replaced by+ /// the model's reported batch cost budget unless the registry is+ /// cost-pinned.default_config: BatchConfig,+ /// `true` when the operator pinned the cost cap+ /// (`SIE_BATCHER_MAX_BATCH_COST`): reported model budgets are+ /// ignored and every scheduler keeps `default_config.max_batch_cost`.+ cost_pinned: bool,+ /// Where the schedulers read their `SIE_ADAPTIVE_BATCH_*` overrides.+ env: EnvLookup,schedulers: RwLock<HashMap<String, Arc<Scheduler<I, T>>>>,}@@ -48,6 +75,7 @@ wherefn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {f.debug_struct("SchedulerRegistry").field("default_config", &self.default_config)+ .field("cost_pinned", &self.cost_pinned).finish_non_exhaustive()}}@@ -57,39 +85,129 @@ whereI: HasCost + Send + Sync + 'static,T: Send + Sync + 'static,{- /// Build with the given default per-scheduler config.+ /// Build with the given default per-scheduler config. Model budgets+ /// reported to [`Self::get_or_create`] replace its cost cap.#[must_use]pub fn new(default_config: BatchConfig) -> Self {Self {default_config,+ cost_pinned: false,+ env: process_env(),schedulers: RwLock::new(HashMap::new()),}}+ /// Production constructor: `SIE_BATCHER_*` defaults, cost-pinned+ /// exactly when `SIE_BATCHER_MAX_BATCH_COST` is set.+ #[must_use]+ pub fn from_env() -> Self {+ Self::from_lookup(process_env())+ }++ /// [`Self::from_env`] reading variables through `env`, which the+ /// schedulers also use for their `SIE_ADAPTIVE_BATCH_*` overrides.+ #[must_use]+ pub fn from_lookup(env: EnvLookup) -> Self {+ Self {+ default_config: BatchConfig::from_lookup(&*env),+ cost_pinned: BatchConfig::max_batch_cost_override(&*env).is_some(),+ env,+ schedulers: RwLock::new(HashMap::new()),+ }+ }++ /// Pin every scheduler to `default_config.max_batch_cost`, ignoring+ /// the budgets models report. [`Self::from_env`] pins exactly when+ /// `SIE_BATCHER_MAX_BATCH_COST` is set.+ #[must_use]+ pub fn with_cost_pinned(mut self, cost_pinned: bool) -> Self {+ self.cost_pinned = cost_pinned;+ self+ }+/// Return the scheduler for `model_id`, lazily creating it on/// first call.///+ /// `model_max_batch_tokens` is the model's batch cost budget as the+ /// backend reported it (`None` when it did not; zero counts as+ /// absent). A new scheduler starts from it; an existing one re-bases+ /// onto it when it differs from the budget the scheduler runs on (see+ /// [`Scheduler::adopt_cost_budget`]). `None` never resets a budget a+ /// scheduler already adopted. A cost-pinned registry ignores it.+ ////// The second tuple element is `true` only on the call that/// actually materialised the scheduler. The dispatcher uses it/// to spawn exactly one drain loop per model — see/// `crate::dispatcher::Dispatcher::resolve_scheduler`.///- /// Thread-safe: the hot path is a read-lock + hashmap lookup;- /// only the very first call for a given `model_id` takes the- /// write lock, and concurrent callers double-check under it.- pub async fn get_or_create(&self, model_id: &str) -> (Arc<Scheduler<I, T>>, bool) {- if let Some(s) = self.schedulers.read().await.get(model_id) {- return (Arc::clone(s), false);+ /// Thread-safe: the hot path is a read-lock + hashmap lookup plus+ /// one atomic load; only the very first call for a given `model_id`+ /// takes the write lock, and concurrent callers double-check under it.+ pub async fn get_or_create(+ &self,+ model_id: &str,+ model_max_batch_tokens: Option<u64>,+ ) -> (Arc<Scheduler<I, T>>, bool) {+ let budget = if self.cost_pinned {+ None+ } else {+ model_max_batch_tokens.filter(|&b| b > 0)+ };+ let existing = self.schedulers.read().await.get(model_id).cloned();+ if let Some(sched) = existing {+ Self::adopt(model_id, &sched, budget).await;+ return (sched, false);}let mut map = self.schedulers.write().await;- if let Some(s) = map.get(model_id) {- return (Arc::clone(s), false);+ if let Some(sched) = map.get(model_id).cloned() {+ drop(map);+ Self::adopt(model_id, &sched, budget).await;+ return (sched, false);}- let sched = Arc::new(Scheduler::new(self.default_config));+ let mut config = self.default_config;+ let source = if self.cost_pinned {+ "env"+ } else if let Some(budget) = budget {+ config.max_batch_cost = budget;+ "model"+ } else {+ "default"+ };+ let sched = Arc::new(+ Scheduler::builder()+ .config(config)+ .env_lookup(Arc::clone(&self.env))+ .build(),+ );+ let max_batch_cost = sched.config().await.max_batch_cost;+ info!(+ model = %model_id,+ budget = config.max_batch_cost,+ source,+ max_batch_cost,+ "rust-scheduler: scheduler created"+ );map.insert(model_id.to_owned(), Arc::clone(&sched));(sched, true)}+ async fn adopt(model_id: &str, sched: &Scheduler<I, T>, budget: Option<u64>) {+ let Some(budget) = budget else {+ return;+ };+ let previous = sched.cost_budget();+ if sched.adopt_cost_budget(budget).await {+ let max_batch_cost = sched.config().await.max_batch_cost;+ info!(+ model = %model_id,+ previous_budget = previous,+ budget,+ max_batch_cost,+ "rust-scheduler: batch cost budget changed; caps and adaptive range re-based"+ );+ }+ }+/// List the model ids that currently have an instantiated/// scheduler. Useful for dashboards and for the shadow-trace/// replay which needs to enumerate live per-model state.@@ -106,6 +224,9 @@ where#[cfg(test)]mod tests {use super::*;+ use crate::ipc_types::{ExtractBatchItem, PreparedAudioPcm16, WireValue};+ use crate::scheduler::engine::{LoraKey, Op};+ use crate::scheduler::item::SchedulerItem;#[derive(Debug, Clone, Copy)]struct StubItem;@@ -121,9 +242,9 @@ mod tests {#[tokio::test]async fn get_or_create_marks_first_call_as_created() {let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());- let (_, created1) = reg.get_or_create("foo").await;+ let (_, created1) = reg.get_or_create("foo", None).await;assert!(created1, "first call for a model must report created=true");- let (_, created2) = reg.get_or_create("foo").await;+ let (_, created2) = reg.get_or_create("foo", None).await;assert!(!created2,"subsequent call for the same model must report created=false"@@ -133,8 +254,8 @@ mod tests {#[tokio::test]async fn get_or_create_returns_same_arc_on_repeat_calls() {let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());- let (a, _) = reg.get_or_create("foo").await;- let (b, _) = reg.get_or_create("foo").await;+ let (a, _) = reg.get_or_create("foo", None).await;+ let (b, _) = reg.get_or_create("foo", None).await;// Pointer equality — lazy creation must memoize the Arc so// adaptive-controller state persists across dispatcher calls.assert!(Arc::ptr_eq(&a, &b));@@ -143,8 +264,8 @@ mod tests {#[tokio::test]async fn different_models_get_different_schedulers() {let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());- let (a, _) = reg.get_or_create("foo").await;- let (b, _) = reg.get_or_create("bar").await;+ let (a, _) = reg.get_or_create("foo", None).await;+ let (b, _) = reg.get_or_create("bar", None).await;assert!(!Arc::ptr_eq(&a, &b));}@@ -152,11 +273,325 @@ mod tests {async fn active_models_reports_materialised_schedulers() {let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());assert!(reg.active_models().await.is_empty());- let _ = reg.get_or_create("foo").await;- let _ = reg.get_or_create("bar").await;+ let _ = reg.get_or_create("foo", None).await;+ let _ = reg.get_or_create("bar", None).await;let mut active = reg.active_models().await;active.sort();assert_eq!(active, vec!["bar".to_string(), "foo".to_string()]);assert_eq!(reg.active_count().await, 2);}++ // ---- Per-model batch cost budget ----++ const WHISPER: &str = "openai/whisper-large-v3-turbo";++ async fn cost_state<I, T>(sched: &Scheduler<I, T>) -> (u64, u64, u64)+ where+ I: HasCost + Send + Sync + 'static,+ T: Send + Sync + 'static,+ {+ (+ sched.cost_budget(),+ sched.config().await.max_batch_cost,+ sched.controller_snapshot().await.current_batch_cost,+ )+ }++ /// Advance the controller's starvation streak by `n` single-item+ /// batches: state that survives only while the same controller runs.+ async fn mark_controller<I, T>(sched: &Scheduler<I, T>, n: u32) -> u32+ where+ I: HasCost + Send + Sync + 'static,+ T: Send + Sync + 'static,+ {+ for _ in 0..n {+ let _ = sched.record_completion(1, 1).await;+ }+ sched.controller_snapshot().await.starvation_streak+ }++ #[tokio::test]+ async fn model_budget_sets_the_cost_cap_and_adaptive_start() {+ let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());+ let (sched, created) = reg.get_or_create(WHISPER, Some(720_000)).await;+ assert!(created);+ assert_eq!(cost_state(&sched).await, (720_000, 720_000, 720_000));+ // Everything but the cost cap still comes from the default config.+ assert_eq!(+ sched.config().await,+ BatchConfig {+ max_batch_cost: 720_000,+ ..BatchConfig::default()+ }+ );+ }++ #[tokio::test]+ async fn missing_or_zero_model_budget_keeps_the_default_cap() {+ for reported in [None, Some(0)] {+ let reg: SchedulerRegistry<StubItem, ()> =+ SchedulerRegistry::new(BatchConfig::default());+ let (sched, _) = reg.get_or_create("m", reported).await;+ assert_eq!(cost_state(&sched).await, (16_384, 16_384, 16_384));+ assert_eq!(sched.config().await, BatchConfig::default());+ }+ }++ #[tokio::test]+ async fn a_16384_budget_runs_exactly_like_the_default() {+ // Most profiles declare 16384; their schedulers must not change.+ let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());+ let (reported, _) = reg.get_or_create("reported", Some(16_384)).await;+ let (silent, _) = reg.get_or_create("silent", None).await;+ assert_eq!(reported.config().await, silent.config().await);+ assert_eq!(+ reported.controller_snapshot().await,+ silent.controller_snapshot().await+ );++ // Reporting 16384 to a scheduler created without a budget keeps+ // its controller: nothing re-calibrates.+ assert_eq!(mark_controller(&silent, 3).await, 3);+ let (again, _) = reg.get_or_create("silent", Some(16_384)).await;+ assert!(Arc::ptr_eq(&again, &silent));+ assert_eq!(again.controller_snapshot().await.starvation_streak, 3);+ }++ #[tokio::test]+ async fn cost_pinned_registry_ignores_model_budgets() {+ // `SIE_BATCHER_MAX_BATCH_COST` set: its cap wins for every model.+ let pinned = BatchConfig {+ max_batch_cost: 32_768,+ ..BatchConfig::default()+ };+ let reg: SchedulerRegistry<StubItem, ()> =+ SchedulerRegistry::new(pinned).with_cost_pinned(true);+ let (sched, _) = reg.get_or_create(WHISPER, Some(720_000)).await;+ assert_eq!(cost_state(&sched).await, (32_768, 32_768, 32_768));+ let (sched, _) = reg.get_or_create(WHISPER, Some(4_096)).await;+ assert_eq!(cost_state(&sched).await, (32_768, 32_768, 32_768));+ }++ #[tokio::test]+ async fn same_budget_again_keeps_the_scheduler_and_its_controller() {+ let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());+ let (first, _) = reg.get_or_create(WHISPER, Some(720_000)).await;+ assert_eq!(mark_controller(&first, 3).await, 3);++ let (second, created) = reg.get_or_create(WHISPER, Some(720_000)).await;+ assert!(!created);+ assert!(Arc::ptr_eq(&first, &second));+ assert_eq!(second.controller_snapshot().await.starvation_streak, 3);+ assert_eq!(cost_state(&second).await, (720_000, 720_000, 720_000));+ }++ #[tokio::test]+ async fn changed_budget_rebases_an_existing_scheduler() {+ // Created against a backend that reported nothing, then the+ // backend restarts and reports the model's budget.+ let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());+ let (sched, _) = reg.get_or_create(WHISPER, None).await;+ sched+ .submit(Op::Extract, LoraKey::base(), StubItem, ())+ .await;+ assert_eq!(mark_controller(&sched, 3).await, 3);++ let (same, created) = reg.get_or_create(WHISPER, Some(720_000)).await;+ assert!(!created);+ assert!(Arc::ptr_eq(&sched, &same));+ assert_eq!(cost_state(&sched).await, (720_000, 720_000, 720_000));+ assert_eq!(+ sched.controller_snapshot().await.starvation_streak,+ 0,+ "the controller is rebuilt for the new budget"+ );++ // `None` from a later answer never undoes an adopted budget.+ let _ = reg.get_or_create(WHISPER, None).await;+ assert_eq!(cost_state(&sched).await, (720_000, 720_000, 720_000));++ // A further change re-bases again.+ let _ = reg.get_or_create(WHISPER, Some(4_096)).await;+ assert_eq!(cost_state(&sched).await, (4_096, 4_096, 4_096));+ }++ /// An environment holding exactly `pairs`.+ fn env_table(pairs: &'static [(&'static str, &'static str)]) -> EnvLookup {+ Arc::new(move |var| {+ pairs+ .iter()+ .find(|(name, _)| *name == var)+ .map(|(_, value)| (*value).to_string())+ })+ }++ #[tokio::test]+ async fn env_cost_cap_wins_over_reported_budgets() {+ // Set: every model keeps the operator's cap and the range it derives.+ let reg: SchedulerRegistry<StubItem, ()> =+ SchedulerRegistry::from_lookup(env_table(&[("SIE_BATCHER_MAX_BATCH_COST", "32768")]));+ let (sched, _) = reg.get_or_create(WHISPER, Some(720_000)).await;+ assert_eq!(cost_state(&sched).await, (32_768, 32_768, 32_768));+ let (sched, _) = reg.get_or_create("text-model", None).await;+ assert_eq!(cost_state(&sched).await, (32_768, 32_768, 32_768));++ // Unset or unparseable: the reported budget applies, else 16384.+ for pairs in [&[][..], &[("SIE_BATCHER_MAX_BATCH_COST", "16k")][..]] {+ let reg: SchedulerRegistry<StubItem, ()> =+ SchedulerRegistry::from_lookup(env_table(pairs));+ let (sched, _) = reg.get_or_create(WHISPER, Some(720_000)).await;+ assert_eq!(+ cost_state(&sched).await,+ (720_000, 720_000, 720_000),+ "{pairs:?}"+ );+ let (sched, _) = reg.get_or_create("text-model", None).await;+ assert_eq!(+ cost_state(&sched).await,+ (16_384, 16_384, 16_384),+ "{pairs:?}"+ );+ }+ }++ #[tokio::test]+ async fn adaptive_cost_ceiling_bounds_batches_from_the_first_one() {+ // `SIE_ADAPTIVE_BATCH_MAX_COST` holds before any controller step:+ // after creation and after a re-base, not only after a completion.+ let reg: SchedulerRegistry<SchedulerItem, String> =+ SchedulerRegistry::from_lookup(env_table(&[("SIE_ADAPTIVE_BATCH_MAX_COST", "65536")]));+ let base = LoraKey::base;+ let clips = || {+ (0..12)+ .map(|i| (audio(25_000), format!("clip-{i}")))+ .collect::<Vec<_>>()+ };++ let (sched, _) = reg.get_or_create(WHISPER, Some(720_000)).await;+ assert_eq!(cost_state(&sched).await, (720_000, 65_536, 65_536));+ sched.submit_many(Op::Extract, base(), clips()).await;+ let first = sched+ .try_drain_same(Op::Extract, base())+ .await+ .expect("clips pending");+ assert_eq!((first.size(), first.total_cost), (2, 50_000));++ // Re-based from the default budget onto the model's.+ let (other, _) = reg.get_or_create("other-speech-model", None).await;+ assert_eq!(cost_state(&other).await, (16_384, 16_384, 16_384));+ other.submit_many(Op::Extract, base(), clips()).await;+ let _ = reg.get_or_create("other-speech-model", Some(720_000)).await;+ assert_eq!(cost_state(&other).await, (720_000, 65_536, 65_536));+ let batch = other+ .try_drain_same(Op::Extract, base())+ .await+ .expect("clips pending");+ assert_eq!((batch.size(), batch.total_cost), (2, 50_000));+ }++ // ---- The clip-starvation case behind per-model budgets ----++ /// A sidecar-prepared 16 kHz audio extract item lasting `ms`.+ fn audio(ms: u64) -> SchedulerItem {+ SchedulerItem::Extract(ExtractBatchItem {+ work_item_id: "r.0".into(),+ request_id: "r".into(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ item: WireValue::Nil,+ labels: None,+ output_schema: None,+ instruction: None,+ options: None,+ profile_id: None,+ bundle_config_hash: None,+ payload_fetch_ms: 0.0,+ prepared_audio: Some(PreparedAudioPcm16 {+ pcm_s16le: vec![],+ sample_rate: 16_000,+ sample_count: ms * 16,+ duration_ms: ms,+ source_sample_rate: 16_000,+ source_sample_count: ms * 16,+ source_channels: 1,+ container: "wav".into(),+ }),+ })+ }++ /// Long recordings and saturating clips on one speech model: the+ /// lanes alternate, so the clips one clip turn takes are the clip+ /// throughput between two recordings. A turn takes the clips pending+ /// when it began up to the cost cap. With the shared 16384 ms default+ /// that was 1-2 clips; with the model's own 720000 ms budget it is+ /// every pending clip, in batches of at most the request count cap.+ #[tokio::test]+ async fn model_budget_lets_one_clip_turn_take_the_pending_clips() {+ // 16 clips of 6-15 s: 152 s of audio, far over 16384 ms, and more+ // clips than the request count cap (12) takes in one batch.+ let clip_seconds = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 6, 7, 8, 9, 10, 11];+ for (budget, clip_turn) in [+ (None, vec![vec![6, 6]]),+ (+ Some(720_000),+ vec![+ vec![6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11],+ vec![12, 13, 14, 15],+ ],+ ),+ ] {+ let reg: SchedulerRegistry<SchedulerItem, String> =+ SchedulerRegistry::new(BatchConfig::default());+ let (sched, _) = reg.get_or_create(WHISPER, budget).await;+ let base = LoraKey::base;++ sched+ .submit(Op::Extract, base(), audio(240_000), "long-1".into())+ .await;+ // Keep arrivals ordered: the recordings bracket the clips.+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;+ let clips = clip_seconds+ .iter()+ .map(|&s| (audio(s * 1_000), format!("clip-{s}s")))+ .collect();+ sched.submit_many(Op::Extract, base(), clips).await;+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;+ sched+ .submit(Op::Extract, base(), audio(200_000), "long-2".into())+ .await;++ let mut served = Vec::new();+ while let Some(batch) = sched.try_drain_same(Op::Extract, base()).await {+ served.push(batch.metadata);+ }++ let seconds = |names: &[String]| -> Vec<u64> {+ names+ .iter()+ .map(|name| {+ name.trim_start_matches("clip-")+ .trim_end_matches('s')+ .parse()+ .expect("a clip")+ })+ .collect()+ };+ let turn_batches = clip_turn.len();+ assert_eq!(served[0], ["long-1"], "budget {budget:?}");+ let turn: Vec<Vec<u64>> = served[1..=turn_batches]+ .iter()+ .map(|batch| seconds(batch))+ .collect();+ assert_eq!(turn, clip_turn, "budget {budget:?}");+ assert_eq!(served[turn_batches + 1], ["long-2"], "budget {budget:?}");+ let clips_served: usize = served.iter().map(Vec::len).sum::<usize>() - 2;+ assert_eq!(clips_served, clip_seconds.len(), "budget {budget:?}");+ if budget.is_some() {+ assert_eq!(served.len(), 4, "one clip turn serves every clip");+ } else {+ assert!(served.len() > 4, "clips are still pending after one turn");+ }+ }+ }}