Skip to main content

hyperinfer_client/
mirroring.rs

1//! Traffic mirroring: fire-and-forget shadow requests to a secondary model.
2//!
3//! When enabled, every successful primary call also spawns a background
4//! [`tokio::task`] that repeats the same request against a configured
5//! "mirror" model.  The mirror response is **not** returned to the caller;
6//! it is simply logged so operators can compare primary vs. mirror results
7//! (e.g. when evaluating a model switch).
8//!
9//! # Usage
10//!
11//! ```rust,ignore
12//! let mirror = MirrorConfig {
13//!     model: "claude-3-5-sonnet-20241022".to_string(),
14//!     sample_rate: 0.5,   // mirror 50 % of requests
15//! };
16//! client.set_mirror(Some(mirror));
17//! ```
18//!
19//! Thread-safety: the config is stored behind an `Arc<RwLock<…>>` so it can
20//! be hot-swapped at runtime without restarting the client.
21
22use crate::util::rand_f64;
23use crate::Router;
24use hyperinfer_core::{types::Provider, ChatRequest, Config};
25use hyperinfer_providers::ProviderRegistry;
26use std::sync::{Arc, OnceLock};
27use tokio::sync::{RwLock, Semaphore};
28use tracing::warn;
29
30/// Maximum number of concurrent background mirror tasks.
31const MIRROR_CONCURRENCY_LIMIT: usize = 100;
32
33/// Module-level semaphore — shared across all `maybe_mirror` calls so we never
34/// have more than `MIRROR_CONCURRENCY_LIMIT` in-flight mirror tasks at once.
35fn mirror_semaphore() -> &'static Arc<Semaphore> {
36    static SEM: OnceLock<Arc<Semaphore>> = OnceLock::new();
37    SEM.get_or_init(|| Arc::new(Semaphore::new(MIRROR_CONCURRENCY_LIMIT)))
38}
39
40/// Configuration for the traffic mirror.
41#[derive(Debug, Clone)]
42pub struct MirrorConfig {
43    /// Target model for the shadow request (e.g. `"claude-3-5-sonnet-20241022"`).
44    pub model: String,
45    /// Fraction of requests to mirror in `[0.0, 1.0]`.
46    /// `1.0` means mirror every request; `0.0` disables mirroring.
47    pub sample_rate: f64,
48}
49
50impl MirrorConfig {
51    pub fn new(model: String, sample_rate: f64) -> Self {
52        Self {
53            model,
54            sample_rate: sample_rate.clamp(0.0, 1.0),
55        }
56    }
57}
58
59/// Shared, hot-swappable mirror configuration.
60pub type MirrorHandle = Arc<RwLock<Option<MirrorConfig>>>;
61
62/// Spawn a fire-and-forget background task that sends `request` to the mirror
63/// model.  Errors are logged but never propagated.
64///
65/// The function returns immediately; the mirror call runs concurrently.
66pub fn maybe_mirror(
67    mirror_handle: MirrorHandle,
68    provider_registry: Arc<ProviderRegistry>,
69    router: Arc<Router>,
70    config_snapshot: Arc<Config>,
71    _key: String,
72    mut request: ChatRequest,
73) {
74    // Read mirror config and bail out early if disabled.
75    let mirror_cfg = match mirror_handle.try_read() {
76        Ok(guard) => match guard.as_ref() {
77            Some(cfg) if cfg.sample_rate > 0.0 => cfg.clone(),
78            _ => return,
79        },
80        Err(_) => return,
81    };
82
83    // Probabilistic sampling — skip if not selected.
84    if mirror_cfg.sample_rate < 1.0 {
85        let roll: f64 = rand_f64();
86        if roll > mirror_cfg.sample_rate {
87            tracing::debug!(
88                "Mirror skipped (sample_rate={:.2}, roll={:.2})",
89                mirror_cfg.sample_rate,
90                roll
91            );
92            return;
93        }
94    }
95
96    // Rewrite the model to the mirror target.
97    request.model = mirror_cfg.model.clone();
98
99    // Resolve provider for the mirror model — bail out early if not resolvable.
100    let resolved = router.resolve(&request.model, &config_snapshot);
101    let (model, provider) = match resolved {
102        Some(r) => r,
103        None => {
104            warn!(
105                "Mirror: could not resolve model '{}', skipping",
106                request.model
107            );
108            return;
109        }
110    };
111
112    // Check we have an API key and supported provider — bail out early if not.
113    let api_key = match config_snapshot.api_keys.get(&provider.to_string()) {
114        Some(k) => k.clone(),
115        None => {
116            warn!("Mirror: no API key for provider {:?}", provider);
117            return;
118        }
119    };
120
121    match provider {
122        Provider::OpenAI | Provider::Anthropic => {}
123        _ => {
124            warn!("Mirror: unsupported provider {:?}", provider);
125            return;
126        }
127    }
128
129    // Acquire permit only after all pre-checks pass; if at capacity, skip this request.
130    let permit = match mirror_semaphore().clone().try_acquire_owned() {
131        Ok(p) => p,
132        Err(_) => {
133            tracing::debug!("Mirror skipped: concurrency limit reached");
134            return;
135        }
136    };
137
138    let provider_name = provider.to_string();
139    tokio::spawn(async move {
140        let _permit = permit;
141
142        let llm_provider = match provider_registry.get(&provider_name) {
143            Some(p) => p,
144            None => {
145                warn!("Mirror: provider '{}' not found in registry", provider_name);
146                return;
147            }
148        };
149
150        let result = llm_provider.chat(&request, &api_key).await;
151
152        match result {
153            Ok(resp) => {
154                let content_len = resp
155                    .choices
156                    .first()
157                    .map(|c| c.message.content.len())
158                    .unwrap_or(0);
159                tracing::debug!(
160                    mirror_model = %model,
161                    input_tokens = resp.usage.input_tokens,
162                    output_tokens = resp.usage.output_tokens,
163                    content_len,
164                    "Mirror response received",
165                );
166            }
167            Err(e) => {
168                warn!("Mirror request failed: {:?}", e);
169            }
170        }
171    });
172}
173
174// ── Tests ─────────────────────────────────────────────────────────────────────
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use hyperinfer_core::types::Config;
180    use std::collections::HashMap;
181
182    fn empty_config() -> Config {
183        Config {
184            api_keys: HashMap::new(),
185            routing_rules: vec![],
186            quotas: HashMap::new(),
187            model_aliases: HashMap::new(),
188            default_provider: None,
189        }
190    }
191
192    #[test]
193    fn test_mirror_config_clone() {
194        let cfg = MirrorConfig {
195            model: "gpt-4o".to_string(),
196            sample_rate: 0.5,
197        };
198        let cloned = cfg.clone();
199        assert_eq!(cloned.model, "gpt-4o");
200        assert!((cloned.sample_rate - 0.5).abs() < 1e-9);
201    }
202
203    #[tokio::test]
204    async fn test_maybe_mirror_disabled_no_panic() {
205        // With sample_rate = 0.0 the spawn fires but exits immediately.
206        let handle: MirrorHandle = Arc::new(RwLock::new(Some(MirrorConfig {
207            model: "gpt-4o".to_string(),
208            sample_rate: 0.0,
209        })));
210        let registry = Arc::new(ProviderRegistry::new());
211        let router = Arc::new(Router::new(vec![]));
212        let config = Arc::new(empty_config());
213
214        let request = hyperinfer_core::ChatRequest {
215            model: "gpt-4".to_string(),
216            messages: vec![hyperinfer_core::types::ChatMessage::user("hello")],
217            max_tokens: Some(10),
218            temperature: None,
219            stream: None,
220            stop: None,
221            tools: None,
222            tool_choice: None,
223            response_format: None,
224        };
225
226        maybe_mirror(handle, registry, router, config, "key".to_string(), request);
227        // Allow the task to run and exit.
228        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
229    }
230
231    #[tokio::test]
232    async fn test_maybe_mirror_none_config_no_panic() {
233        // With None config nothing should happen.
234        let handle: MirrorHandle = Arc::new(RwLock::new(None));
235        let registry = Arc::new(ProviderRegistry::new());
236        let router = Arc::new(Router::new(vec![]));
237        let config = Arc::new(empty_config());
238
239        let request = hyperinfer_core::ChatRequest {
240            model: "gpt-4".to_string(),
241            messages: vec![hyperinfer_core::types::ChatMessage::user("hello")],
242            max_tokens: Some(10),
243            temperature: None,
244            stream: None,
245            stop: None,
246            tools: None,
247            tool_choice: None,
248            response_format: None,
249        };
250
251        maybe_mirror(handle, registry, router, config, "key".to_string(), request);
252        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
253    }
254
255    #[tokio::test]
256    async fn test_maybe_mirror_unresolvable_model_no_panic() {
257        // Mirror model that cannot be resolved → logs warning, no panic.
258        let handle: MirrorHandle = Arc::new(RwLock::new(Some(MirrorConfig {
259            model: "unknown-llm-xyz".to_string(),
260            sample_rate: 1.0,
261        })));
262        let registry = Arc::new(ProviderRegistry::new());
263        let router = Arc::new(Router::new(vec![]));
264        let config = Arc::new(empty_config());
265
266        let request = hyperinfer_core::ChatRequest {
267            model: "gpt-4".to_string(),
268            messages: vec![hyperinfer_core::types::ChatMessage::user("hello")],
269            max_tokens: Some(10),
270            temperature: None,
271            stream: None,
272            stop: None,
273            tools: None,
274            tool_choice: None,
275            response_format: None,
276        };
277
278        maybe_mirror(handle, registry, router, config, "key".to_string(), request);
279        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
280    }
281
282    static SERIALIZE_MIRROR_TEST: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
283
284    fn get_serialize_mutex() -> &'static tokio::sync::Mutex<()> {
285        SERIALIZE_MIRROR_TEST.get_or_init(|| tokio::sync::Mutex::new(()))
286    }
287
288    #[tokio::test]
289    async fn test_maybe_mirror_concurrency_limit_no_panic() {
290        let _guard = get_serialize_mutex().lock().await;
291
292        let sem = mirror_semaphore();
293        let mut permits: Vec<tokio::sync::SemaphorePermit<'_>> =
294            Vec::with_capacity(MIRROR_CONCURRENCY_LIMIT);
295        for _ in 0..MIRROR_CONCURRENCY_LIMIT {
296            let permit = sem.acquire().await.expect("should acquire permit");
297            permits.push(permit);
298        }
299
300        assert_eq!(sem.available_permits(), 0);
301
302        let handle: MirrorHandle = Arc::new(RwLock::new(Some(MirrorConfig {
303            model: "gpt-4o".to_string(),
304            sample_rate: 1.0,
305        })));
306        let registry = Arc::new(ProviderRegistry::new());
307        let router = Arc::new(Router::new(vec![]));
308        let config = Arc::new(empty_config());
309
310        let request = hyperinfer_core::ChatRequest {
311            model: "gpt-4".to_string(),
312            messages: vec![hyperinfer_core::types::ChatMessage::user("hello")],
313            max_tokens: Some(10),
314            temperature: None,
315            stream: None,
316            stop: None,
317            tools: None,
318            tool_choice: None,
319            response_format: None,
320        };
321
322        maybe_mirror(handle, registry, router, config, "key".to_string(), request);
323
324        drop(permits);
325
326        assert_eq!(
327            sem.available_permits(),
328            MIRROR_CONCURRENCY_LIMIT,
329            "maybe_mirror should not have acquired a permit when at capacity"
330        );
331    }
332}