Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix(batcher): serve long-form audio in its own lane, alternating with clips (#601)

Shai Shmuel45b6ffe1b58d
diff --git a/packages/sie_server/src/sie_server/adapters/whisper/adapter.py b/packages/sie_server/src/sie_server/adapters/whisper/adapter.py
index f98bb87a2..3fbcc818c 100644
--- a/packages/sie_server/src/sie_server/adapters/whisper/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/whisper/adapter.py
@@ -101,7 +101,12 @@ class WhisperAdapter(BaseAdapter):
torch_dtype=dtype,
device=device,
)
- self._preprocessor = AudioPreprocessor()
+ # Audio past one feature window is transcribed long-form, one recording
+ # per pipeline call (see extract()), so the batcher serves it alone and
+ # short clips never wait inside its batch.
+ self._preprocessor = AudioPreprocessor(
+ runs_alone_above_samples=self._processor.feature_extractor.n_samples,
+ )
def _resolve_dtype(self) -> torch.dtype:
if not self._device or not self._device.startswith("cuda"):
diff --git a/packages/sie_server/src/sie_server/core/batcher.py b/packages/sie_server/src/sie_server/core/batcher.py
index 9678ffb7c..c4a5cf4ca 100644
--- a/packages/sie_server/src/sie_server/core/batcher.py
+++ b/packages/sie_server/src/sie_server/core/batcher.py
@@ -18,11 +18,21 @@ The key optimization is cost-sorted sub-batching:
- Each sub-batch contains similar-cost items
- This minimizes padding waste within each sub-batch
+Items flagged ``runs_alone`` (long-form audio, #585) 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 cost-sorted batch of batchable items,
+then the oldest flagged item, and so on. A batchable item never waits inside
+a long item's batch, and waits for at most one flagged item between two
+batches of its lane. A flagged item with k flagged items ahead of it waits
+for at most k + 1 batches of batchable items, however many keep arriving.
+When nothing pending is flagged, batch formation is exactly the cost-sorted
+greedy packing above.
+
Cost semantics vary by modality (modality-native units):
- Text: cost = token count
- Images: cost = 1 per image (fixed dimensions)
- Vision (tiled): cost = tile count (1-N per image)
-- Audio: cost = sample_count / chunk_size
+- Audio: cost = duration in milliseconds
These units are NOT commensurable across modalities, so ``total_cost`` is only
meaningful within a single modality (the common case — a model's batch is
@@ -49,7 +59,9 @@ logger = logging.getLogger(__name__)
class HasCost(Protocol):
"""Protocol for items that have a batching cost.
- PreparedItem and other prepared item types satisfy this protocol.
+ PreparedItem and other prepared item types satisfy this protocol. An item
+ may also expose ``runs_alone``; only ``True`` keeps it out of shared
+ batches (see ``PreparedItem.runs_alone``).
"""
@property
@@ -73,6 +85,7 @@ class PendingRequest[I: HasCost, T]:
item: I
metadata: T
arrival_time: float = field(default_factory=time.monotonic)
+ runs_alone: bool = False
@dataclass(slots=True)
@@ -215,6 +228,7 @@ class BatchFormer[I: HasCost, T]:
self._batch_ready = asyncio.Event()
self._first_request_time: float | None = None
self._last_submit_time: float | None = None
+ self._last_batch_alone: bool | None = None
@property
def config(self) -> BatchConfig:
@@ -308,7 +322,7 @@ class BatchFormer[I: HasCost, T]:
def _append_item(self, item: I, metadata: T) -> None:
"""Append item to pending list (caller must hold lock)."""
- request = PendingRequest(item=item, metadata=metadata)
+ request = PendingRequest(item=item, metadata=metadata, runs_alone=getattr(item, "runs_alone", False) is True)
self._pending.append(request)
self._total_cost += item.cost
@@ -403,6 +417,26 @@ class BatchFormer[I: HasCost, T]:
effective_ms = min(batch_remaining_ms, coalesce_remaining_ms)
return effective_ms / 1000 # Convert to seconds
+ def _order_runs_alone_lane(self) -> None:
+ """Order pending requests when at least one is flagged ``runs_alone``.
+
+ Batchable requests come first, sorted by cost as usual, and flagged
+ requests follow in arrival order. The two lanes take turns (#585): the
+ oldest flagged request moves to the front after a batch of batchable
+ requests, and before the first batch only if it is the oldest pending
+ request.
+ """
+ self._pending.sort(key=lambda r: (r.runs_alone, r.arrival_time if r.runs_alone else r.item.cost))
+ head_index = next(index for index, request in enumerate(self._pending) if request.runs_alone)
+ if head_index == 0:
+ return
+ if self._last_batch_alone is None:
+ alone_turn = min(self._pending, key=lambda r: r.arrival_time).runs_alone
+ else:
+ alone_turn = not self._last_batch_alone
+ if alone_turn:
+ self._pending.insert(0, self._pending.pop(head_index))
+
def _extract_batch(
self,
max_items: int | None = None,
@@ -416,6 +450,9 @@ class BatchFormer[I: HasCost, T]:
3. Keep remaining requests for next get_batch() call
This minimizes padding waste by grouping similar-cost sequences.
+ When a pending request is flagged ``runs_alone``, the order comes from
+ ``_order_runs_alone_lane`` instead, and a flagged request is always
+ taken on its own.
Args:
max_items: Optional hard cap on the number of items taken, on top of
@@ -435,8 +472,11 @@ class BatchFormer[I: HasCost, T]:
pending_before = len(self._pending)
cost_before = self._total_cost
- # Sort pending by cost (ascending) for optimal batching
- self._pending.sort(key=lambda r: r.item.cost)
+ if any(request.runs_alone for request in self._pending):
+ self._order_runs_alone_lane()
+ else:
+ # Sort pending by cost (ascending) for optimal batching
+ self._pending.sort(key=lambda r: r.item.cost)
# Greedily take items until we exceed max_batch_cost
batch_items: list[I] = []
@@ -451,6 +491,10 @@ class BatchFormer[I: HasCost, T]:
# before anything else, so post-snapshot arrivals stay queued.
if max_items is not None and take_count >= max_items:
break
+ # A runs_alone item never shares a batch: stop in front of one
+ # unless it is the first item taken.
+ if request.runs_alone and take_count > 0:
+ break
# Would this item push us over the cost limit?
# Always take at least one item (handles single large requests)
if batch_cost + request.item.cost > self._config.max_batch_cost:
@@ -464,11 +508,19 @@ class BatchFormer[I: HasCost, T]:
batch_cost += request.item.cost
take_count += 1
+ if request.runs_alone:
+ break
+
# Also respect max_batch_requests
if take_count >= self._config.max_batch_requests:
hit_request_limit = True
break
+ lane = "alone" if take_count > 0 and self._pending[0].runs_alone else "batched"
+ if take_count > 0:
+ # Whose turn is next when both lanes are pending.
+ self._last_batch_alone = lane == "alone"
+
# Remove taken items from pending
self._pending = self._pending[take_count:]
self._total_cost -= batch_cost
@@ -479,8 +531,9 @@ class BatchFormer[I: HasCost, T]:
)
limit_hit = "cost_limit" if hit_cost_limit else ("request_limit" if hit_request_limit else "none")
logger.debug(
- "Batch formed: trigger=%s, limit_hit=%s, items=%d/%d taken, cost=%d/%d, remaining=%d items",
+ "Batch formed: trigger=%s, lane=%s, limit_hit=%s, items=%d/%d taken, cost=%d/%d, remaining=%d items",
trigger,
+ lane,
limit_hit,
take_count,
pending_before,
diff --git a/packages/sie_server/src/sie_server/core/prepared.py b/packages/sie_server/src/sie_server/core/prepared.py
index 2cfa3828e..55b3d36c3 100644
--- a/packages/sie_server/src/sie_server/core/prepared.py
+++ b/packages/sie_server/src/sie_server/core/prepared.py
@@ -87,11 +87,14 @@ class PreparedItem[T: Payload]:
across modalities; the BatchFormer sum is only meaningful within
one modality.
original_index: Position in original request for result reordering.
+ runs_alone: Never batched with other items; such items are served one
+ per batch in arrival order.
"""
payload: T
cost: int
original_index: int
+ runs_alone: bool = False
@dataclass(slots=True)
diff --git a/packages/sie_server/src/sie_server/core/preprocessor/audio.py b/packages/sie_server/src/sie_server/core/preprocessor/audio.py
index 0e25e7bfb..016060f5e 100644
--- a/packages/sie_server/src/sie_server/core/preprocessor/audio.py
+++ b/packages/sie_server/src/sie_server/core/preprocessor/audio.py
@@ -21,6 +21,16 @@ class _AudioPrepModule(Protocol):
class AudioPreprocessor:
"""Decode and resample audio through the shared Rust extension."""
+ def __init__(self, *, runs_alone_above_samples: int | None = None) -> None:
+ """Initialize the preprocessor.
+
+ Args:
+ runs_alone_above_samples: Prepared items with more samples than
+ this are flagged ``runs_alone``, so the batcher serves each on
+ its own. ``None`` flags nothing.
+ """
+ self._runs_alone_above_samples = runs_alone_above_samples
+
@property
def modality(self) -> str:
return "audio"
@@ -43,6 +53,7 @@ class AudioPreprocessor:
raise RuntimeError(msg) from exc
prepared_items: list[PreparedItem[AudioPayload]] = []
total_cost = 0
+ threshold = self._runs_alone_above_samples
for index, item in enumerate(items):
if item.audio is None:
@@ -86,6 +97,7 @@ class AudioPreprocessor:
payload=payload,
cost=payload.duration_cost_ms,
original_index=index,
+ runs_alone=threshold is not None and payload.sample_count > threshold,
)
)
total_cost += payload.duration_cost_ms
diff --git a/packages/sie_server/tests/adapters/test_whisper.py b/packages/sie_server/tests/adapters/test_whisper.py
index 53e4fbb54..9b9258960 100644
--- a/packages/sie_server/tests/adapters/test_whisper.py
+++ b/packages/sie_server/tests/adapters/test_whisper.py
@@ -2,11 +2,12 @@ from __future__ import annotations
from types import SimpleNamespace
from typing import Any
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
import numpy as np
import pytest
import torch
+import transformers
from sie_server.adapters.whisper.adapter import WhisperAdapter
from sie_server.core.prepared import AudioPayload, PreparedItem
from sie_server.core.preprocessor.audio import AudioPreprocessor
@@ -278,6 +279,73 @@ def test_direct_preprocessor_uses_rust_and_strips_encoded_audio(monkeypatch: pyt
assert batch.items[0].payload.duration_ms == 2
+def _decode_to_sample_counts(monkeypatch: pytest.MonkeyPatch, sample_counts: list[int]) -> None:
+ """Make the Rust decoder return one 16 kHz recording per sample count, in order."""
+ decoded = iter(sample_counts)
+
+ def decode_audio(data: bytes, fmt: str | None) -> dict[str, Any]:
+ sample_count = next(decoded)
+ return {
+ "pcm_s16le": b"",
+ "sample_rate": 16_000,
+ "sample_count": sample_count,
+ "duration_ms": sample_count // 16,
+ "source_sample_rate": 16_000,
+ "source_sample_count": sample_count,
+ "source_channels": 1,
+ "container": "wav",
+ }
+
+ monkeypatch.setattr(
+ "sie_server.core.preprocessor.audio.importlib.import_module",
+ lambda name: SimpleNamespace(decode_audio=decode_audio),
+ )
+
+
+def test_direct_preprocessor_flags_audio_past_the_threshold_to_run_alone(monkeypatch: pytest.MonkeyPatch) -> None:
+ items = [Item(audio={"data": b"encoded", "format": "wav"}) for _ in range(2)]
+
+ _decode_to_sample_counts(monkeypatch, [480_000, 480_001])
+ flagged = AudioPreprocessor(runs_alone_above_samples=480_000).prepare(items, config=MagicMock())
+ _decode_to_sample_counts(monkeypatch, [480_000, 480_001])
+ default = AudioPreprocessor().prepare(items, config=MagicMock())
+
+ assert [item.runs_alone for item in flagged.items] == [False, True]
+ assert [item.runs_alone for item in default.items] == [False, False]
+ # Cost stays the duration either way.
+ assert [item.cost for item in flagged.items] == [30_000, 30_000]
+
+
+def test_load_flags_audio_past_one_feature_window_to_run_alone(monkeypatch: pytest.MonkeyPatch) -> None:
+ processor = MagicMock()
+ processor.feature_extractor.n_samples = 160_000
+ adapter = WhisperAdapter("openai/whisper-large-v3-turbo")
+ # Resolve the lazy attributes first, or the patches below can miss the
+ # `from transformers import ...` inside load() and reach the Hub.
+ for name in ("AutoProcessor", "AutoModelForSpeechSeq2Seq", "pipeline"):
+ getattr(transformers, name)
+
+ with (
+ patch("transformers.AutoProcessor") as auto_processor,
+ patch("transformers.AutoModelForSpeechSeq2Seq") as auto_model,
+ patch("transformers.pipeline") as pipeline,
+ ):
+ auto_processor.from_pretrained.return_value = processor
+ adapter.load("cpu")
+
+ auto_processor.from_pretrained.assert_called_once()
+ auto_model.from_pretrained.assert_called_once()
+ pipeline.assert_called_once()
+ preprocessor = adapter.get_preprocessor()
+ assert preprocessor is not None
+ _decode_to_sample_counts(monkeypatch, [160_000, 160_001])
+ batch = preprocessor.prepare(
+ [Item(audio={"data": b"encoded", "format": "wav"}) for _ in range(2)],
+ config=MagicMock(),
+ )
+ assert [item.runs_alone for item in batch.items] == [False, True]
+
+
def test_direct_preprocessor_reports_missing_audio_extension(monkeypatch: pytest.MonkeyPatch) -> None:
def missing_extension(name: str) -> None:
raise ModuleNotFoundError(name=name)
diff --git a/packages/sie_server/tests/core/test_batcher.py b/packages/sie_server/tests/core/test_batcher.py
index 2333509a8..87a418e31 100644
--- a/packages/sie_server/tests/core/test_batcher.py
+++ b/packages/sie_server/tests/core/test_batcher.py
@@ -1,17 +1,20 @@
"""Tests for batch formation module."""
import asyncio
+import random
import time
+from dataclasses import dataclass
import pytest
from sie_server.core.batcher import (
BatchConfig,
BatchFormer,
FormattedBatch,
+ HasCost,
PendingRequest,
collate_batch,
)
-from sie_server.core.prepared import TextPayload, TextPreparedItem, make_text_item
+from sie_server.core.prepared import ExtractPreparedItem, TextPayload, TextPreparedItem, make_text_item
class TestPendingRequest:
@@ -1037,3 +1040,237 @@ class TestEffectiveCoalesce:
# Should fire near effective_coalesce (40ms), well before timeout (200ms)
assert elapsed_ms < 80, f"Waited too long: {elapsed_ms:.1f}ms"
assert elapsed_ms >= 30, f"Fired too early: {elapsed_ms:.1f}ms"
+
+
+@dataclass(slots=True)
+class _Audio:
+ """Audio item stub: cost is duration in ms, as ``AudioPreprocessor`` sets it."""
+
+ cost: int
+ original_index: int = 0
+ runs_alone: bool = False
+
+
+def _clip(seconds: float) -> _Audio:
+ return _Audio(cost=round(seconds * 1_000))
+
+
+def _long_form(seconds: float) -> _Audio:
+ return _Audio(cost=round(seconds * 1_000), runs_alone=True)
+
+
+def _arrive(batcher: BatchFormer[_Audio, str], item: _Audio, name: str, *, at: float) -> None:
+ """Queue ``item`` as if it arrived at monotonic time ``at``."""
+ batcher._append_item(item, name)
+ batcher._pending[-1].arrival_time = at
+
+
+def _greedy_reference(pending: list[tuple[int, int]], config: BatchConfig, max_items: int | None) -> list[int]:
+ """Cost-sorted greedy packing as it was before the runs_alone lane.
+
+ ``pending`` holds ``(cost, id)`` in queue order and is updated in place,
+ as ``BatchFormer`` updates its own queue.
+ """
+ pending.sort(key=lambda entry: entry[0])
+ taken: list[int] = []
+ batch_cost = 0
+ for cost, request_id in pending:
+ if max_items is not None and len(taken) >= max_items:
+ break
+ if batch_cost + cost > config.max_batch_cost and taken:
+ break
+ taken.append(request_id)
+ batch_cost += cost
+ if len(taken) >= config.max_batch_requests:
+ break
+ del pending[: len(taken)]
+ return taken
+
+
+class TestRunsAloneLane:
+ """Items flagged ``runs_alone`` (long-form audio, #585) never share a batch."""
+
+ @pytest.mark.parametrize("seed", range(20))
+ def test_unflagged_items_batch_exactly_as_cost_sorted_greedy_packing(self, seed: int) -> None:
+ """Without a flagged item pending, every batch matches the old algorithm."""
+ rng = random.Random(seed) # noqa: S311 -- reproducible test data
+ config = BatchConfig(max_batch_cost=rng.randint(1, 4_000), max_batch_requests=rng.randint(1, 8))
+ batcher: BatchFormer[HasCost, int] = BatchFormer(config)
+ reference: list[tuple[int, int]] = []
+ next_id = 0
+
+ for _ in range(60):
+ for _ in range(rng.randint(0, 5)):
+ cost = rng.randint(1, 1_500)
+ # Items with runs_alone=False and items without the attribute.
+ item: HasCost = _Audio(cost=cost) if rng.random() < 0.5 else ExtractPreparedItem(cost, 0)
+ batcher._append_item(item, next_id)
+ reference.append((cost, next_id))
+ next_id += 1
+ if not reference:
+ continue
+ max_items = rng.choice([None, None, 1, 2, 5])
+
+ batch = batcher._extract_batch(max_items=max_items)
+
+ assert batch.metadata == _greedy_reference(reference, config, max_items)
+ assert batcher.pending_count == len(reference)
+ assert batcher.pending_cost == sum(cost for cost, _ in reference)
+
+ def test_long_form_runs_alone_after_clips_that_arrived_around_it(self) -> None:
+ """Clips are not held in a long recording's batch (head-of-line wait)."""
+ batcher: BatchFormer[_Audio, str] = BatchFormer(BatchConfig(max_batch_cost=720_000))
+ _arrive(batcher, _clip(5), "clip-5s", at=0.0)
+ _arrive(batcher, _long_form(240), "long-240s", at=1.0)
+ _arrive(batcher, _clip(8), "clip-8s", at=2.0)
+
+ assert batcher._extract_batch().metadata == ["clip-5s", "clip-8s"]
+ assert batcher._extract_batch().metadata == ["long-240s"]
+ assert batcher.pending_count == 0
+
+ def test_long_form_items_run_in_arrival_order(self) -> None:
+ """An older long recording is not starved by a newer, shorter one."""
+ batcher: BatchFormer[_Audio, str] = BatchFormer(BatchConfig(max_batch_cost=720_000))
+ _arrive(batcher, _long_form(250), "long-250s", at=0.0)
+ _arrive(batcher, _long_form(190), "long-190s", at=1.0)
+
+ assert batcher._extract_batch().metadata == ["long-250s"]
+ assert batcher._extract_batch().metadata == ["long-190s"]
+
+ @pytest.mark.parametrize(("long_arrival", "order"), [(0.0, ["long", "clip"]), (2.0, ["clip", "long"])])
+ def test_first_batch_comes_from_the_lane_of_the_oldest_request(self, long_arrival: float, order: list[str]) -> None:
+ batcher: BatchFormer[_Audio, str] = BatchFormer(BatchConfig(max_batch_cost=720_000))
+ _arrive(batcher, _clip(5), "clip", at=1.0)
+ _arrive(batcher, _long_form(240), "long", at=long_arrival)
+
+ first = batcher._extract_batch().metadata
+ second = batcher._extract_batch().metadata
+ assert first + second == order
+
+ def test_lanes_take_turns_while_both_are_pending(self) -> None:
+ """Two long recordings and clips that keep arriving: clips, long, clips, long."""
+ batcher: BatchFormer[_Audio, str] = BatchFormer(BatchConfig(max_batch_cost=720_000))
+ _arrive(batcher, _clip(4), "clip-a", at=0.0)
+ _arrive(batcher, _clip(6), "clip-b", at=1.0)
+ _arrive(batcher, _long_form(240), "long-1", at=2.0)
+ _arrive(batcher, _long_form(200), "long-2", at=3.0)
+
+ served = []
+ for second in range(4, 9):
+ served.append(batcher._extract_batch().metadata)
+ # One clip lands while each batch runs.
+ _arrive(batcher, _clip(5), f"clip@{second}", at=float(second))
+
+ assert served == [
+ ["clip-a", "clip-b"],
+ ["long-1"],
+ ["clip@4", "clip@5"],
+ ["long-2"],
+ ["clip@6", "clip@7"],
+ ]
+ assert batcher.pending_count == 1
+
+ def test_long_form_amid_steady_clips_waits_for_one_clip_batch(self) -> None:
+ """Clip traffic that never lets up delays a flagged item by one clip batch.
+
+ A flagged recording just over 30 s is not held back for as long as
+ short traffic keeps the queue busy.
+ """
+ batcher: BatchFormer[_Audio, str] = BatchFormer(BatchConfig(max_batch_cost=720_000))
+ _arrive(batcher, _long_form(240), "long-240s", at=0.0)
+ assert batcher._extract_batch().metadata == ["long-240s"]
+
+ # A clip and a 31 s recording land while long-240s runs, and one more
+ # clip lands while each later batch runs.
+ _arrive(batcher, _clip(4), "clip@1", at=1.0)
+ _arrive(batcher, _long_form(31), "long-31s", at=2.0)
+ served = []
+ for second in range(3, 7):
+ _arrive(batcher, _clip(4), f"clip@{second}", at=float(second))
+ served.append(batcher._extract_batch().metadata)
+
+ assert served == [["clip@1", "clip@3"], ["long-31s"], ["clip@4", "clip@5"], ["clip@6"]]
+
+ @pytest.mark.asyncio
+ async def test_try_drain_takes_turns_and_keeps_counts_consistent(self) -> None:
+ batcher: BatchFormer[_Audio, str] = BatchFormer(BatchConfig(max_batch_cost=720_000))
+ await batcher.submit_many(
+ [
+ (_clip(5), "clip-5s"),
+ (_long_form(240), "long-240s"),
+ (_clip(8), "clip-8s"),
+ (_long_form(200), "long-200s"),
+ (_clip(3), "clip-3s"),
+ ]
+ )
+
+ expected = [
+ (1, ["clip-3s"], 4, 453_000),
+ (4, ["long-240s"], 3, 213_000),
+ (2, ["clip-5s", "clip-8s"], 1, 200_000),
+ (None, ["long-200s"], 0, 0),
+ ]
+ for max_items, names, pending_count, pending_cost in expected:
+ batch = await batcher.try_drain(max_items=max_items)
+ assert batch is not None
+ assert batch.metadata == names
+ assert batch.total_cost == sum(item.cost for item in batch.items)
+ assert batcher.pending_count == pending_count
+ assert batcher.pending_cost == pending_cost
+ assert await batcher.try_drain() is None
+ assert batcher._first_request_time is None
+ assert batcher._last_submit_time is None
+
+ @pytest.mark.parametrize("max_batch_cost", [180_000, 2_880_000])
+ def test_lanes_never_mix_and_take_turns_at_any_cost_cap(self, max_batch_cost: int) -> None:
+ """Holds at both ends of Whisper's adaptive cost range."""
+ rng = random.Random(max_batch_cost) # noqa: S311 -- reproducible test data
+ batcher: BatchFormer[_Audio, str] = BatchFormer(BatchConfig(max_batch_cost=max_batch_cost))
+ submitted: set[str] = set()
+ served: list[str] = []
+ last_alone: bool | None = None
+ # Pending flagged item -> [flagged items ahead of it on arrival, clip batches since].
+ flagged_waits: dict[str, list[int]] = {}
+
+ def extract() -> None:
+ nonlocal last_alone
+ pending = list(batcher._pending)
+ batch = batcher._extract_batch(max_items=rng.choice([None, 1, 3]))
+ assert batch.size > 0
+ alone = batch.items[0].runs_alone
+ assert all(item.runs_alone is alone for item in batch.items)
+ if alone:
+ assert batch.size == 1
+ if {request.runs_alone for request in pending} == {True, False}:
+ # The lanes take turns, starting with the lane of the oldest request.
+ oldest_alone = min(pending, key=lambda request: request.arrival_time).runs_alone
+ assert alone is (oldest_alone if last_alone is None else not last_alone)
+ last_alone = alone
+ if alone:
+ ahead, clip_batches = flagged_waits.pop(batch.metadata[0])
+ assert clip_batches <= ahead + 1
+ else:
+ for wait in flagged_waits.values():
+ wait[1] += 1
+ served.extend(batch.metadata)
+
+ now = 0.0
+ for index in range(300):
+ now += rng.uniform(0.0, 2.0)
+ if rng.random() < 0.6:
+ name = f"item-{index}"
+ if rng.random() < 0.3:
+ flagged_waits[name] = [len(flagged_waits), 0]
+ item = _long_form(rng.uniform(30.001, 300.0))
+ else:
+ item = _clip(rng.uniform(1.0, 30.0))
+ _arrive(batcher, item, name, at=now)
+ submitted.add(name)
+ if batcher.pending_count and rng.random() < 0.5:
+ extract()
+ while batcher.pending_count:
+ extract()
+
+ assert sorted(served) == sorted(submitted)
+ assert not flagged_waits
+ assert batcher.pending_cost == 0
diff --git a/packages/sie_server/tests/core/test_worker_extract.py b/packages/sie_server/tests/core/test_worker_extract.py
index d9c375050..6b773019e 100644
--- a/packages/sie_server/tests/core/test_worker_extract.py
+++ b/packages/sie_server/tests/core/test_worker_extract.py
@@ -1,8 +1,11 @@
import asyncio
+import threading
+from typing import Any
from unittest.mock import MagicMock
import pytest
from sie_server.core.inference_output import ExtractOutput
+from sie_server.core.prepared import AudioPayload, PreparedItem
from sie_server.core.worker import ModelWorker, WorkerConfig
from sie_server.types.inputs import Item
from sie_server.types.responses import Entity
@@ -204,6 +207,76 @@ class TestModelWorkerExtractIsolation:
await worker.stop()
+def _audio_item(duration_ms: int) -> PreparedItem[AudioPayload]:
+ """Prepared 16 kHz audio, flagged runs_alone past Whisper's 30 s window."""
+ sample_count = duration_ms * 16
+ payload = AudioPayload(
+ pcm_s16le=b"",
+ sample_rate=16_000,
+ sample_count=sample_count,
+ duration_ms=duration_ms,
+ source_sample_rate=16_000,
+ source_sample_count=sample_count,
+ source_channels=1,
+ container="wav",
+ )
+ return PreparedItem(
+ payload=payload,
+ cost=payload.duration_cost_ms,
+ original_index=0,
+ runs_alone=sample_count > 480_000,
+ )
+
+
+class TestModelWorkerExtractRunsAlone:
+ @pytest.mark.asyncio
+ async def test_long_form_audio_and_clips_take_turns_in_separate_calls(self) -> None:
+ """Long-form audio gets its own adapter call, taking turns with clip calls (#585)."""
+ calls: list[list[int]] = []
+ lanes: list[set[bool]] = []
+ call_started = threading.Semaphore(0)
+ call_released = threading.Semaphore(0)
+
+ def extract(items: list[Item], *, prepared_items: list[Any], **kwargs: Any) -> ExtractOutput:
+ calls.append([prepared.payload.duration_ms for prepared in prepared_items])
+ lanes.append({prepared.runs_alone for prepared in prepared_items})
+ call_started.release()
+ call_released.acquire(timeout=10.0)
+ return ExtractOutput(entities=[[] for _ in items])
+
+ adapter = MagicMock()
+ adapter.extract.side_effect = extract
+ # Whisper's audio cap: today's packing would put clips and long-form audio in one call.
+ worker = ModelWorker(adapter, WorkerConfig(max_batch_tokens=720_000, max_batch_wait_ms=20))
+
+ async def submit(duration_ms: int) -> asyncio.Future[Any]:
+ return await worker.submit_extract([_audio_item(duration_ms)], [Item()])
+
+ async def wait_for_next_call() -> None:
+ assert await asyncio.to_thread(call_started.acquire, timeout=5.0)
+
+ await worker.start()
+ try:
+ futures = [await submit(4_000)]
+ await wait_for_next_call()
+ # Two long recordings and a clip land while the first call runs,
+ # then one more clip lands while each later call runs.
+ futures += [await submit(duration_ms) for duration_ms in (240_000, 200_000, 6_000)]
+ for duration_ms in (5_000, 7_000, 3_000):
+ call_released.release()
+ await wait_for_next_call()
+ futures.append(await submit(duration_ms))
+ call_released.release(2)
+ await asyncio.wait_for(asyncio.gather(*futures), timeout=5.0)
+ finally:
+ call_released.release(10)
+ await worker.stop()
+
+ # No call mixes long-form audio with clips, and the two take turns.
+ assert lanes == [{False}, {True}, {False}, {True}, {False}]
+ assert calls == [[4_000], [240_000], [5_000, 6_000], [200_000], [3_000, 7_000]]
+
+
class TestModelWorkerExtractBackpressure:
"""Tests for extract backpressure."""