oxibonsai-runtime 0.1.4

Inference runtime, sampling, tokenizer, and server for OxiBonsai
Documentation
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! Bounded request queue with backpressure for the inference pipeline.
//!
//! [`BoundedQueue`] is a generic FIFO queue with a fixed capacity.  When the
//! queue is full, [`BoundedQueue::try_push`] returns `false` immediately,
//! allowing the caller to issue an HTTP 503 response rather than blocking
//! indefinitely.  [`BoundedQueue::push_timeout`] blocks for up to a given
//! [`Duration`] waiting for a slot to become available.
//!
//! [`InferenceQueue`] builds on top of [`BoundedQueue`] and wraps every
//! submitted work item with a one-shot [`std::sync::mpsc`] channel so that
//! callers can await the inference result asynchronously.

use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

use crate::sampling::SamplingParams;

// ─────────────────────────────────────────────────────────────────────────────
// QueueStats
// ─────────────────────────────────────────────────────────────────────────────

/// A serialisable snapshot of queue utilisation.
#[derive(Debug, Clone, serde::Serialize)]
pub struct QueueStats {
    /// Number of items currently waiting in the queue.
    pub len: usize,
    /// Maximum number of items the queue can hold.
    pub capacity: usize,
    /// `len / capacity` as a fraction in `[0.0, 1.0]`.
    pub utilization: f32,
    /// Total items ever successfully enqueued.
    pub total_enqueued: u64,
    /// Total items ever successfully dequeued.
    pub total_dequeued: u64,
    /// Total items dropped due to backpressure.
    pub total_dropped: u64,
    /// `total_dropped / (total_enqueued + total_dropped)`.
    pub drop_rate: f32,
}

// ─────────────────────────────────────────────────────────────────────────────
// BoundedQueue
// ─────────────────────────────────────────────────────────────────────────────

/// Thread-safe bounded FIFO queue with condvar-based blocking and backpressure.
///
/// The internal state is stored behind a `Mutex<VecDeque<(T, Instant)>>`.
/// Two [`Condvar`]s (`not_empty` and `not_full`) allow producers and consumers
/// to park efficiently instead of busy-waiting.
pub struct BoundedQueue<T> {
    /// Inner queue guarded by a mutex.
    queue: Mutex<VecDeque<(T, Instant)>>,
    /// Signalled whenever an item is pushed.
    not_empty: Condvar,
    /// Signalled whenever an item is popped.
    not_full: Condvar,
    /// Hard capacity limit.
    capacity: usize,
    /// Cumulative items enqueued without being dropped.
    pub total_enqueued: AtomicU64,
    /// Cumulative items dequeued.
    pub total_dequeued: AtomicU64,
    /// Cumulative items rejected due to a full queue.
    pub total_dropped: AtomicU64,
}

impl<T: Send> BoundedQueue<T> {
    /// Create a new bounded queue with the given maximum capacity.
    pub fn new(capacity: usize) -> Self {
        assert!(capacity > 0, "queue capacity must be at least 1");
        Self {
            queue: Mutex::new(VecDeque::with_capacity(capacity)),
            not_empty: Condvar::new(),
            not_full: Condvar::new(),
            capacity,
            total_enqueued: AtomicU64::new(0),
            total_dequeued: AtomicU64::new(0),
            total_dropped: AtomicU64::new(0),
        }
    }

    /// Attempt to push `item` without blocking.
    ///
    /// Returns `true` on success, `false` if the queue is already at capacity
    /// (backpressure: the caller should propagate a 503 to the client).
    pub fn try_push(&self, item: T) -> bool {
        let mut guard = self
            .queue
            .lock()
            .expect("queue mutex should not be poisoned");

        if guard.len() >= self.capacity {
            self.total_dropped.fetch_add(1, Ordering::Relaxed);
            return false;
        }

        guard.push_back((item, Instant::now()));
        self.total_enqueued.fetch_add(1, Ordering::Relaxed);
        self.not_empty.notify_one();
        true
    }

    /// Push `item`, blocking up to `timeout` for a free slot.
    ///
    /// Returns `true` if the item was enqueued before the timeout elapsed,
    /// `false` otherwise.
    pub fn push_timeout(&self, item: T, timeout: Duration) -> bool {
        let deadline = Instant::now() + timeout;

        let mut guard = self
            .queue
            .lock()
            .expect("queue mutex should not be poisoned");

        loop {
            if guard.len() < self.capacity {
                guard.push_back((item, Instant::now()));
                self.total_enqueued.fetch_add(1, Ordering::Relaxed);
                self.not_empty.notify_one();
                return true;
            }

            let remaining = match deadline.checked_duration_since(Instant::now()) {
                Some(d) => d,
                None => {
                    self.total_dropped.fetch_add(1, Ordering::Relaxed);
                    return false;
                }
            };

            let (new_guard, timed_out) = self
                .not_full
                .wait_timeout(guard, remaining)
                .expect("queue condvar should not be poisoned");
            guard = new_guard;

            if timed_out.timed_out() {
                self.total_dropped.fetch_add(1, Ordering::Relaxed);
                return false;
            }
        }
    }

    /// Remove and return the oldest item without blocking.
    ///
    /// Returns `None` if the queue is empty.
    pub fn pop(&self) -> Option<T> {
        let mut guard = self
            .queue
            .lock()
            .expect("queue mutex should not be poisoned");

        guard.pop_front().map(|(item, _enqueued_at)| {
            self.total_dequeued.fetch_add(1, Ordering::Relaxed);
            self.not_full.notify_one();
            item
        })
    }

    /// Remove and return the oldest item, blocking up to `timeout` for one to
    /// become available.
    ///
    /// Returns `None` on timeout.
    pub fn pop_timeout(&self, timeout: Duration) -> Option<T> {
        let deadline = Instant::now() + timeout;

        let mut guard = self
            .queue
            .lock()
            .expect("queue mutex should not be poisoned");

        loop {
            if let Some((item, _)) = guard.pop_front() {
                self.total_dequeued.fetch_add(1, Ordering::Relaxed);
                self.not_full.notify_one();
                return Some(item);
            }

            let remaining = deadline.checked_duration_since(Instant::now())?;

            let (new_guard, timed_out) = self
                .not_empty
                .wait_timeout(guard, remaining)
                .expect("queue condvar should not be poisoned");
            guard = new_guard;

            if timed_out.timed_out() && guard.is_empty() {
                return None;
            }
        }
    }

    /// Current number of items in the queue.
    pub fn len(&self) -> usize {
        self.queue
            .lock()
            .expect("queue mutex should not be poisoned")
            .len()
    }

    /// `true` if the queue contains no items.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// `true` if the queue is at capacity.
    pub fn is_full(&self) -> bool {
        self.len() >= self.capacity
    }

    /// Maximum number of items the queue can hold.
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Current fill level as a fraction in `[0.0, 1.0]`.
    pub fn utilization(&self) -> f32 {
        self.len() as f32 / self.capacity as f32
    }

    /// Take a snapshot of queue statistics.
    pub fn stats(&self) -> QueueStats {
        let len = self.len();
        let enqueued = self.total_enqueued.load(Ordering::Relaxed);
        let dropped = self.total_dropped.load(Ordering::Relaxed);
        let attempted = enqueued + dropped;
        let drop_rate = if attempted == 0 {
            0.0
        } else {
            dropped as f32 / attempted as f32
        };

        QueueStats {
            len,
            capacity: self.capacity,
            utilization: len as f32 / self.capacity as f32,
            total_enqueued: enqueued,
            total_dequeued: self.total_dequeued.load(Ordering::Relaxed),
            total_dropped: dropped,
            drop_rate,
        }
    }

    /// Drain all items from the queue and return them in FIFO order.
    pub fn drain(&self) -> Vec<T> {
        let mut guard = self
            .queue
            .lock()
            .expect("queue mutex should not be poisoned");

        let count = guard.len();
        let items: Vec<T> = guard.drain(..).map(|(item, _)| item).collect();
        self.total_dequeued
            .fetch_add(count as u64, Ordering::Relaxed);
        self.not_full.notify_all();
        items
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// InferenceWorkItem
// ─────────────────────────────────────────────────────────────────────────────

/// A single unit of work to be processed by the inference engine.
pub struct InferenceWorkItem {
    /// Unique monotonically-increasing request identifier.
    pub id: u64,
    /// Pre-tokenised prompt.
    pub prompt_tokens: Vec<u32>,
    /// Maximum number of tokens to generate.
    pub max_tokens: usize,
    /// Sampling hyper-parameters for this request.
    pub params: SamplingParams,
    /// Wall-clock time at which this item was submitted to the queue.
    pub created_at: Instant,
    /// Channel through which the inference result is delivered.
    pub result_tx: std::sync::mpsc::SyncSender<Vec<u32>>,
}

impl InferenceWorkItem {
    /// How long this item has been waiting in the queue.
    pub fn wait_time(&self) -> Duration {
        self.created_at.elapsed()
    }

    /// Whether this item has been waiting longer than `ttl`.
    pub fn is_expired(&self, ttl: Duration) -> bool {
        self.wait_time() > ttl
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// InferenceQueue
// ─────────────────────────────────────────────────────────────────────────────

/// High-level inference request queue wrapping [`BoundedQueue<InferenceWorkItem>`].
///
/// Each call to [`InferenceQueue::submit`] returns a [`std::sync::mpsc::Receiver`]
/// through which the caller can retrieve the generated token IDs once inference
/// completes.  Returns `None` immediately if the queue is full (backpressure).
pub struct InferenceQueue {
    queue: Arc<BoundedQueue<InferenceWorkItem>>,
    next_id: AtomicU64,
}

impl InferenceQueue {
    /// Create a new inference queue with the given maximum pending-request capacity.
    pub fn new(capacity: usize) -> Self {
        Self {
            queue: Arc::new(BoundedQueue::new(capacity)),
            next_id: AtomicU64::new(1),
        }
    }

    /// Submit an inference request.
    ///
    /// Returns a `Receiver` that will yield the generated token IDs once the
    /// request is processed, or `None` if the queue is full.
    pub fn submit(
        &self,
        prompt_tokens: Vec<u32>,
        max_tokens: usize,
        params: SamplingParams,
    ) -> Option<std::sync::mpsc::Receiver<Vec<u32>>> {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let (tx, rx) = std::sync::mpsc::sync_channel(1);

        let item = InferenceWorkItem {
            id,
            prompt_tokens,
            max_tokens,
            params,
            created_at: Instant::now(),
            result_tx: tx,
        };

        if self.queue.try_push(item) {
            Some(rx)
        } else {
            None
        }
    }

    /// Number of pending requests currently in the queue.
    pub fn queue_depth(&self) -> usize {
        self.queue.len()
    }

    /// `true` if the queue is at capacity.
    pub fn is_full(&self) -> bool {
        self.queue.is_full()
    }

    /// Take a statistics snapshot.
    pub fn stats(&self) -> QueueStats {
        self.queue.stats()
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::Ordering;

    // ── BoundedQueue ──────────────────────────────────────────────────────

    #[test]
    fn test_bounded_queue_try_push() {
        let q: BoundedQueue<u32> = BoundedQueue::new(4);
        assert!(q.try_push(1));
        assert!(q.try_push(2));
        assert_eq!(q.len(), 2);
        assert_eq!(q.total_enqueued.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn test_bounded_queue_try_push_full_returns_false() {
        let q: BoundedQueue<u32> = BoundedQueue::new(2);
        assert!(q.try_push(10));
        assert!(q.try_push(20));
        // Queue is now full — further push must fail.
        assert!(!q.try_push(30));
        assert_eq!(q.total_dropped.load(Ordering::Relaxed), 1);
        assert_eq!(q.len(), 2);
    }

    #[test]
    fn test_bounded_queue_pop_empty_returns_none() {
        let q: BoundedQueue<u32> = BoundedQueue::new(4);
        assert_eq!(q.pop(), None);
    }

    #[test]
    fn test_bounded_queue_fifo_order() {
        let q: BoundedQueue<u32> = BoundedQueue::new(8);
        for i in 0..5u32 {
            assert!(q.try_push(i));
        }
        for expected in 0..5u32 {
            assert_eq!(q.pop(), Some(expected));
        }
        assert_eq!(q.pop(), None);
    }

    #[test]
    fn test_bounded_queue_stats() {
        let q: BoundedQueue<u32> = BoundedQueue::new(4);
        q.try_push(1);
        q.try_push(2);
        q.pop();

        let stats = q.stats();
        assert_eq!(stats.capacity, 4);
        assert_eq!(stats.len, 1);
        assert_eq!(stats.total_enqueued, 2);
        assert_eq!(stats.total_dequeued, 1);
        assert_eq!(stats.total_dropped, 0);
        assert!((stats.utilization - 0.25).abs() < f32::EPSILON);
    }

    #[test]
    fn test_bounded_queue_drain() {
        let q: BoundedQueue<u32> = BoundedQueue::new(8);
        for i in 0..4u32 {
            q.try_push(i);
        }
        let items = q.drain();
        assert_eq!(items, vec![0, 1, 2, 3]);
        assert_eq!(q.len(), 0);
        assert_eq!(q.total_dequeued.load(Ordering::Relaxed), 4);
    }

    // ── InferenceQueue ────────────────────────────────────────────────────

    #[test]
    fn test_inference_queue_submit_and_depth() {
        let iq = InferenceQueue::new(8);
        let _rx1 = iq
            .submit(vec![1, 2, 3], 16, SamplingParams::default())
            .expect("submit should succeed on an empty queue");
        let _rx2 = iq
            .submit(vec![4, 5, 6], 16, SamplingParams::default())
            .expect("second submit should succeed");

        assert_eq!(iq.queue_depth(), 2);
        assert!(!iq.is_full());
    }

    #[test]
    fn test_inference_queue_full_returns_none() {
        let iq = InferenceQueue::new(2);

        let _rx1 = iq
            .submit(vec![1], 8, SamplingParams::default())
            .expect("first submit");
        let _rx2 = iq
            .submit(vec![2], 8, SamplingParams::default())
            .expect("second submit");

        // Queue is now full — next submit must return None.
        assert!(iq.is_full());
        let result = iq.submit(vec![3], 8, SamplingParams::default());
        assert!(result.is_none(), "submit to a full queue must return None");
    }
}