Skip to main content

lean_ctx/proxy/
routing.rs

1//! Active request router (enterprise#13) — alias + intent-tier model rewrite
2//! in the forward path, **fail-open by construction**.
3//!
4//! Runs between body parse and body compression: it may replace the `model`
5//! field and re-target the request to another upstream of the **same wire
6//! shape** — or, with the `shape-xlat` feature (enterprise#16), route an
7//! Anthropic `/v1/messages` request onto an OpenAI-shape upstream with the
8//! translation flag set. The decision is recorded as `routed_from` on the
9//! usage record, so savings attribution can prove what the router did
10//! (enterprise#15/#19).
11//!
12//! Two rule sources (`[proxy.routing]`, [`RoutingRules`]):
13//!
14//! 1. **Aliases** — exact requested-model match. `"acme/fast" = "foundry:gpt-4o-mini"`
15//!    gives clients a stable org-level name; `"claude-opus-4-5" = "claude-sonnet-4-5"`
16//!    transparently downgrades a concrete model.
17//! 2. **Tiers** — intent classification of the request's last user message
18//!    (`intent_engine::classify` → `route_intent` → `fast|standard|premium`)
19//!    picks the target from the `tiers` table. Unset/empty tier = keep the
20//!    requested model.
21//!
22//! Every failure mode — no rules, no model field, unknown target provider,
23//! shape mismatch, unextractable query — routes nothing: the request forwards
24//! unchanged. A routing bug can cost savings, never availability.
25
26use super::routing_feedback::global_feedback;
27use crate::core::config::{
28    ResolvedProvider, RoutingRules, Upstreams, WireShape, parse_route_target,
29};
30use crate::core::ocla::registry::OclaRegistry;
31use crate::core::ocla::types::{ModelRouteRequest, OclaRequestContext};
32
33#[cfg(test)]
34use crate::core::ocla::builtin::model_router::BuiltinModelRouter;
35#[cfg(test)]
36use crate::core::ocla::registry::with_test_registry;
37#[cfg(test)]
38use std::sync::Arc;
39
40/// What the router decided for one request. Applied by the forward path:
41/// `model` already swapped in the body by [`route_request`]; the caller
42/// re-targets the upstream and injects the registry credential if set.
43#[derive(Debug, Clone, PartialEq)]
44pub struct RouteDecision {
45    /// Feedback correlation id unique to this routed request.
46    pub decision_id: String,
47    /// Model now in the body.
48    pub model: String,
49    /// Originally requested model (usage record `routed_from`).
50    pub routed_from: String,
51    /// Registry/builtin provider id serving the request after routing
52    /// (usage attribution); `None` = upstream unchanged.
53    pub provider_id: Option<String>,
54    /// Override for the upstream base URL; `None` = keep the handler's.
55    pub upstream_base: Option<String>,
56    /// Registry entry whose `api_key_env` credential must be injected before
57    /// the request leaves (gateway-held keys, enterprise#7).
58    pub credential: Option<ResolvedProvider>,
59    /// Target's local-inference flag (shadow-rate billing): `Some` for
60    /// registry targets, `None` for built-ins (URL heuristic applies).
61    pub local: Option<bool>,
62    /// Cross-shape route (enterprise#16, feature `shape-xlat`): the Anthropic
63    /// request body must be translated to OpenAI Chat Completions before it
64    /// leaves, and the response translated back. Always `false` within-shape.
65    pub xlat: bool,
66}
67
68/// Maximum user-message prefix fed to the intent classifier. Classification is
69/// keyword/structure based; a bounded prefix keeps it O(1) per request.
70const CLASSIFY_QUERY_CAP: usize = 2000;
71
72/// Applies the routing rules to a parsed request body. On a routing decision
73/// the body's `model` field is rewritten in place and the full decision is
74/// returned; on any miss/failure the body is untouched and `None` is returned
75/// (fail-open passthrough).
76///
77/// `xlat_ok` — the caller vouches that this request may be shape-translated
78/// (exact messages-create path, `shape-xlat` compiled in). Subpaths like
79/// `count_tokens`/`batches` have no OpenAI equivalent and must stay
80/// within-shape.
81pub fn route_request(
82    parsed: &mut serde_json::Value,
83    provider_label: &str,
84    upstreams: &Upstreams,
85    rules: &RoutingRules,
86    xlat_ok: bool,
87) -> Option<RouteDecision> {
88    if global_feedback().should_use_fallback() {
89        tracing::warn!("routing quality below threshold, using fallback");
90        return None;
91    }
92    if !rules.is_active() {
93        return None;
94    }
95    // Body-addressed model dialects route. Gemini keys the model in the URL
96    // path and ChatGPT-backend is OAuth'd Codex traffic — both passthrough.
97    let request_shape = match provider_label {
98        "Anthropic" => WireShape::Anthropic,
99        "OpenAI" => WireShape::OpenAi,
100        _ => return None,
101    };
102    let requested = parsed.get("model")?.as_str()?.trim().to_string();
103    if requested.is_empty() {
104        return None;
105    }
106
107    #[cfg(test)]
108    let _registry_guard = {
109        let mut registry = OclaRegistry::with_builtins();
110        registry.model_router = Arc::new(BuiltinModelRouter::with_rules(rules.clone()));
111        Some(with_test_registry(registry))
112    };
113
114    let target = rules.aliases.get(&requested).cloned().or_else(|| {
115        let content_ref = extract_user_query(parsed, request_shape)?;
116        let request_id = format!(
117            "proxy-routing:{}",
118            blake3::hash(&serde_json::to_vec(parsed).ok()?).to_hex()
119        );
120        let request = ModelRouteRequest {
121            context: OclaRequestContext {
122                request_id,
123                session_id: "proxy-routing".into(),
124                agent_id: "proxy-routing".into(),
125                content_ref,
126                tenant_id: None,
127                trace_id: "tr-unit".into(),
128                task_id: None,
129                parent_task_id: None,
130            },
131            candidate_models: vec![requested.clone()],
132            maximum_cost_micros: None,
133            maximum_latency_ms: None,
134        };
135        let decision = tokio::task::block_in_place(|| {
136            tokio::runtime::Handle::current()
137                .block_on(OclaRegistry::global().model_router.route_model(request))
138        })
139        .ok()?;
140        if decision.model == requested {
141            None
142        } else if decision.provider.is_empty() {
143            Some(decision.model)
144        } else {
145            Some(format!("{}:{}", decision.provider, decision.model))
146        }
147    })?;
148    let (provider, new_model) = parse_route_target(&target)?;
149    let new_model = new_model.to_string();
150
151    let resolved = match provider {
152        None => ResolvedTarget::default(),
153        Some(p) => resolve_provider(p, request_shape, upstreams, xlat_ok)?,
154    };
155
156    if new_model == requested && resolved.upstream_base.is_none() {
157        return None; // no-op rule
158    }
159
160    parsed["model"] = serde_json::Value::String(new_model.clone());
161    let route_reason = if rules.aliases.contains_key(&requested) {
162        "alias"
163    } else {
164        "intent_tier"
165    };
166    let decision_id = global_feedback().record_decision(&requested, &new_model, route_reason);
167    let decision = RouteDecision {
168        decision_id,
169        model: new_model,
170        routed_from: requested,
171        provider_id: resolved.provider_id,
172        upstream_base: resolved.upstream_base,
173        credential: resolved.credential,
174        local: resolved.local,
175        xlat: resolved.xlat,
176    };
177    Some(decision)
178}
179
180/// A resolved route target. `Default` = model-only rewrite (upstream unchanged).
181#[derive(Default)]
182struct ResolvedTarget {
183    provider_id: Option<String>,
184    upstream_base: Option<String>,
185    credential: Option<ResolvedProvider>,
186    local: Option<bool>,
187    xlat: bool,
188}
189
190/// Resolves a route-target provider name, enforcing the shape rules: same
191/// shape always routes; Anthropic→OpenAI routes with the translation flag when
192/// the `shape-xlat` feature is compiled in and the caller allowed it. Unknown
193/// ids and untranslatable shape pairs are logged and route nothing.
194fn resolve_provider(
195    name: &str,
196    request_shape: WireShape,
197    upstreams: &Upstreams,
198    xlat_ok: bool,
199) -> Option<ResolvedTarget> {
200    let (target_shape, base_url, credential, local) = match name {
201        "anthropic" => (
202            WireShape::Anthropic,
203            upstreams.anthropic.clone(),
204            None,
205            None,
206        ),
207        "openai" => (WireShape::OpenAi, upstreams.openai.clone(), None, None),
208        "gemini" => (WireShape::Gemini, upstreams.gemini.clone(), None, None),
209        id => {
210            let Some(p) = upstreams.provider_by_id(id) else {
211                tracing::warn!(
212                    "[proxy.routing] target provider '{id}' not in [[proxy.providers]] — passthrough"
213                );
214                return None;
215            };
216            (
217                p.shape,
218                p.base_url.clone(),
219                p.api_key_env.is_some().then(|| p.clone()),
220                Some(p.local),
221            )
222        }
223    };
224    let xlat = if target_shape == request_shape {
225        false
226    } else if can_translate(
227        request_shape,
228        target_shape,
229        xlat_ok,
230        credential.as_ref(),
231        local,
232    ) {
233        true
234    } else {
235        tracing::warn!(
236            "[proxy.routing] target '{name}' speaks {} but the request is {} — \
237             not translatable here, passthrough",
238            target_shape.as_str(),
239            request_shape.as_str()
240        );
241        return None;
242    };
243    Some(ResolvedTarget {
244        provider_id: Some(name.to_string()),
245        upstream_base: Some(base_url),
246        credential,
247        local,
248        xlat,
249    })
250}
251
252/// Anthropic→OpenAI is the supported translation pair (enterprise#16). The
253/// upstream must be gateway-authenticated (`api_key_env`) or a local endpoint
254/// (no auth) — the caller's Anthropic credentials mean nothing to an
255/// OpenAI-shape provider.
256#[cfg(feature = "shape-xlat")]
257fn can_translate(
258    request_shape: WireShape,
259    target_shape: WireShape,
260    xlat_ok: bool,
261    credential: Option<&ResolvedProvider>,
262    local: Option<bool>,
263) -> bool {
264    xlat_ok
265        && request_shape == WireShape::Anthropic
266        && target_shape == WireShape::OpenAi
267        && (credential.is_some() || local == Some(true))
268}
269
270#[cfg(not(feature = "shape-xlat"))]
271fn can_translate(
272    _request_shape: WireShape,
273    _target_shape: WireShape,
274    _xlat_ok: bool,
275    _credential: Option<&ResolvedProvider>,
276    _local: Option<bool>,
277) -> bool {
278    false
279}
280
281/// Extracts the newest user-authored text from a request body — the router's
282/// classification input. Handles the two body-addressed dialects:
283///
284/// - Anthropic Messages / OpenAI Chat: `messages[]`, last `role == "user"`,
285///   content as string or text-part array.
286/// - OpenAI Responses: `input` as string, or `input[]` items with
287///   `role == "user"` and `content[]` parts (`input_text`/`text`).
288fn extract_user_query(parsed: &serde_json::Value, shape: WireShape) -> Option<String> {
289    debug_assert!(matches!(shape, WireShape::Anthropic | WireShape::OpenAi));
290    let items = parsed.get("messages").or_else(|| parsed.get("input"))?;
291
292    // OpenAI Responses shorthand: `"input": "plain text"`.
293    if let Some(text) = items.as_str() {
294        return non_empty_prefix(text);
295    }
296    let items = items.as_array()?;
297    let last_user = items.iter().rev().find(|m| {
298        m.get("role").and_then(|r| r.as_str()) == Some("user")
299            || (m.get("type").and_then(|t| t.as_str()) == Some("message")
300                && m.get("role").and_then(|r| r.as_str()) == Some("user"))
301    })?;
302    let content = last_user.get("content")?;
303    if let Some(text) = content.as_str() {
304        return non_empty_prefix(text);
305    }
306    let parts = content.as_array()?;
307    let mut buf = String::new();
308    for part in parts {
309        let is_text = matches!(
310            part.get("type").and_then(|t| t.as_str()),
311            Some("text" | "input_text")
312        );
313        if is_text && let Some(t) = part.get("text").and_then(|t| t.as_str()) {
314            if !buf.is_empty() {
315                buf.push(' ');
316            }
317            buf.push_str(t);
318            if buf.len() >= CLASSIFY_QUERY_CAP {
319                break;
320            }
321        }
322    }
323    non_empty_prefix(&buf)
324}
325fn non_empty_prefix(text: &str) -> Option<String> {
326    let trimmed = text.trim();
327    if trimmed.is_empty() {
328        return None;
329    }
330    let mut end = trimmed.len().min(CLASSIFY_QUERY_CAP);
331    while !trimmed.is_char_boundary(end) {
332        end -= 1;
333    }
334    Some(trimmed[..end].to_string())
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340    use serde_json::json;
341
342    fn upstreams_with_foundry() -> Upstreams {
343        Upstreams {
344            anthropic: "https://api.anthropic.com".into(),
345            openai: "https://api.openai.com".into(),
346            chatgpt: "https://chatgpt.com".into(),
347            gemini: "https://generativelanguage.googleapis.com".into(),
348            providers: vec![
349                ResolvedProvider {
350                    id: "foundry".into(),
351                    shape: WireShape::OpenAi,
352                    base_url: "https://acme.services.ai.azure.com/openai".into(),
353                    api_key_env: Some("FOUNDRY_API_KEY".into()),
354                    aws_region: None,
355                    local: false,
356                },
357                ResolvedProvider {
358                    id: "claudeish".into(),
359                    shape: WireShape::Anthropic,
360                    base_url: "https://anthropic-gw.example.com".into(),
361                    api_key_env: None,
362                    aws_region: None,
363                    local: false,
364                },
365            ],
366        }
367    }
368
369    fn rules(aliases: &[(&str, &str)], tiers: &[(&str, &str)]) -> RoutingRules {
370        RoutingRules {
371            enabled: Some(true),
372            aliases: aliases
373                .iter()
374                .map(|(k, v)| (k.to_string(), v.to_string()))
375                .collect(),
376            tiers: tiers
377                .iter()
378                .map(|(k, v)| (k.to_string(), v.to_string()))
379                .collect(),
380        }
381    }
382
383    #[test]
384    fn route_decision_does_not_record_feedback_before_outcome() {
385        let feedback = global_feedback();
386        let before = feedback.stats();
387        let mut body = json!({"model":"expensive","messages":[{"role":"user","content":"hi"}]});
388
389        let decision = route_request(
390            &mut body,
391            "OpenAI",
392            &upstreams_with_foundry(),
393            &rules(&[("expensive", "fast")], &[]),
394            false,
395        )
396        .expect("alias should route");
397
398        assert_eq!(decision.routed_from, "expensive");
399        assert_eq!(decision.model, "fast");
400        assert_eq!(feedback.stats(), before);
401    }
402
403    #[test]
404    fn alias_routes_to_registry_provider_and_rewrites_model() {
405        let mut body = json!({"model": "acme/fast", "messages": [{"role":"user","content":"hi"}]});
406        let d = route_request(
407            &mut body,
408            "OpenAI",
409            &upstreams_with_foundry(),
410            &rules(&[("acme/fast", "foundry:gpt-4o-mini")], &[]),
411            false,
412        )
413        .expect("routed");
414        assert_eq!(body["model"], "gpt-4o-mini");
415        assert_eq!(d.routed_from, "acme/fast");
416        assert_eq!(d.provider_id.as_deref(), Some("foundry"));
417        assert_eq!(
418            d.upstream_base.as_deref(),
419            Some("https://acme.services.ai.azure.com/openai")
420        );
421        assert!(
422            d.credential.is_some(),
423            "foundry has api_key_env — credential must be injected"
424        );
425    }
426
427    #[test]
428    fn alias_model_only_keeps_upstream() {
429        let mut body =
430            json!({"model": "claude-opus-4-5", "messages": [{"role":"user","content":"hi"}]});
431        let d = route_request(
432            &mut body,
433            "Anthropic",
434            &upstreams_with_foundry(),
435            &rules(&[("claude-opus-4-5", "claude-sonnet-4-5")], &[]),
436            false,
437        )
438        .expect("routed");
439        assert_eq!(body["model"], "claude-sonnet-4-5");
440        assert_eq!(d.upstream_base, None);
441        assert_eq!(d.provider_id, None);
442        assert_eq!(d.credential, None);
443    }
444
445    #[test]
446    fn cross_shape_target_is_passthrough_when_xlat_not_allowed() {
447        // Anthropic request → OpenAI-shape foundry with xlat_ok=false (wrong
448        // path, e.g. count_tokens): must stay passthrough.
449        let mut body =
450            json!({"model": "claude-opus-4-5", "messages": [{"role":"user","content":"hi"}]});
451        let before = body.clone();
452        let d = route_request(
453            &mut body,
454            "Anthropic",
455            &upstreams_with_foundry(),
456            &rules(&[("claude-opus-4-5", "foundry:gpt-4o-mini")], &[]),
457            false,
458        );
459        assert_eq!(d, None);
460        assert_eq!(body, before, "fail-open must leave the body untouched");
461    }
462
463    #[cfg(feature = "shape-xlat")]
464    #[test]
465    fn cross_shape_target_routes_with_translation_flag() {
466        // enterprise#16: with the feature compiled in and the caller vouching
467        // for the path, Anthropic → OpenAI-shape routes and marks xlat.
468        let mut body =
469            json!({"model": "claude-opus-4-5", "messages": [{"role":"user","content":"hi"}]});
470        let d = route_request(
471            &mut body,
472            "Anthropic",
473            &upstreams_with_foundry(),
474            &rules(&[("claude-opus-4-5", "foundry:gpt-4o-mini")], &[]),
475            true,
476        )
477        .expect("cross-shape route with translation");
478        assert!(d.xlat, "decision must carry the translation flag");
479        assert_eq!(body["model"], "gpt-4o-mini");
480        assert_eq!(d.provider_id.as_deref(), Some("foundry"));
481        assert!(d.credential.is_some());
482
483        // Within-shape decisions never set xlat.
484        let mut body2 = json!({"model": "acme/fast", "messages": [{"role":"user","content":"hi"}]});
485        let d2 = route_request(
486            &mut body2,
487            "OpenAI",
488            &upstreams_with_foundry(),
489            &rules(&[("acme/fast", "foundry:gpt-4o-mini")], &[]),
490            true,
491        )
492        .expect("within-shape route");
493        assert!(!d2.xlat);
494    }
495
496    #[cfg(feature = "shape-xlat")]
497    #[test]
498    fn cross_shape_needs_gateway_credential_or_local_target() {
499        // An OpenAI-shape target without api_key_env and not local cannot be
500        // reached with the caller's Anthropic credentials → passthrough.
501        let mut upstreams = upstreams_with_foundry();
502        upstreams.providers.push(ResolvedProvider {
503            id: "openaiish".into(),
504            shape: WireShape::OpenAi,
505            base_url: "https://oai-compat.example.com".into(),
506            api_key_env: None,
507            aws_region: None,
508            local: false,
509        });
510        let mut body =
511            json!({"model": "claude-opus-4-5", "messages": [{"role":"user","content":"hi"}]});
512        let before = body.clone();
513        let d = route_request(
514            &mut body,
515            "Anthropic",
516            &upstreams,
517            &rules(&[("claude-opus-4-5", "openaiish:gpt-4o-mini")], &[]),
518            true,
519        );
520        assert_eq!(d, None);
521        assert_eq!(body, before);
522
523        // The same target declared local (e.g. Ollama) needs no credential.
524        upstreams.providers.last_mut().unwrap().local = true;
525        let d = route_request(
526            &mut body,
527            "Anthropic",
528            &upstreams,
529            &rules(&[("claude-opus-4-5", "openaiish:llama3.3")], &[]),
530            true,
531        )
532        .expect("local cross-shape target routes");
533        assert!(d.xlat);
534        assert_eq!(d.local, Some(true));
535    }
536
537    #[cfg(feature = "shape-xlat")]
538    #[test]
539    fn openai_to_anthropic_direction_stays_passthrough() {
540        // Only Anthropic→OpenAI is translated; the reverse pair passes through.
541        let mut body = json!({"model": "gpt-5.2", "messages": [{"role":"user","content":"hi"}]});
542        let d = route_request(
543            &mut body,
544            "OpenAI",
545            &upstreams_with_foundry(),
546            &rules(&[("gpt-5.2", "claudeish:claude-sonnet-4-5")], &[]),
547            true,
548        );
549        assert_eq!(d, None);
550    }
551
552    #[test]
553    fn unknown_provider_and_disabled_rules_are_passthrough() {
554        let mut body = json!({"model": "m", "messages": [{"role":"user","content":"hi"}]});
555        let before = body.clone();
556        assert_eq!(
557            route_request(
558                &mut body,
559                "OpenAI",
560                &upstreams_with_foundry(),
561                &rules(&[("m", "nope:x")], &[]),
562                false,
563            ),
564            None
565        );
566        // enabled=false → inactive even with rules present.
567        let mut off = rules(&[("m", "foundry:x")], &[]);
568        off.enabled = Some(false);
569        assert_eq!(
570            route_request(&mut body, "OpenAI", &upstreams_with_foundry(), &off, false),
571            None
572        );
573        assert_eq!(body, before);
574    }
575
576    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
577    async fn tier_downgrade_routes_simple_queries_to_cheap_model() {
578        // An explore-style question lands on a non-premium tier (fast, or
579        // standard when the classifier hedges on low confidence). Both map to
580        // the cheap target here — this test pins the routing mechanics; tier
581        // assignment itself is covered by the intent_engine tests.
582        let mut body = json!({
583            "model": "gpt-5.2",
584            "messages": [
585                {"role":"system","content":"be helpful"},
586                {"role":"user","content":"where is the config file for the proxy?"}
587            ]
588        });
589        let d = route_request(
590            &mut body,
591            "OpenAI",
592            &upstreams_with_foundry(),
593            &rules(
594                &[],
595                &[("fast", "foundry:phi-4"), ("standard", "foundry:phi-4")],
596            ),
597            false,
598        )
599        .expect("non-premium query must route");
600        assert_eq!(body["model"], "phi-4");
601        assert_eq!(d.routed_from, "gpt-5.2");
602        assert_eq!(d.provider_id.as_deref(), Some("foundry"));
603    }
604
605    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
606    async fn premium_tier_unset_keeps_requested_model() {
607        // Generation work classifies premium; with no premium target the
608        // request passes through untouched.
609        let mut body = json!({
610            "model": "gpt-5.2",
611            "messages": [{"role":"user","content":
612                "implement a new distributed lock manager with leader election and fencing tokens"}]
613        });
614        let before = body.clone();
615        let d = route_request(
616            &mut body,
617            "OpenAI",
618            &upstreams_with_foundry(),
619            &rules(&[], &[("fast", "foundry:phi-4"), ("premium", "")]),
620            false,
621        );
622        assert_eq!(d, None);
623        assert_eq!(body, before);
624    }
625
626    #[test]
627    fn responses_input_string_and_items_are_extractable() {
628        let s = json!({"model":"m","input":"quick question about rust"});
629        assert!(extract_user_query(&s, WireShape::OpenAi).is_some());
630
631        let items = json!({"model":"m","input":[
632            {"type":"message","role":"user","content":[{"type":"input_text","text":"what does this do"}]}
633        ]});
634        assert_eq!(
635            extract_user_query(&items, WireShape::OpenAi).as_deref(),
636            Some("what does this do")
637        );
638
639        let anthropic = json!({"model":"m","messages":[
640            {"role":"user","content":[{"type":"text","text":"first"}]},
641            {"role":"assistant","content":"a"},
642            {"role":"user","content":[{"type":"text","text":"latest question"}]}
643        ]});
644        assert_eq!(
645            extract_user_query(&anthropic, WireShape::Anthropic).as_deref(),
646            Some("latest question")
647        );
648    }
649
650    #[test]
651    fn missing_model_or_query_is_passthrough() {
652        let mut no_model = json!({"messages":[{"role":"user","content":"hi"}]});
653        assert_eq!(
654            route_request(
655                &mut no_model,
656                "OpenAI",
657                &upstreams_with_foundry(),
658                &rules(&[], &[("fast", "foundry:phi-4")]),
659                false,
660            ),
661            None
662        );
663        let mut no_user = json!({"model":"m","messages":[{"role":"system","content":"x"}]});
664        assert_eq!(
665            route_request(
666                &mut no_user,
667                "OpenAI",
668                &upstreams_with_foundry(),
669                &rules(&[], &[("fast", "foundry:phi-4")]),
670                false,
671            ),
672            None
673        );
674    }
675
676    #[test]
677    fn gemini_and_chatgpt_labels_are_passthrough() {
678        let mut body = json!({"model":"m","messages":[{"role":"user","content":"hi"}]});
679        for label in ["Gemini", "ChatGPT"] {
680            assert_eq!(
681                route_request(
682                    &mut body,
683                    label,
684                    &upstreams_with_foundry(),
685                    &rules(&[("m", "x")], &[]),
686                    false,
687                ),
688                None,
689                "{label} must not route in M1"
690            );
691        }
692    }
693
694    #[test]
695    fn poor_feedback_triggers_fallback() {
696        let feedback = crate::proxy::routing_feedback::RoutingFeedback::new();
697        for _ in 0..20 {
698            feedback.record_outcome("expensive", "fast", Some(0.4), 0, 0);
699        }
700        assert!(feedback.should_use_fallback());
701    }
702}