litellm-rs 0.8.2

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
//! Non-blocking ordered runtime for integration lifecycle callbacks.

use std::sync::Arc;

use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tracing::{error, warn};

use super::IntegrationManager;
use crate::core::traits::integration::{
    EmbeddingEndEvent, EmbeddingErrorEvent, EmbeddingStartEvent, GuardrailDecisionEvent,
    IntegrationError, IntegrationResult, LlmEndEvent, LlmErrorEvent, LlmStartEvent, LlmStreamEvent,
};

pub(crate) trait CallbackMetrics: Send + Sync {
    #[cfg(any(feature = "gateway", test))]
    fn begin_llm_lifecycle(&self, event: &LlmStartEvent);
    #[cfg(any(feature = "gateway", test))]
    fn finish_llm_lifecycle(&self, event: &LlmEndEvent);
    #[cfg(feature = "gateway")]
    fn fail_llm_lifecycle(&self, event: &LlmErrorEvent);
    #[cfg(any(feature = "gateway", test))]
    fn cancel_llm_lifecycle(&self, event: &LlmStartEvent);
    #[cfg(feature = "gateway")]
    fn record_embedding_start(&self, event: &EmbeddingStartEvent);
    #[cfg(feature = "gateway")]
    fn record_embedding_end(&self, event: &EmbeddingEndEvent);
    fn render(&self) -> String;
}

pub(crate) type CallbackMetricsRecorder = Arc<dyn CallbackMetrics>;

#[derive(Debug)]
enum CallbackEvent {
    Start(LlmStartEvent),
    End(LlmEndEvent),
    Error(LlmErrorEvent),
    Stream(LlmStreamEvent),
    EmbeddingStart(EmbeddingStartEvent),
    EmbeddingEnd(EmbeddingEndEvent),
    EmbeddingError(EmbeddingErrorEvent),
    GuardrailDecision(GuardrailDecisionEvent),
}

/// Error returned when an event cannot enter the non-blocking callback queue.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum CallbackDispatchError {
    /// The bounded queue is at capacity.
    #[error("callback queue is full")]
    QueueFull,
    /// The callback worker is no longer accepting events.
    #[error("callback queue is closed")]
    QueueClosed,
}

/// Cloneable request-path handle for non-blocking callback delivery.
#[derive(Clone, Default)]
pub struct CallbackDispatcher {
    sender: Option<mpsc::Sender<CallbackEvent>>,
    manager: Option<Arc<IntegrationManager>>,
    callback_metrics: Option<CallbackMetricsRecorder>,
}

/// Capacity reserved for the terminal event of an admitted lifecycle.
pub struct CallbackTerminalPermit {
    permit: Option<mpsc::OwnedPermit<CallbackEvent>>,
}

impl CallbackTerminalPermit {
    /// Enqueue an LLM success using its reserved capacity.
    pub fn emit_end(self, event: LlmEndEvent) {
        if let Some(permit) = self.permit {
            permit.send(CallbackEvent::End(event));
        }
    }

    /// Enqueue an LLM error using its reserved capacity.
    pub fn emit_error(self, event: LlmErrorEvent) {
        if let Some(permit) = self.permit {
            permit.send(CallbackEvent::Error(event));
        }
    }

    /// Enqueue an embedding success using its reserved capacity.
    pub fn emit_embedding_end(self, event: EmbeddingEndEvent) {
        if let Some(permit) = self.permit {
            permit.send(CallbackEvent::EmbeddingEnd(event));
        }
    }

    /// Enqueue an embedding error using its reserved capacity.
    pub fn emit_embedding_error(self, event: EmbeddingErrorEvent) {
        if let Some(permit) = self.permit {
            permit.send(CallbackEvent::EmbeddingError(event));
        }
    }
}

#[cfg(any(feature = "gateway", test))]
enum CallbackMetricsKind {
    Llm(Box<LlmStartEvent>),
    #[cfg(feature = "gateway")]
    Embedding,
}

/// Request lifecycle guard for synchronous in-process callback metrics.
///
/// This is deliberately separate from [`CallbackTerminalPermit`]: exporter
/// queue admission keeps its public failure semantics, while metrics never
/// enter that queue. Dropping an unfinished LLM guard releases the active
/// request gauge during cancellation, task abortion, or panic unwinding.
#[cfg(any(feature = "gateway", test))]
pub(crate) struct CallbackMetricsPermit {
    recorder: CallbackMetricsRecorder,
    kind: CallbackMetricsKind,
    completed: bool,
}

#[cfg(any(feature = "gateway", test))]
impl CallbackMetricsPermit {
    #[cfg(feature = "gateway")]
    pub(crate) fn update_llm_target(&mut self, model: &str, provider: &str) {
        if let CallbackMetricsKind::Llm(event) = &mut self.kind {
            event.model = model.to_string();
            event.provider = Some(provider.to_string());
        }
    }

    pub(crate) fn emit_end(mut self, event: &LlmEndEvent) {
        self.recorder.finish_llm_lifecycle(event);
        self.completed = true;
    }

    #[cfg(feature = "gateway")]
    pub(crate) fn emit_error(mut self, event: &LlmErrorEvent) {
        if matches!(self.kind, CallbackMetricsKind::Llm(_)) {
            self.recorder.fail_llm_lifecycle(event);
        }
        self.completed = true;
    }

    #[cfg(feature = "gateway")]
    pub(crate) fn emit_embedding_end(mut self, event: &EmbeddingEndEvent) {
        self.recorder.record_embedding_end(event);
        self.completed = true;
    }

    #[cfg(feature = "gateway")]
    pub(crate) fn emit_embedding_error(mut self) {
        self.completed = true;
    }
}

#[cfg(any(feature = "gateway", test))]
impl Drop for CallbackMetricsPermit {
    fn drop(&mut self) {
        if !self.completed
            && let CallbackMetricsKind::Llm(event) = &self.kind
        {
            self.recorder.cancel_llm_lifecycle(event);
        }
    }
}

impl CallbackDispatcher {
    /// Create a dispatcher that performs no external callback work.
    pub fn disabled() -> Self {
        Self::default()
    }

    /// Whether this dispatcher has exporter delivery or in-process metrics enabled.
    pub fn is_enabled(&self) -> bool {
        self.sender.is_some() || self.callback_metrics.is_some()
    }

    /// List the callback integrations registered with this dispatcher.
    pub async fn registered_integrations(&self) -> Vec<&'static str> {
        let mut integrations = match &self.manager {
            Some(manager) => manager.list_integrations().await,
            None => Vec::new(),
        };
        if self.callback_metrics.is_some() {
            integrations.push("prometheus");
        }
        integrations
    }

    /// Render metrics from the configured Prometheus callback backend.
    pub fn render_prometheus_metrics(&self) -> Option<String> {
        self.callback_metrics
            .as_ref()
            .map(|metrics| metrics.render())
    }

    /// Atomically admit an LLM start and reserve capacity for its terminal event.
    pub fn begin_llm(
        &self,
        event: LlmStartEvent,
    ) -> Result<CallbackTerminalPermit, CallbackDispatchError> {
        self.begin(CallbackEvent::Start(event))
    }

    /// Atomically admit an embedding start and reserve its terminal capacity.
    pub fn begin_embedding(
        &self,
        event: EmbeddingStartEvent,
    ) -> Result<CallbackTerminalPermit, CallbackDispatchError> {
        self.begin(CallbackEvent::EmbeddingStart(event))
    }

    /// Enqueue an LLM start event without waiting for exporter I/O.
    pub fn emit_start(&self, event: LlmStartEvent) -> Result<(), CallbackDispatchError> {
        self.try_send(CallbackEvent::Start(event))
    }

    /// Enqueue an LLM success event without waiting for exporter I/O.
    pub fn emit_end(&self, event: LlmEndEvent) -> Result<(), CallbackDispatchError> {
        self.try_send(CallbackEvent::End(event))
    }

    /// Enqueue an LLM error event without waiting for exporter I/O.
    pub fn emit_error(&self, event: LlmErrorEvent) -> Result<(), CallbackDispatchError> {
        self.try_send(CallbackEvent::Error(event))
    }

    /// Enqueue an LLM stream event without waiting for exporter I/O.
    pub fn emit_stream(&self, event: LlmStreamEvent) -> Result<(), CallbackDispatchError> {
        self.try_send(CallbackEvent::Stream(event))
    }

    /// Enqueue a sanitized guardrail decision. Queue pressure is observable only.
    pub fn emit_guardrail_decision(&self, event: GuardrailDecisionEvent) {
        if let Err(error) = self.try_send(CallbackEvent::GuardrailDecision(event)) {
            warn!(
                error = %error,
                "Guardrail decision callback dispatch failed"
            );
        }
    }

    #[cfg(any(feature = "gateway", test))]
    pub(crate) fn begin_llm_metrics(&self, event: &LlmStartEvent) -> Option<CallbackMetricsPermit> {
        let recorder = self.callback_metrics.clone()?;
        recorder.begin_llm_lifecycle(event);
        Some(CallbackMetricsPermit {
            recorder,
            kind: CallbackMetricsKind::Llm(Box::new(event.clone())),
            completed: false,
        })
    }

    #[cfg(feature = "gateway")]
    pub(crate) fn begin_embedding_metrics(
        &self,
        event: &EmbeddingStartEvent,
    ) -> Option<CallbackMetricsPermit> {
        let recorder = self.callback_metrics.clone()?;
        recorder.record_embedding_start(event);
        Some(CallbackMetricsPermit {
            recorder,
            kind: CallbackMetricsKind::Embedding,
            completed: false,
        })
    }

    fn try_send(&self, event: CallbackEvent) -> Result<(), CallbackDispatchError> {
        let Some(sender) = &self.sender else {
            return Ok(());
        };
        sender.try_send(event).map_err(|error| match error {
            mpsc::error::TrySendError::Full(_) => CallbackDispatchError::QueueFull,
            mpsc::error::TrySendError::Closed(_) => CallbackDispatchError::QueueClosed,
        })
    }

    fn begin(
        &self,
        start_event: CallbackEvent,
    ) -> Result<CallbackTerminalPermit, CallbackDispatchError> {
        let Some(sender) = &self.sender else {
            return Ok(CallbackTerminalPermit { permit: None });
        };
        let start_permit = sender
            .clone()
            .try_reserve_owned()
            .map_err(map_reserve_error)?;
        let terminal_permit = sender
            .clone()
            .try_reserve_owned()
            .map_err(map_reserve_error)?;
        start_permit.send(start_event);
        Ok(CallbackTerminalPermit {
            permit: Some(terminal_permit),
        })
    }
}

fn map_reserve_error<T>(error: mpsc::error::TrySendError<T>) -> CallbackDispatchError {
    match error {
        mpsc::error::TrySendError::Full(_) => CallbackDispatchError::QueueFull,
        mpsc::error::TrySendError::Closed(_) => CallbackDispatchError::QueueClosed,
    }
}

/// Owns the callback queue worker and its graceful-shutdown signal.
pub struct CallbackRuntime {
    dispatcher: CallbackDispatcher,
    shutdown_tx: Option<oneshot::Sender<()>>,
    worker: Option<JoinHandle<IntegrationResult<()>>>,
}

impl CallbackRuntime {
    /// Start a callback worker around an existing integration manager.
    pub fn new(manager: Arc<IntegrationManager>, queue_capacity: usize) -> IntegrationResult<Self> {
        if queue_capacity < 2 {
            return Err(IntegrationError::config(
                "callback queue capacity must be at least 2",
            ));
        }

        let (sender, receiver) = mpsc::channel(queue_capacity);
        let (shutdown_tx, shutdown_rx) = oneshot::channel();
        let worker_manager = Arc::clone(&manager);
        let worker = tokio::spawn(async move {
            run_callback_worker(worker_manager, receiver, shutdown_rx).await
        });

        Ok(Self {
            dispatcher: CallbackDispatcher {
                sender: Some(sender),
                manager: Some(manager),
                callback_metrics: None,
            },
            shutdown_tx: Some(shutdown_tx),
            worker: Some(worker),
        })
    }

    /// Construct a disabled runtime.
    pub fn disabled() -> Self {
        Self {
            dispatcher: CallbackDispatcher::disabled(),
            shutdown_tx: None,
            worker: None,
        }
    }

    /// Obtain the request-path dispatcher.
    pub fn dispatcher(&self) -> CallbackDispatcher {
        self.dispatcher.clone()
    }

    #[cfg(any(feature = "gateway", test))]
    pub(crate) fn with_callback_metrics(
        mut self,
        metrics: Option<CallbackMetricsRecorder>,
    ) -> Self {
        self.dispatcher.callback_metrics = metrics;
        self
    }

    /// Drain pending events, flush integrations, and stop the worker.
    pub async fn shutdown(mut self) -> IntegrationResult<()> {
        if let Some(shutdown_tx) = self.shutdown_tx.take() {
            let _ = shutdown_tx.send(());
        }
        let Some(worker) = self.worker.take() else {
            return Ok(());
        };
        worker
            .await
            .map_err(|error| IntegrationError::other(format!("callback worker failed: {error}")))?
    }
}

impl Drop for CallbackRuntime {
    fn drop(&mut self) {
        if let Some(shutdown_tx) = self.shutdown_tx.take() {
            let _ = shutdown_tx.send(());
        }
    }
}

async fn run_callback_worker(
    manager: Arc<IntegrationManager>,
    mut receiver: mpsc::Receiver<CallbackEvent>,
    mut shutdown_rx: oneshot::Receiver<()>,
) -> IntegrationResult<()> {
    loop {
        tokio::select! {
            biased;
            _ = &mut shutdown_rx => {
                receiver.close();
                while let Some(event) = receiver.recv().await {
                    dispatch_event(manager.as_ref(), event).await;
                }
                break;
            }
            event = receiver.recv() => {
                let Some(event) = event else {
                    break;
                };
                dispatch_event(manager.as_ref(), event).await;
            }
        }
    }

    if let Err(error) = manager.flush().await {
        warn!("Callback integration flush failed: {}", error);
    }
    manager.shutdown().await
}

async fn dispatch_event(manager: &IntegrationManager, event: CallbackEvent) {
    let result = match event {
        CallbackEvent::Start(event) => manager.on_llm_start(&event).await,
        CallbackEvent::End(event) => manager.on_llm_end(&event).await,
        CallbackEvent::Error(event) => manager.on_llm_error(&event).await,
        CallbackEvent::Stream(event) => manager.on_llm_stream(&event).await,
        CallbackEvent::EmbeddingStart(event) => manager.on_embedding_start(&event).await,
        CallbackEvent::EmbeddingEnd(event) => manager.on_embedding_end(&event).await,
        CallbackEvent::EmbeddingError(event) => manager.on_embedding_error(&event).await,
        CallbackEvent::GuardrailDecision(event) => manager.on_guardrail_decision(&event).await,
    };
    if let Err(error) = result {
        error!("Callback event dispatch failed: {}", error);
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicBool, Ordering};

    use async_trait::async_trait;
    use parking_lot::Mutex;
    use tokio::sync::Notify;

    use super::*;
    use crate::core::integrations::{IntegrationManagerConfig, PrometheusIntegration};
    use crate::core::traits::integration::{Integration, LlmErrorEvent};

    struct RecordingIntegration {
        events: Arc<Mutex<Vec<&'static str>>>,
        flushed: Arc<AtomicBool>,
    }

    struct BlockingIntegration {
        entered: Arc<Notify>,
        release: Arc<Notify>,
        events: Arc<Mutex<Vec<&'static str>>>,
    }

    struct FailingIntegration;

    #[async_trait]
    impl Integration for FailingIntegration {
        fn name(&self) -> &'static str {
            "failing"
        }

        fn is_enabled(&self) -> bool {
            true
        }

        async fn on_llm_start(&self, _event: &LlmStartEvent) -> IntegrationResult<()> {
            Err(IntegrationError::other("test callback failure"))
        }

        async fn on_llm_end(&self, _event: &LlmEndEvent) -> IntegrationResult<()> {
            Err(IntegrationError::other("test callback failure"))
        }

        async fn on_llm_error(&self, _event: &LlmErrorEvent) -> IntegrationResult<()> {
            Err(IntegrationError::other("test callback failure"))
        }

        async fn flush(&self) -> IntegrationResult<()> {
            Ok(())
        }

        async fn shutdown(&self) -> IntegrationResult<()> {
            Ok(())
        }
    }

    #[async_trait]
    impl Integration for BlockingIntegration {
        fn name(&self) -> &'static str {
            "blocking"
        }

        fn is_enabled(&self) -> bool {
            true
        }

        async fn on_llm_start(&self, _event: &LlmStartEvent) -> IntegrationResult<()> {
            self.events.lock().push("start");
            self.entered.notify_one();
            self.release.notified().await;
            Ok(())
        }

        async fn on_llm_end(&self, _event: &LlmEndEvent) -> IntegrationResult<()> {
            self.events.lock().push("end");
            Ok(())
        }

        async fn on_llm_error(&self, _event: &LlmErrorEvent) -> IntegrationResult<()> {
            Ok(())
        }

        async fn flush(&self) -> IntegrationResult<()> {
            Ok(())
        }

        async fn shutdown(&self) -> IntegrationResult<()> {
            Ok(())
        }
    }

    #[async_trait]
    impl Integration for RecordingIntegration {
        fn name(&self) -> &'static str {
            "recording"
        }

        fn is_enabled(&self) -> bool {
            true
        }

        async fn on_llm_start(&self, _event: &LlmStartEvent) -> IntegrationResult<()> {
            self.events.lock().push("start");
            Ok(())
        }

        async fn on_llm_end(&self, _event: &LlmEndEvent) -> IntegrationResult<()> {
            self.events.lock().push("end");
            Ok(())
        }

        async fn on_llm_error(&self, _event: &LlmErrorEvent) -> IntegrationResult<()> {
            self.events.lock().push("error");
            Ok(())
        }

        async fn flush(&self) -> IntegrationResult<()> {
            self.flushed.store(true, Ordering::SeqCst);
            Ok(())
        }

        async fn shutdown(&self) -> IntegrationResult<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn runtime_preserves_order_and_flushes_on_shutdown() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let flushed = Arc::new(AtomicBool::new(false));
        let manager = Arc::new(IntegrationManager::with_defaults());
        manager
            .register(Arc::new(RecordingIntegration {
                events: Arc::clone(&events),
                flushed: Arc::clone(&flushed),
            }))
            .await;
        let runtime = match CallbackRuntime::new(manager, 8) {
            Ok(runtime) => runtime,
            Err(error) => panic!("callback runtime should start: {error}"),
        };
        let dispatcher = runtime.dispatcher();

        assert!(
            dispatcher
                .emit_start(LlmStartEvent::new("req-1", "model"))
                .is_ok()
        );
        assert!(
            dispatcher
                .emit_end(LlmEndEvent::new("req-1", "model"))
                .is_ok()
        );
        assert!(runtime.shutdown().await.is_ok());
        assert_eq!(*events.lock(), vec!["start", "end"]);
        assert!(flushed.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn runtime_rejects_capacity_below_lifecycle_pair() {
        let manager = Arc::new(IntegrationManager::with_defaults());
        for capacity in [0, 1] {
            let error = match CallbackRuntime::new(Arc::clone(&manager), capacity) {
                Ok(_) => panic!("callback runtime capacity {capacity} must fail"),
                Err(error) => error,
            };
            assert!(error.to_string().contains("at least 2"));
        }
    }

    #[tokio::test]
    async fn dispatcher_reports_full_and_closed_queue() {
        let entered = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());
        let manager = Arc::new(IntegrationManager::new(
            IntegrationManagerConfig::default().parallel(false),
        ));
        manager
            .register(Arc::new(BlockingIntegration {
                entered: Arc::clone(&entered),
                release: Arc::clone(&release),
                events: Arc::new(Mutex::new(Vec::new())),
            }))
            .await;
        let runtime = match CallbackRuntime::new(manager, 2) {
            Ok(runtime) => runtime,
            Err(error) => panic!("callback runtime should start: {error}"),
        };
        let dispatcher = runtime.dispatcher();
        let entered_wait = entered.notified();

        assert!(
            dispatcher
                .emit_start(LlmStartEvent::new("req-1", "model"))
                .is_ok()
        );
        entered_wait.await;
        assert!(
            dispatcher
                .emit_end(LlmEndEvent::new("req-1", "model"))
                .is_ok()
        );
        assert!(
            dispatcher
                .emit_end(LlmEndEvent::new("req-1", "model"))
                .is_ok()
        );
        assert_eq!(
            dispatcher.emit_error(LlmErrorEvent::new("req-1", "model", "failed")),
            Err(CallbackDispatchError::QueueFull)
        );

        release.notify_one();
        assert!(runtime.shutdown().await.is_ok());
        assert_eq!(
            dispatcher.emit_start(LlmStartEvent::new("req-2", "model")),
            Err(CallbackDispatchError::QueueClosed)
        );
    }

    #[tokio::test]
    async fn lifecycle_admission_reserves_terminal_capacity_as_a_pair() {
        let entered = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());
        let events = Arc::new(Mutex::new(Vec::new()));
        let manager = Arc::new(IntegrationManager::new(
            IntegrationManagerConfig::default().parallel(false),
        ));
        manager
            .register(Arc::new(BlockingIntegration {
                entered: Arc::clone(&entered),
                release: Arc::clone(&release),
                events: Arc::clone(&events),
            }))
            .await;
        let runtime = CallbackRuntime::new(manager, 2).unwrap();
        let dispatcher = runtime.dispatcher();
        let entered_wait = entered.notified();

        let terminal = dispatcher
            .begin_llm(LlmStartEvent::new("req-1", "model"))
            .unwrap();
        entered_wait.await;
        assert!(matches!(
            dispatcher.begin_llm(LlmStartEvent::new("req-2", "model")),
            Err(CallbackDispatchError::QueueFull)
        ));
        terminal.emit_end(LlmEndEvent::new("req-1", "model"));
        release.notify_one();
        runtime.shutdown().await.unwrap();

        assert_eq!(*events.lock(), vec!["start", "end"]);
    }

    #[tokio::test]
    async fn metrics_lifecycle_is_independent_without_hiding_queue_errors() {
        let entered = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());
        let manager = Arc::new(IntegrationManager::new(
            IntegrationManagerConfig::default().parallel(false),
        ));
        manager
            .register(Arc::new(BlockingIntegration {
                entered: Arc::clone(&entered),
                release: Arc::clone(&release),
                events: Arc::new(Mutex::new(Vec::new())),
            }))
            .await;
        let prometheus = Arc::new(PrometheusIntegration::with_defaults());
        let runtime = CallbackRuntime::new(manager, 2)
            .unwrap()
            .with_callback_metrics(Some(prometheus));
        let dispatcher = runtime.dispatcher();
        let entered_wait = entered.notified();

        let first = dispatcher
            .begin_llm(LlmStartEvent::new("req-1", "model"))
            .unwrap();
        entered_wait.await;

        let second_start = LlmStartEvent::new("req-2", "model");
        let second_metrics = dispatcher
            .begin_llm_metrics(&second_start)
            .expect("configured metrics should admit independently");
        assert!(matches!(
            dispatcher.begin_llm(second_start),
            Err(CallbackDispatchError::QueueFull)
        ));
        second_metrics.emit_end(&LlmEndEvent::new("req-2", "model").latency(25));
        assert_eq!(
            dispatcher.emit_end(LlmEndEvent::new("queued", "model")),
            Ok(())
        );
        for _ in 0..2 {
            assert_eq!(
                dispatcher.emit_end(LlmEndEvent::new("retry", "model")),
                Err(CallbackDispatchError::QueueFull)
            );
        }

        let cancelled = dispatcher
            .begin_llm_metrics(&LlmStartEvent::new("req-3", "model"))
            .expect("configured metrics should admit independently");
        drop(cancelled);

        let rendered = dispatcher.render_prometheus_metrics().unwrap();
        assert!(rendered.contains("litellm_requests_total{model=\"model\"} 2"));
        assert!(rendered.contains("litellm_requests_success_total{model=\"model\"} 1"));
        assert!(rendered.contains("litellm_active_requests 0"));

        first.emit_end(LlmEndEvent::new("req-1", "model"));
        release.notify_one();
        runtime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn failing_backend_does_not_block_healthy_backend() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let manager = Arc::new(IntegrationManager::new(
            IntegrationManagerConfig::default()
                .parallel(false)
                .fail_fast(false),
        ));
        manager.register(Arc::new(FailingIntegration)).await;
        manager
            .register(Arc::new(RecordingIntegration {
                events: Arc::clone(&events),
                flushed: Arc::new(AtomicBool::new(false)),
            }))
            .await;
        let runtime = match CallbackRuntime::new(manager, 8) {
            Ok(runtime) => runtime,
            Err(error) => panic!("callback runtime should start: {error}"),
        };
        let dispatcher = runtime.dispatcher();

        assert!(
            dispatcher
                .emit_start(LlmStartEvent::new("req-1", "model"))
                .is_ok()
        );
        assert!(
            dispatcher
                .emit_end(LlmEndEvent::new("req-1", "model"))
                .is_ok()
        );
        assert!(runtime.shutdown().await.is_ok());
        assert_eq!(*events.lock(), vec!["start", "end"]);
    }
}