1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//! Simple request batching service for continuous batching.
//!
//! This module provides request batching that queues incoming requests and
//! processes them in batches using the engine's generate_batch API.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, oneshot};
use tracing::{debug, info};
use abaddon::engine::InferenceEngine;
use infernum_core::request::GenerateRequest;
use infernum_core::response::GenerateResponse;
use infernum_core::Error;
/// Configuration for the request batcher.
#[derive(Debug, Clone)]
pub struct BatcherConfig {
/// Maximum number of requests per batch.
pub max_batch_size: usize,
/// Maximum time to wait for batch formation.
pub max_wait_time: Duration,
/// Minimum time between batches (prevents thrashing).
pub min_batch_interval: Duration,
/// Maximum queue size before rejecting requests.
pub max_queue_size: usize,
}
impl Default for BatcherConfig {
fn default() -> Self {
Self {
max_batch_size: 8,
max_wait_time: Duration::from_millis(50),
min_batch_interval: Duration::from_millis(10),
max_queue_size: 100,
}
}
}
/// Statistics for the batcher.
#[derive(Debug, Default)]
pub struct BatcherStats {
/// Total number of requests submitted to the batcher.
pub requests_submitted: AtomicU64,
/// Total number of requests that completed successfully.
pub requests_completed: AtomicU64,
/// Total number of requests rejected (e.g., queue full).
pub requests_rejected: AtomicU64,
/// Total number of batches processed.
pub batches_processed: AtomicU64,
/// Cumulative batch processing time in milliseconds.
pub total_batch_time_ms: AtomicU64,
}
impl BatcherStats {
/// Returns the average batch processing time in milliseconds.
pub fn avg_batch_time_ms(&self) -> f64 {
let batches = self.batches_processed.load(Ordering::Relaxed);
if batches == 0 {
return 0.0;
}
self.total_batch_time_ms.load(Ordering::Relaxed) as f64 / batches as f64
}
}
/// A pending request with its response channel.
struct PendingRequest {
request: GenerateRequest,
response_tx: oneshot::Sender<Result<GenerateResponse, Error>>,
submitted_at: Instant,
}
/// Handle for submitting requests to the batcher.
#[derive(Clone)]
pub struct BatcherHandle {
request_tx: mpsc::Sender<PendingRequest>,
stats: Arc<BatcherStats>,
config: BatcherConfig,
}
impl BatcherHandle {
/// Submits a request and returns a receiver for the response.
pub async fn submit(
&self,
request: GenerateRequest,
) -> Result<oneshot::Receiver<Result<GenerateResponse, Error>>, Error> {
let (response_tx, response_rx) = oneshot::channel();
let pending = PendingRequest {
request,
response_tx,
submitted_at: Instant::now(),
};
self.request_tx
.send(pending)
.await
.map_err(|_| Error::internal("Batcher channel closed"))?;
self.stats
.requests_submitted
.fetch_add(1, Ordering::Relaxed);
Ok(response_rx)
}
/// Returns current statistics.
pub fn stats(&self) -> &BatcherStats {
&self.stats
}
/// Returns the configuration.
pub fn config(&self) -> &BatcherConfig {
&self.config
}
}
/// The request batcher service.
pub struct RequestBatcher {
config: BatcherConfig,
stats: Arc<BatcherStats>,
shutdown: Arc<AtomicBool>,
}
impl RequestBatcher {
/// Creates a new request batcher with the given configuration.
pub fn new(config: BatcherConfig) -> Self {
Self {
config,
stats: Arc::new(BatcherStats::default()),
shutdown: Arc::new(AtomicBool::new(false)),
}
}
/// Starts the batcher and returns a handle for submitting requests.
///
/// The batcher runs a background task that collects requests into batches
/// and processes them using the engine's generate_batch API.
pub fn start<E: InferenceEngine + Send + Sync + 'static>(
self,
engine: Arc<E>,
) -> BatcherHandle {
let (request_tx, mut request_rx) =
mpsc::channel::<PendingRequest>(self.config.max_queue_size);
let config = self.config.clone();
let stats = self.stats.clone();
let shutdown = self.shutdown.clone();
// Spawn the batch processing task
tokio::spawn(async move {
let mut pending_batch: Vec<PendingRequest> = Vec::with_capacity(config.max_batch_size);
let mut last_batch_time = Instant::now();
info!(
max_batch_size = config.max_batch_size,
max_wait_ms = config.max_wait_time.as_millis(),
"Request batcher started"
);
loop {
// Check for shutdown
if shutdown.load(Ordering::Relaxed) {
info!("Request batcher shutting down");
// Drain remaining requests with errors
for pending in pending_batch.drain(..) {
let _ = pending
.response_tx
.send(Err(Error::internal("Server shutting down")));
}
break;
}
// Wait for requests with timeout
let timeout = if pending_batch.is_empty() {
// No pending requests, wait longer
Duration::from_secs(1)
} else {
// Have pending requests, use max wait time
config.max_wait_time
};
match tokio::time::timeout(timeout, request_rx.recv()).await {
Ok(Some(request)) => {
pending_batch.push(request);
},
Ok(None) => {
// Channel closed, shutdown
info!("Request channel closed, shutting down batcher");
break;
},
Err(_) => {
// Timeout - process batch if we have requests
},
}
// Check if we should process the batch
let should_process = !pending_batch.is_empty()
&& (pending_batch.len() >= config.max_batch_size
|| pending_batch
.first()
.map(|r| r.submitted_at.elapsed() >= config.max_wait_time)
.unwrap_or(false));
if !should_process {
continue;
}
// Enforce minimum batch interval
let since_last = last_batch_time.elapsed();
if since_last < config.min_batch_interval {
tokio::time::sleep(config.min_batch_interval - since_last).await;
}
// Take the batch
let batch: Vec<_> = pending_batch
.drain(..pending_batch.len().min(config.max_batch_size))
.collect();
let batch_size = batch.len();
let batch_start = Instant::now();
debug!(batch_size = batch_size, "Processing request batch");
// Extract requests and channels
let (requests, channels): (Vec<_>, Vec<_>) = batch
.into_iter()
.map(|p| (p.request, p.response_tx))
.unzip();
// Process batch
let results = engine.generate_batch(requests).await;
// Send results back
for (result, response_tx) in results.into_iter().zip(channels) {
let _ = response_tx.send(result);
stats.requests_completed.fetch_add(1, Ordering::Relaxed);
}
// Update stats
let batch_time = batch_start.elapsed().as_millis() as u64;
stats.batches_processed.fetch_add(1, Ordering::Relaxed);
stats
.total_batch_time_ms
.fetch_add(batch_time, Ordering::Relaxed);
debug!(
batch_size = batch_size,
batch_time_ms = batch_time,
"Batch completed"
);
last_batch_time = Instant::now();
}
});
BatcherHandle {
request_tx,
stats: self.stats,
config: self.config,
}
}
/// Signals the batcher to shut down.
pub fn shutdown(&self) {
self.shutdown.store(true, Ordering::Relaxed);
}
}