1use crate::error::{Error, Result};
9use crate::features::{Features, TaskKind};
10use serde::{Deserialize, Serialize};
11use std::time::Duration;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "lowercase")]
16pub enum Mode {
17 Enforce,
19 Observe,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
35#[serde(rename_all = "lowercase")]
36pub enum RoutingMode {
37 Observe,
40 Cost,
43 #[default]
46 Balanced,
47 Quality,
50 Latency,
53 Max,
56}
57
58impl RoutingMode {
59 #[must_use]
61 pub fn as_str(self) -> &'static str {
62 match self {
63 Self::Observe => "observe",
64 Self::Cost => "cost",
65 Self::Balanced => "balanced",
66 Self::Quality => "quality",
67 Self::Latency => "latency",
68 Self::Max => "max",
69 }
70 }
71
72 pub const ALL: &'static [Self] = &[
74 Self::Observe,
75 Self::Cost,
76 Self::Balanced,
77 Self::Quality,
78 Self::Latency,
79 Self::Max,
80 ];
81
82 #[must_use]
87 pub fn preset(self) -> ModePreset {
88 match self {
89 Self::Observe => ModePreset {
91 speculation: None,
92 max_rungs_delta: None,
93 start_at_top: false,
94 description: "shadow mode: forward without gating; verdicts are async learning signals only",
95 tradeoff: "zero added latency, zero quality proof; use to observe before enforcing",
96 },
97 Self::Cost => ModePreset {
99 speculation: Some(0),
100 max_rungs_delta: None,
101 start_at_top: false,
102 description: "no speculative prefetch; bandit start on cheapest rung",
103 tradeoff: "lowest token spend; can serve lower quality on hard or heavy traffic",
104 },
105 Self::Balanced => ModePreset {
107 speculation: None,
108 max_rungs_delta: None,
109 start_at_top: false,
110 description: "bandit start, configured thresholds and speculation (default — no behavioral change)",
111 tradeoff: "today's tuned balance; add a mode only when you need a different point",
112 },
113 Self::Quality => ModePreset {
115 speculation: Some(0),
116 max_rungs_delta: Some(1),
117 start_at_top: false,
118 description: "one extra escalation rung; serial (no speculative waste)",
119 tradeoff: "higher quality ceiling at higher cost; still bounded by gate verification",
120 },
121 Self::Latency => ModePreset {
123 speculation: Some(1),
124 max_rungs_delta: None,
125 start_at_top: false,
126 description: "speculation=1: always prefetch one rung ahead to cut p95 latency",
127 tradeoff: "pays 1 wasted speculative call when cheap rung passes; speculation_band is overridden",
128 },
129 Self::Max => ModePreset {
131 speculation: Some(0),
132 max_rungs_delta: None,
133 start_at_top: true,
134 description: "start at the top (most expensive) ladder rung; verification as insurance",
135 tradeoff: "highest quality, highest cost per call; bandit bypassed; savings minimal",
136 },
137 }
138 }
139}
140
141#[derive(Debug, Clone, Copy)]
146pub struct ModePreset {
147 pub speculation: Option<u32>,
149 pub max_rungs_delta: Option<i32>,
152 pub start_at_top: bool,
154 pub description: &'static str,
156 pub tradeoff: &'static str,
158}
159
160#[derive(Debug, Clone, Default, Deserialize)]
162#[serde(deny_unknown_fields)]
163pub struct Config {
164 #[serde(rename = "route", default)]
166 pub routes: Vec<Route>,
167 #[serde(default)]
169 pub budget: Budget,
170 #[serde(default)]
172 pub escalation: Escalation,
173 #[serde(default)]
176 pub guardrail: Option<crate::guardrail::Guardrail>,
177 #[serde(default = "default_guardrail_cooldown")]
181 pub guardrail_cooldown_secs: i64,
182 #[serde(rename = "gate", default)]
185 pub gate_defs: Vec<GateDef>,
186 #[serde(rename = "price", default)]
190 pub price_defs: Vec<PriceDef>,
191 #[serde(rename = "provider", default)]
196 pub providers: Vec<ProviderDef>,
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
203#[serde(rename_all = "lowercase")]
204pub enum Dialect {
205 Anthropic,
207 Openai,
209 Gemini,
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
218#[serde(rename_all = "snake_case")]
219pub enum AuthScheme {
220 #[default]
223 ApiKey,
224 AwsSigv4,
227 GcpOauth,
230}
231
232#[derive(Debug, Clone, Deserialize)]
235#[serde(deny_unknown_fields)]
236pub struct ProviderDef {
237 pub id: String,
239 pub dialect: Dialect,
241 #[serde(default)]
244 pub base_url: String,
245 #[serde(default)]
249 pub api_key_env: Option<String>,
250 #[serde(default)]
253 pub auth: AuthScheme,
254 #[serde(default)]
257 pub region: Option<String>,
258 #[serde(default)]
260 pub project: Option<String>,
261}
262
263#[derive(Debug, Clone, Deserialize)]
265#[serde(deny_unknown_fields)]
266pub struct PriceDef {
267 pub model: String,
269 pub input_per_mtok: f64,
271 pub output_per_mtok: f64,
273}
274
275#[derive(Debug, Clone, Deserialize)]
284#[serde(deny_unknown_fields)]
285pub struct GateDef {
286 pub id: String,
288 #[serde(default)]
291 pub cmd: Vec<String>,
292 #[serde(default = "default_gate_timeout_ms")]
295 pub timeout_ms: u64,
296 #[serde(default)]
298 pub judge: Option<JudgeDef>,
299 #[serde(default)]
301 pub consistency: Option<ConsistencyDef>,
302 #[serde(default)]
305 pub schema: Option<serde_json::Value>,
306 #[serde(default)]
311 pub on_abstain: AbstainPolicy,
312}
313
314#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
316#[serde(rename_all = "snake_case")]
317pub enum AbstainPolicy {
318 #[default]
320 FailOpen,
321 FailClosed,
323}
324
325#[derive(Debug, Clone, Deserialize)]
329#[serde(deny_unknown_fields)]
330pub struct JudgeDef {
331 pub model: String,
333 #[serde(default = "default_judge_threshold")]
335 pub threshold: f64,
336 #[serde(default)]
338 pub rubric: Option<String>,
339}
340
341#[derive(Debug, Clone, Deserialize)]
352#[serde(deny_unknown_fields)]
353pub struct ConsistencyDef {
354 pub model: String,
357 #[serde(default = "default_consistency_k")]
359 pub k: u32,
360 pub threshold: f64,
362}
363
364fn default_gate_timeout_ms() -> u64 {
367 30_000
368}
369
370fn default_judge_threshold() -> f64 {
372 0.7
373}
374
375fn default_consistency_k() -> u32 {
377 3
378}
379
380#[derive(Debug, Clone, Deserialize)]
382#[serde(deny_unknown_fields)]
383pub struct Route {
384 #[serde(rename = "match", default)]
386 pub match_: Match,
387 pub mode: Mode,
389 #[serde(default)]
391 pub ladder: Vec<String>,
392 #[serde(default)]
394 pub gates: Vec<String>,
395 #[serde(default)]
398 pub deferred_gates: Vec<String>,
399 #[serde(default)]
403 pub routing_mode: Option<RoutingMode>,
404 #[serde(default)]
408 pub rollout: Option<crate::rollout::Rollout>,
409 #[serde(default)]
414 pub shadow: Option<crate::rollout::Shadow>,
415}
416
417#[derive(Debug, Clone, Default, Deserialize)]
420#[serde(deny_unknown_fields)]
421pub struct Match {
422 #[serde(default)]
424 pub agent: Option<String>,
425 #[serde(default)]
427 pub subagent: Option<StringOrVec>,
428 #[serde(default)]
430 pub task_kind: Option<TaskKind>,
431 #[serde(default)]
433 pub language: Option<StringOrVec>,
434}
435
436impl Match {
437 #[must_use]
439 pub fn matches(&self, f: &Features) -> bool {
440 if let Some(agent) = &self.agent
441 && f.agent.as_deref() != Some(agent.as_str())
442 {
443 return false;
444 }
445 if let Some(subs) = &self.subagent {
446 match &f.subagent {
447 Some(s) if subs.contains(s) => {}
448 _ => return false,
449 }
450 }
451 if let Some(tk) = self.task_kind
452 && f.task_kind != tk
453 {
454 return false;
455 }
456 if let Some(langs) = &self.language {
457 match &f.language {
458 Some(l) if langs.contains(l) => {}
459 _ => return false,
460 }
461 }
462 true
463 }
464}
465
466#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
468#[serde(untagged)]
469pub enum StringOrVec {
470 One(String),
472 Many(Vec<String>),
474}
475
476impl StringOrVec {
477 #[must_use]
479 pub fn contains(&self, needle: &str) -> bool {
480 match self {
481 StringOrVec::One(s) => s == needle,
482 StringOrVec::Many(v) => v.iter().any(|s| s == needle),
483 }
484 }
485}
486
487#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
489#[serde(rename_all = "snake_case")]
490pub enum OnExhausted {
491 #[default]
493 ServeBestAttempt,
494 Error,
496}
497
498#[derive(Debug, Clone, Default, Deserialize)]
500#[serde(deny_unknown_fields)]
501pub struct Budget {
502 #[serde(default)]
504 pub per_request_usd: Option<f64>,
505 #[serde(default)]
507 pub per_session_usd: Option<f64>,
508 #[serde(default)]
510 pub per_day_usd: Option<f64>,
511 #[serde(default)]
513 pub on_exhausted: OnExhausted,
514}
515
516#[derive(Debug, Clone, Deserialize)]
518#[serde(deny_unknown_fields)]
519pub struct Escalation {
520 #[serde(default = "default_max_rungs")]
522 pub max_rungs_per_request: u32,
523 #[serde(default)]
525 pub session_promotion: Option<SessionPromotion>,
526 #[serde(default)]
529 pub speculation: u32,
530 #[serde(default)]
534 pub serve_threshold: Option<f64>,
535 #[serde(default)]
539 pub adaptive: Option<AdaptiveConfig>,
540 #[serde(default)]
542 pub eprocess: Option<EProcessConfig>,
543 #[serde(default = "default_enforce_structured")]
550 pub enforce_structured: bool,
551 #[serde(default)]
556 pub bandit: Option<BanditConfig>,
557 #[serde(default)]
565 pub condense: Option<CondenseConfig>,
566 #[serde(default)]
575 pub prompt_cache: bool,
576 #[serde(default)]
584 pub verified_cache: Option<VerifiedCacheConfig>,
585 #[serde(default)]
594 pub speculation_band: Option<[f64; 2]>,
595 #[serde(default)]
599 pub exploration: Option<ExplorationConfig>,
600 #[serde(default)]
604 pub probe: Option<ProbeConfig>,
605 #[serde(default)]
609 pub predictor: Option<PredictorConfig>,
610 #[serde(default)]
615 pub elastic: Option<ElasticConfig>,
616}
617
618#[derive(Debug, Clone, Copy, Deserialize)]
624#[serde(deny_unknown_fields)]
625pub struct PredictorConfig {
626 #[serde(default = "default_predictor_lr")]
628 pub lr: f64,
629 #[serde(default = "default_predictor_l2")]
631 pub l2: f64,
632}
633
634fn default_predictor_lr() -> f64 {
635 0.05
636}
637
638fn default_predictor_l2() -> f64 {
639 1e-4
640}
641
642#[derive(Debug, Clone, Deserialize)]
649#[serde(deny_unknown_fields)]
650pub struct EProcessConfig {
651 pub alpha: f64,
653 pub delta: f64,
655 #[serde(default = "default_bet")]
657 pub bet: f64,
658 #[serde(default = "default_grid")]
661 pub grid: Vec<f64>,
662}
663
664fn default_bet() -> f64 {
665 0.5
666}
667
668fn default_grid() -> Vec<f64> {
671 (0..=20).map(|i| f64::from(i) / 20.0).collect()
672}
673
674#[derive(Debug, Clone, Deserialize)]
676#[serde(deny_unknown_fields)]
677pub struct AdaptiveConfig {
678 pub alpha: f64,
680 #[serde(default = "default_adaptive_gamma")]
682 pub gamma: f64,
683}
684
685fn default_adaptive_gamma() -> f64 {
686 0.02
687}
688
689#[derive(Debug, Clone, Deserialize)]
701#[serde(deny_unknown_fields)]
702pub struct ExplorationConfig {
703 pub epsilon: f64,
708}
709
710#[derive(Debug, Clone, Copy, Deserialize)]
718#[serde(deny_unknown_fields)]
719pub struct ProbeConfig {
720 pub k: u32,
723 pub sample_rate: f64,
726}
727
728#[derive(Debug, Clone, Deserialize, PartialEq)]
744#[serde(deny_unknown_fields)]
745pub struct ElasticConfig {
746 pub expensive_gates: Vec<String>,
750 pub lambda: f64,
753 #[serde(default)]
756 pub alpha: Option<f64>,
757 #[serde(default)]
759 pub delta: Option<f64>,
760 #[serde(default)]
763 pub calibration_id: Option<String>,
764}
765
766#[derive(Debug, Clone, Deserialize)]
768#[serde(deny_unknown_fields)]
769pub struct CondenseConfig {
770 #[serde(default = "default_condense_keep_head")]
772 pub keep_head: usize,
773 #[serde(default = "default_condense_keep_tail")]
775 pub keep_tail: usize,
776}
777
778const fn default_condense_keep_head() -> usize {
779 2
780}
781
782const fn default_condense_keep_tail() -> usize {
783 6
784}
785
786#[derive(Debug, Clone, Deserialize)]
788#[serde(deny_unknown_fields)]
789pub struct VerifiedCacheConfig {
790 #[serde(default = "default_cache_ttl_secs")]
795 pub ttl_secs: u64,
796 #[serde(default = "default_cache_max_entries")]
799 pub max_entries: usize,
800 #[serde(default)]
811 pub redis_url: Option<String>,
812}
813
814const fn default_cache_ttl_secs() -> u64 {
815 15 * 60
816}
817
818const fn default_cache_max_entries() -> usize {
819 10_000
820}
821
822#[derive(Debug, Clone, Deserialize)]
826#[serde(deny_unknown_fields)]
827pub struct BanditConfig {
828 #[serde(default = "default_bandit_min_observations")]
831 pub min_observations: usize,
832 #[serde(default = "default_bandit_exploration")]
835 pub exploration: f64,
836 #[serde(default)]
841 pub algorithm: BanditAlgorithm,
842 #[serde(default = "default_bandit_discount")]
846 pub discount: f64,
847}
848
849#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
851#[serde(rename_all = "lowercase")]
852pub enum BanditAlgorithm {
853 #[default]
855 Ucb1,
856 Thompson,
858}
859
860fn default_bandit_discount() -> f64 {
861 1.0
862}
863
864fn default_bandit_min_observations() -> usize {
865 50
866}
867
868fn default_bandit_exploration() -> f64 {
869 1.0
870}
871
872const fn default_max_rungs() -> u32 {
873 3
874}
875
876fn default_enforce_structured() -> bool {
879 true
880}
881
882impl Default for Escalation {
883 fn default() -> Self {
884 Self {
885 max_rungs_per_request: default_max_rungs(),
886 session_promotion: None,
887 speculation: 0,
888 serve_threshold: None,
889 adaptive: None,
890 eprocess: None,
891 enforce_structured: default_enforce_structured(),
892 speculation_band: None,
893 bandit: None,
894 condense: None,
895 prompt_cache: false,
896 verified_cache: None,
897 exploration: None,
898 probe: None,
899 predictor: None,
900 elastic: None,
901 }
902 }
903}
904
905#[derive(Debug, Clone, Deserialize)]
907#[serde(deny_unknown_fields)]
908pub struct SessionPromotion {
909 pub after_failures: u32,
911 pub window: String,
914 #[serde(default = "default_promotion_probe_every")]
921 pub probe_every: u32,
922 #[serde(default = "default_promotion_max_sessions")]
927 pub max_sessions: usize,
928 #[serde(default)]
935 pub redis_url: Option<String>,
936}
937
938const fn default_promotion_probe_every() -> u32 {
939 5
942}
943
944const fn default_promotion_max_sessions() -> usize {
945 10_000
946}
947
948impl SessionPromotion {
949 pub fn window_duration(&self) -> Result<Duration> {
954 parse_window(&self.window)
955 }
956}
957
958fn parse_window(s: &str) -> Result<Duration> {
960 let s = s.trim();
961 let split = s
962 .find(|c: char| c.is_ascii_alphabetic())
963 .ok_or_else(|| Error::BadDuration(s.to_owned()))?;
964 let (num, unit) = s.split_at(split);
965 let n: u64 = num
966 .trim()
967 .parse()
968 .map_err(|_| Error::BadDuration(s.to_owned()))?;
969 let secs = match unit {
970 "s" => n,
971 "m" => n.saturating_mul(60),
972 "h" => n.saturating_mul(3600),
973 "d" => n.saturating_mul(86_400),
974 _ => return Err(Error::BadDuration(s.to_owned())),
975 };
976 Ok(Duration::from_secs(secs))
977}
978
979#[derive(Debug, Clone, PartialEq, Eq)]
981pub struct ModelRef {
982 pub provider: String,
984 pub model: String,
986}
987
988impl ModelRef {
989 pub fn parse(s: &str) -> Result<Self> {
994 match s.split_once('/') {
995 Some((p, m)) if !p.is_empty() && !m.is_empty() && !m.contains('/') => Ok(Self {
996 provider: p.to_owned(),
997 model: m.to_owned(),
998 }),
999 _ => Err(Error::BadModelRef(s.to_owned())),
1000 }
1001 }
1002}
1003
1004const fn default_guardrail_cooldown() -> i64 {
1005 3_600
1006}
1007
1008impl Config {
1009 pub fn parse(toml_str: &str) -> Result<Self> {
1016 let config: Self = toml::from_str(toml_str)?;
1017 for (i, route) in config.routes.iter().enumerate() {
1021 if let Some(r) = &route.rollout {
1022 r.validate()
1023 .map_err(|e| Error::InvalidConfig(format!("route[{i}]: {e}")))?;
1024 }
1025 if let Some(sh) = &route.shadow {
1026 sh.validate()
1027 .map_err(|e| Error::InvalidConfig(format!("route[{i}]: {e}")))?;
1028 }
1029 }
1030 if let Some(g) = &config.guardrail {
1031 g.validate().map_err(Error::InvalidConfig)?;
1032 }
1033 if let Some(p) = &config.escalation.session_promotion {
1034 p.window_duration()?;
1036 if p.probe_every == 0 {
1041 return Err(Error::InvalidConfig(
1042 "[escalation.session_promotion] probe_every must be >= 1. It is how a promoted \
1043 session ever returns to a cheaper rung; 0 would pin it permanently."
1044 .to_owned(),
1045 ));
1046 }
1047 if p.max_sessions == 0 {
1048 return Err(Error::InvalidConfig(
1049 "[escalation.session_promotion] max_sessions must be >= 1".to_owned(),
1050 ));
1051 }
1052 }
1053 let mut seen = std::collections::HashSet::new();
1054 for def in &config.gate_defs {
1055 if def.id.trim().is_empty() {
1056 return Err(Error::InvalidConfig("gate id must not be empty".to_owned()));
1057 }
1058 let kinds_set = [
1060 !def.cmd.is_empty(),
1061 def.judge.is_some(),
1062 def.consistency.is_some(),
1063 def.schema.is_some(),
1064 ]
1065 .iter()
1066 .filter(|&&b| b)
1067 .count();
1068 if kinds_set != 1 {
1069 return Err(Error::InvalidConfig(format!(
1070 "gate {:?} must set exactly one of `cmd`, `judge`, `consistency`, or `schema`",
1071 def.id
1072 )));
1073 }
1074 if let Some(judge) = &def.judge
1075 && !(0.0..=1.0).contains(&judge.threshold)
1076 {
1077 return Err(Error::InvalidConfig(format!(
1078 "gate {:?} judge threshold {} is outside [0, 1]",
1079 def.id, judge.threshold
1080 )));
1081 }
1082 if let Some(c) = &def.consistency {
1083 if !(2..=8).contains(&c.k) {
1084 return Err(Error::InvalidConfig(format!(
1085 "gate {:?} consistency k {} is outside [2, 8]",
1086 def.id, c.k
1087 )));
1088 }
1089 if !(0.0..=1.0).contains(&c.threshold) {
1090 return Err(Error::InvalidConfig(format!(
1091 "gate {:?} consistency threshold {} is outside [0, 1]",
1092 def.id, c.threshold
1093 )));
1094 }
1095 }
1096 if !seen.insert(def.id.as_str()) {
1097 return Err(Error::InvalidConfig(format!(
1098 "duplicate gate id {:?}",
1099 def.id
1100 )));
1101 }
1102 }
1103 for price in &config.price_defs {
1104 if price.model.trim().is_empty() {
1105 return Err(Error::InvalidConfig(
1106 "price model must not be empty".to_owned(),
1107 ));
1108 }
1109 let ok = |v: f64| v.is_finite() && v >= 0.0;
1110 if !ok(price.input_per_mtok) || !ok(price.output_per_mtok) {
1111 return Err(Error::InvalidConfig(format!(
1112 "price for {:?} must be finite and >= 0",
1113 price.model
1114 )));
1115 }
1116 }
1117 config.validate_ladders_are_priced()?;
1118 if let Some(b) = &config.escalation.bandit {
1119 if !b.exploration.is_finite() || b.exploration < 0.0 {
1120 return Err(Error::InvalidConfig(format!(
1121 "bandit.exploration must be finite and >= 0, got {}",
1122 b.exploration
1123 )));
1124 }
1125 if !b.discount.is_finite() || b.discount <= 0.0 || b.discount > 1.0 {
1126 return Err(Error::InvalidConfig(format!(
1127 "bandit.discount must be in (0, 1], got {}",
1128 b.discount
1129 )));
1130 }
1131 }
1132 if let Some([lo, hi]) = config.escalation.speculation_band {
1133 let ok = |v: f64| v.is_finite() && (0.0..=1.0).contains(&v);
1134 if !ok(lo) || !ok(hi) || lo > hi {
1135 return Err(Error::InvalidConfig(format!(
1136 "escalation.speculation_band must satisfy 0 <= low <= high <= 1, got [{lo}, {hi}]"
1137 )));
1138 }
1139 }
1140 if let Some(exp) = &config.escalation.exploration
1141 && (!exp.epsilon.is_finite() || exp.epsilon <= 0.0 || exp.epsilon > 0.5)
1142 {
1143 return Err(Error::InvalidConfig(format!(
1144 "escalation.exploration.epsilon must be finite and in (0, 0.5], got {}",
1145 exp.epsilon
1146 )));
1147 }
1148 if let Some(probe) = &config.escalation.probe {
1149 if !(2..=8).contains(&probe.k) {
1150 return Err(Error::InvalidConfig(format!(
1151 "escalation.probe.k must be in [2, 8], got {}",
1152 probe.k
1153 )));
1154 }
1155 if !probe.sample_rate.is_finite() || !(0.0..=1.0).contains(&probe.sample_rate) {
1156 return Err(Error::InvalidConfig(format!(
1157 "escalation.probe.sample_rate must be finite and in [0, 1], got {}",
1158 probe.sample_rate
1159 )));
1160 }
1161 }
1162 if let Some(pred) = &config.escalation.predictor {
1163 if !pred.lr.is_finite() || !(0.0..=1.0).contains(&pred.lr) || pred.lr == 0.0 {
1164 return Err(Error::InvalidConfig(format!(
1165 "escalation.predictor.lr must be finite and in (0, 1], got {}",
1166 pred.lr
1167 )));
1168 }
1169 if !pred.l2.is_finite() || pred.l2 < 0.0 {
1170 return Err(Error::InvalidConfig(format!(
1171 "escalation.predictor.l2 must be finite and >= 0, got {}",
1172 pred.l2
1173 )));
1174 }
1175 }
1176 if let Some(elastic) = &config.escalation.elastic {
1177 if elastic.expensive_gates.is_empty() {
1178 return Err(Error::InvalidConfig(
1179 "escalation.elastic.expensive_gates must name at least one gate to skip".into(),
1180 ));
1181 }
1182 if !elastic.lambda.is_finite() || !(0.0..=1.0).contains(&elastic.lambda) {
1183 return Err(Error::InvalidConfig(format!(
1184 "escalation.elastic.lambda must be finite and in [0, 1], got {}",
1185 elastic.lambda
1186 )));
1187 }
1188 }
1189 Ok(config)
1190 }
1191
1192 #[must_use]
1194 pub fn route_for(&self, f: &Features) -> Option<&Route> {
1195 self.routes.iter().find(|r| r.match_.matches(f))
1196 }
1197
1198 #[must_use]
1200 pub fn price_table(&self) -> crate::cost::PriceTable {
1201 self.price_defs
1202 .iter()
1203 .fold(crate::cost::PriceTable::defaults(), |table, p| {
1204 table.with_override(
1205 p.model.clone(),
1206 crate::cost::ModelPrice {
1207 input_per_mtok: p.input_per_mtok,
1208 output_per_mtok: p.output_per_mtok,
1209 },
1210 )
1211 })
1212 }
1213
1214 fn validate_ladders_are_priced(&self) -> Result<()> {
1225 let prices = self.price_table();
1226 for (i, route) in self.routes.iter().enumerate() {
1227 for rung in &route.ladder {
1228 if prices.get(rung).is_none() {
1229 return Err(Error::InvalidConfig(format!(
1230 "route[{i}] ladder rung {rung:?} has no price, so its cost would be \
1231 recorded as $0.00 and any [budget] cap would never trip. Declare it:\n\n\
1232 [[price]]\nmodel = {rung:?}\ninput_per_mtok = 0.0\noutput_per_mtok = 0.0\n\n\
1233 (use the real per-1M-token prices; 0.0 is correct only for a model you \
1234 host yourself)"
1235 )));
1236 }
1237 }
1238 }
1239 Ok(())
1240 }
1241}
1242
1243#[cfg(test)]
1244mod tests {
1245 use super::*;
1246 use crate::features::Features;
1247
1248 const SPEC_CONFIG: &str = r#"
1249[[route]]
1250match = { agent = "claude-code", subagent = ["test-runner", "explore"] }
1251mode = "enforce"
1252ladder = ["anthropic/claude-haiku-4-5", "anthropic/claude-sonnet-5"]
1253gates = ["schema", "judge-diff"]
1254
1255[[route]]
1256match = { task_kind = "code_edit" }
1257mode = "enforce"
1258ladder = ["anthropic/claude-sonnet-5", "anthropic/claude-opus-4-8"]
1259gates = ["patch-applies", "lint-diff", "judge-diff"]
1260deferred_gates = ["compiles", "tests"]
1261
1262[[route]]
1263match = {}
1264mode = "observe"
1265ladder = ["anthropic/claude-opus-4-8"]
1266
1267[budget]
1268per_request_usd = 0.50
1269per_session_usd = 10.00
1270per_day_usd = 250.00
1271on_exhausted = "serve_best_attempt"
1272
1273[escalation]
1274max_rungs_per_request = 3
1275session_promotion = { after_failures = 3, window = "30m" }
1276"#;
1277
1278 #[test]
1279 fn parses_the_spec_example() {
1280 let c = Config::parse(SPEC_CONFIG).unwrap();
1281 assert_eq!(c.routes.len(), 3);
1282 assert_eq!(c.routes[0].mode, Mode::Enforce);
1283 assert_eq!(
1284 c.routes[0].ladder,
1285 ["anthropic/claude-haiku-4-5", "anthropic/claude-sonnet-5"]
1286 );
1287 assert_eq!(c.routes[1].deferred_gates, ["compiles", "tests"]);
1288 assert_eq!(c.budget.per_request_usd, Some(0.50));
1289 assert_eq!(c.budget.on_exhausted, OnExhausted::ServeBestAttempt);
1290 assert_eq!(c.escalation.max_rungs_per_request, 3);
1291 let sp = c.escalation.session_promotion.as_ref().unwrap();
1292 assert_eq!(sp.after_failures, 3);
1293 assert_eq!(sp.window_duration().unwrap(), Duration::from_secs(1800));
1294 }
1295
1296 #[test]
1297 fn first_matching_route_wins() {
1298 let c = Config::parse(SPEC_CONFIG).unwrap();
1299
1300 let mut f = Features::new(TaskKind::Explore);
1302 f.agent = Some("claude-code".into());
1303 f.subagent = Some("test-runner".into());
1304 let r = c.route_for(&f).unwrap();
1305 assert_eq!(r.ladder[0], "anthropic/claude-haiku-4-5");
1306
1307 let f2 = Features::new(TaskKind::CodeEdit);
1309 let r2 = c.route_for(&f2).unwrap();
1310 assert_eq!(r2.gates, ["patch-applies", "lint-diff", "judge-diff"]);
1311
1312 let f3 = Features::new(TaskKind::Chat);
1314 let r3 = c.route_for(&f3).unwrap();
1315 assert_eq!(r3.mode, Mode::Observe);
1316 }
1317
1318 #[test]
1319 fn shipped_example_config_parses() {
1320 let toml = include_str!("../../../firstpass.example.toml");
1323 let c = Config::parse(toml).expect("firstpass.example.toml must parse");
1324 assert_eq!(c.routes.len(), 3);
1325 assert_eq!(c.routes[0].mode, Mode::Enforce);
1326 }
1327
1328 #[test]
1329 fn parses_gate_definitions() {
1330 let toml = r#"
1331[[route]]
1332match = {}
1333mode = "enforce"
1334ladder = ["anthropic/claude-haiku-4-5"]
1335gates = ["my-tests"]
1336
1337[[gate]]
1338id = "my-tests"
1339cmd = ["pytest", "-q"]
1340
1341[[gate]]
1342id = "judge"
1343cmd = ["bash", "-c", "./judge.sh"]
1344timeout_ms = 60000
1345"#;
1346 let c = Config::parse(toml).unwrap();
1347 assert_eq!(c.gate_defs.len(), 2);
1348 assert_eq!(c.gate_defs[0].id, "my-tests");
1349 assert_eq!(c.gate_defs[0].cmd, ["pytest", "-q"]);
1350 assert_eq!(c.gate_defs[0].timeout_ms, 30_000, "default timeout applies");
1351 assert_eq!(c.gate_defs[1].timeout_ms, 60_000);
1352 }
1353
1354 #[test]
1355 fn rejects_invalid_gate_definitions() {
1356 let empty_cmd = "[[gate]]\nid = \"g\"\ncmd = []\n";
1357 assert!(matches!(
1358 Config::parse(empty_cmd),
1359 Err(Error::InvalidConfig(_))
1360 ));
1361
1362 let dup = "[[gate]]\nid = \"g\"\ncmd = [\"a\"]\n[[gate]]\nid = \"g\"\ncmd = [\"b\"]\n";
1363 assert!(matches!(Config::parse(dup), Err(Error::InvalidConfig(_))));
1364 }
1365
1366 #[test]
1367 fn parses_consistency_gate_definition() {
1368 let toml = r#"
1369[[gate]]
1370id = "uncertainty"
1371consistency = { model = "anthropic/claude-haiku-4-5", k = 5, threshold = 0.6 }
1372"#;
1373 let c = Config::parse(toml).unwrap();
1374 assert_eq!(c.gate_defs.len(), 1);
1375 let cons = c.gate_defs[0].consistency.as_ref().unwrap();
1376 assert_eq!(cons.model, "anthropic/claude-haiku-4-5");
1377 assert_eq!(cons.k, 5);
1378 assert!((cons.threshold - 0.6).abs() < 1e-9);
1379 }
1380
1381 #[test]
1382 fn consistency_k_defaults_to_3() {
1383 let toml = "[[gate]]\nid = \"u\"\nconsistency = { model = \"anthropic/claude-haiku-4-5\", threshold = 0.7 }\n";
1384 let c = Config::parse(toml).unwrap();
1385 assert_eq!(c.gate_defs[0].consistency.as_ref().unwrap().k, 3);
1386 }
1387
1388 #[test]
1389 fn rejects_exactly_one_of_violations_for_consistency() {
1390 let both = "[[gate]]\nid = \"g\"\ncmd = [\"x\"]\nconsistency = { model = \"a/b\", threshold = 0.5 }\n";
1392 assert!(matches!(Config::parse(both), Err(Error::InvalidConfig(_))));
1393
1394 let bad_k =
1396 "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", k = 1, threshold = 0.5 }\n";
1397 assert!(matches!(Config::parse(bad_k), Err(Error::InvalidConfig(_))));
1398
1399 let bad_k2 =
1400 "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", k = 9, threshold = 0.5 }\n";
1401 assert!(matches!(
1402 Config::parse(bad_k2),
1403 Err(Error::InvalidConfig(_))
1404 ));
1405
1406 let bad_thresh =
1408 "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", threshold = 1.1 }\n";
1409 assert!(matches!(
1410 Config::parse(bad_thresh),
1411 Err(Error::InvalidConfig(_))
1412 ));
1413 }
1414
1415 #[test]
1416 fn parses_adaptive_conformal_config() {
1417 let c = Config::parse("[escalation.adaptive]\nalpha = 0.1\n").unwrap();
1418 let a = c
1419 .escalation
1420 .adaptive
1421 .expect("[escalation.adaptive] should parse");
1422 assert!((a.alpha - 0.1).abs() < 1e-9);
1423 assert!((a.gamma - 0.02).abs() < 1e-9, "gamma defaults to 0.02");
1424 assert!(Config::parse("").unwrap().escalation.adaptive.is_none());
1426 }
1427
1428 #[test]
1429 fn parses_provider_entries_and_ladders_can_reference_them() {
1430 let c = Config::parse(
1431 r#"
1432[[provider]]
1433id = "groq"
1434dialect = "openai"
1435base_url = "https://api.groq.com/openai"
1436api_key_env = "GROQ_API_KEY"
1437
1438[[provider]]
1439id = "ollama"
1440dialect = "openai"
1441base_url = "http://localhost:11434"
1442
1443# A bring-your-own provider has no built-in price, so the ladder must declare one or the
1444# receipt would report $0.00 for every Groq call.
1445[[price]]
1446model = "groq/llama-3.3-70b-versatile"
1447input_per_mtok = 0.59
1448output_per_mtok = 0.79
1449
1450[[route]]
1451match = {}
1452mode = "enforce"
1453ladder = ["groq/llama-3.3-70b-versatile", "anthropic/claude-sonnet-5"]
1454"#,
1455 )
1456 .unwrap();
1457 assert_eq!(c.providers.len(), 2);
1458 let groq = &c.providers[0];
1459 assert_eq!(groq.id, "groq");
1460 assert_eq!(groq.dialect, Dialect::Openai);
1461 assert_eq!(groq.base_url, "https://api.groq.com/openai");
1462 assert_eq!(groq.api_key_env.as_deref(), Some("GROQ_API_KEY"));
1463 assert_eq!(c.providers[1].id, "ollama");
1465 assert!(c.providers[1].api_key_env.is_none());
1466 assert!(Config::parse("").unwrap().providers.is_empty());
1468 }
1469
1470 #[test]
1471 fn parses_aws_sigv4_provider_and_defaults_auth_to_api_key() {
1472 let c = Config::parse(
1473 r#"
1474[[provider]]
1475id = "bedrock"
1476dialect = "anthropic"
1477auth = "aws_sigv4"
1478region = "us-east-1"
1479"#,
1480 )
1481 .unwrap();
1482 let bedrock = &c.providers[0];
1483 assert_eq!(bedrock.auth, AuthScheme::AwsSigv4);
1484 assert_eq!(bedrock.region.as_deref(), Some("us-east-1"));
1485 assert!(bedrock.project.is_none());
1486
1487 let c2 = Config::parse(
1490 r#"
1491[[provider]]
1492id = "groq"
1493dialect = "openai"
1494base_url = "https://api.groq.com/openai"
1495"#,
1496 )
1497 .unwrap();
1498 assert_eq!(c2.providers[0].auth, AuthScheme::ApiKey);
1499 }
1500
1501 #[test]
1502 fn all_documented_provider_shapes_parse() {
1503 let c = Config::parse(
1507 r#"
1508[[provider]]
1509id = "groq"
1510dialect = "openai"
1511base_url = "https://api.groq.com/openai"
1512api_key_env = "GROQ_API_KEY"
1513
1514[[provider]]
1515id = "ollama"
1516dialect = "openai"
1517base_url = "http://localhost:11434"
1518
1519[[provider]]
1520id = "gemini"
1521dialect = "gemini"
1522base_url = "https://generativelanguage.googleapis.com"
1523api_key_env = "GEMINI_API_KEY"
1524
1525[[provider]]
1526id = "bedrock"
1527dialect = "anthropic"
1528auth = "aws_sigv4"
1529region = "us-east-1"
1530
1531[[provider]]
1532id = "vertex"
1533dialect = "anthropic"
1534auth = "gcp_oauth"
1535region = "us-east5"
1536project = "my-gcp-project"
1537"#,
1538 )
1539 .expect("every documented provider shape must parse");
1540 assert_eq!(c.providers.len(), 5);
1541
1542 let gemini = c.providers.iter().find(|p| p.id == "gemini").unwrap();
1543 assert_eq!(gemini.dialect, Dialect::Gemini);
1544 assert_eq!(gemini.auth, AuthScheme::ApiKey);
1545
1546 let vertex = c.providers.iter().find(|p| p.id == "vertex").unwrap();
1547 assert_eq!(vertex.auth, AuthScheme::GcpOauth);
1548 assert_eq!(vertex.region.as_deref(), Some("us-east5"));
1549 assert_eq!(vertex.project.as_deref(), Some("my-gcp-project"));
1550 }
1551
1552 #[test]
1553 fn empty_match_is_wildcard() {
1554 let m = Match::default();
1555 assert!(m.matches(&Features::new(TaskKind::Other)));
1556 }
1557
1558 #[test]
1559 fn subagent_list_membership() {
1560 let c = Config::parse(SPEC_CONFIG).unwrap();
1561 let route0 = &c.routes[0];
1562 let mut f = Features::new(TaskKind::Other);
1563 f.agent = Some("claude-code".into());
1564 f.subagent = Some("docs-writer".into()); assert!(!route0.match_.matches(&f));
1566 f.subagent = Some("explore".into());
1567 assert!(route0.match_.matches(&f));
1568 }
1569
1570 #[test]
1571 fn model_ref_parsing() {
1572 let m = ModelRef::parse("anthropic/claude-haiku-4-5").unwrap();
1573 assert_eq!(m.provider, "anthropic");
1574 assert_eq!(m.model, "claude-haiku-4-5");
1575 assert!(ModelRef::parse("no-slash").is_err());
1576 assert!(ModelRef::parse("/model").is_err());
1577 assert!(ModelRef::parse("a/b/c").is_err());
1578 }
1579
1580 #[test]
1581 fn window_parsing_units_and_errors() {
1582 assert_eq!(parse_window("90s").unwrap(), Duration::from_secs(90));
1583 assert_eq!(parse_window("30m").unwrap(), Duration::from_secs(1800));
1584 assert_eq!(parse_window("2h").unwrap(), Duration::from_secs(7200));
1585 assert_eq!(parse_window("1d").unwrap(), Duration::from_secs(86_400));
1586 assert!(parse_window("30x").is_err());
1587 assert!(parse_window("abc").is_err());
1588 }
1589
1590 #[test]
1591 fn empty_config_defaults() {
1592 let c = Config::parse("").unwrap();
1593 assert!(c.routes.is_empty());
1594 assert_eq!(c.escalation.max_rungs_per_request, 3);
1595 assert_eq!(c.budget.on_exhausted, OnExhausted::ServeBestAttempt);
1596 }
1597
1598 #[test]
1601 fn parses_exploration_config() {
1602 let c = Config::parse("[escalation.exploration]\nepsilon = 0.1\n").unwrap();
1603 let exp = c
1604 .escalation
1605 .exploration
1606 .expect("[escalation.exploration] should parse");
1607 assert!((exp.epsilon - 0.1).abs() < 1e-12);
1608 assert!(Config::parse("").unwrap().escalation.exploration.is_none());
1610 }
1611
1612 #[test]
1613 fn exploration_epsilon_boundary_valid() {
1614 let c = Config::parse("[escalation.exploration]\nepsilon = 0.5\n").unwrap();
1616 assert!((c.escalation.exploration.unwrap().epsilon - 0.5).abs() < 1e-12);
1617 }
1618
1619 #[test]
1620 fn exploration_epsilon_above_half_rejected() {
1621 let bad = "[escalation.exploration]\nepsilon = 0.51\n";
1622 assert!(
1623 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1624 "epsilon > 0.5 must be rejected"
1625 );
1626 }
1627
1628 #[test]
1629 fn exploration_epsilon_zero_rejected() {
1630 let bad = "[escalation.exploration]\nepsilon = 0.0\n";
1631 assert!(
1632 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1633 "epsilon = 0 must be rejected (must be strictly positive)"
1634 );
1635 }
1636
1637 #[test]
1638 fn exploration_epsilon_negative_rejected() {
1639 let bad = "[escalation.exploration]\nepsilon = -0.1\n";
1640 assert!(
1641 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1642 "epsilon < 0 must be rejected"
1643 );
1644 }
1645
1646 #[test]
1647 fn gate_def_schema_and_on_abstain_parse() {
1648 let toml = r#"
1649[[route]]
1650match = {}
1651mode = "enforce"
1652ladder = ["anthropic/claude-haiku-4-5"]
1653gates = ["extract-shape"]
1654
1655[[gate]]
1656id = "extract-shape"
1657schema = { type = "object", required = ["name"] }
1658on_abstain = "fail_closed"
1659"#;
1660 let config = Config::parse(toml).expect("schema gate def must parse");
1661 let def = &config.gate_defs[0];
1662 assert_eq!(def.id, "extract-shape");
1663 let schema = def.schema.as_ref().expect("schema captured");
1664 assert_eq!(schema["type"], "object");
1665 assert_eq!(def.on_abstain, AbstainPolicy::FailClosed);
1666 }
1667
1668 #[test]
1669 fn gate_def_on_abstain_defaults_fail_open() {
1670 let toml = r#"
1671[[route]]
1672match = {}
1673mode = "enforce"
1674ladder = ["anthropic/claude-haiku-4-5"]
1675
1676[[gate]]
1677id = "tests"
1678cmd = ["true"]
1679"#;
1680 let config = Config::parse(toml).expect("parse");
1681 assert_eq!(config.gate_defs[0].on_abstain, AbstainPolicy::FailOpen);
1682 }
1683
1684 #[test]
1685 fn gate_def_rejects_schema_plus_cmd() {
1686 let toml = r#"
1687[[route]]
1688match = {}
1689mode = "enforce"
1690ladder = ["anthropic/claude-haiku-4-5"]
1691
1692[[gate]]
1693id = "both"
1694cmd = ["true"]
1695schema = { type = "object" }
1696"#;
1697 let err = Config::parse(toml).unwrap_err();
1698 assert!(
1699 err.to_string().contains("exactly one"),
1700 "two kinds must be rejected: {err}"
1701 );
1702 }
1703
1704 #[test]
1705 fn price_overrides_parse_and_validate() {
1706 let toml = r#"
1707[[route]]
1708match = {}
1709mode = "observe"
1710ladder = ["anthropic/claude-haiku-4-5"]
1711
1712[[price]]
1713model = "anthropic/claude-haiku-4-5"
1714input_per_mtok = 0.8
1715output_per_mtok = 4.0
1716"#;
1717 let config = Config::parse(toml).expect("price override must parse");
1718 assert_eq!(config.price_defs[0].model, "anthropic/claude-haiku-4-5");
1719 assert!((config.price_defs[0].input_per_mtok - 0.8).abs() < 1e-12);
1720
1721 let bad = toml.replace("input_per_mtok = 0.8", "input_per_mtok = -1.0");
1722 assert!(Config::parse(&bad).is_err(), "negative price rejected");
1723 }
1724
1725 #[test]
1730 fn balanced_preset_is_strict_noop() {
1731 let p = RoutingMode::Balanced.preset();
1732 assert!(
1733 p.speculation.is_none(),
1734 "Balanced must not override speculation"
1735 );
1736 assert!(
1737 p.max_rungs_delta.is_none(),
1738 "Balanced must not override max_rungs"
1739 );
1740 assert!(!p.start_at_top, "Balanced must not set start_at_top");
1741 }
1742
1743 #[test]
1744 fn cost_preset_disables_speculation() {
1745 let p = RoutingMode::Cost.preset();
1746 assert_eq!(p.speculation, Some(0));
1747 assert!(p.max_rungs_delta.is_none());
1748 assert!(!p.start_at_top);
1749 }
1750
1751 #[test]
1752 fn quality_preset_bumps_max_rungs_and_disables_speculation() {
1753 let p = RoutingMode::Quality.preset();
1754 assert_eq!(p.max_rungs_delta, Some(1));
1755 assert_eq!(p.speculation, Some(0));
1756 assert!(!p.start_at_top);
1757 }
1758
1759 #[test]
1760 fn latency_preset_enables_speculation() {
1761 let p = RoutingMode::Latency.preset();
1762 assert_eq!(p.speculation, Some(1));
1763 assert!(p.max_rungs_delta.is_none());
1764 assert!(!p.start_at_top);
1765 }
1766
1767 #[test]
1768 fn max_preset_sets_start_at_top_and_disables_speculation() {
1769 let p = RoutingMode::Max.preset();
1770 assert!(p.start_at_top);
1771 assert_eq!(p.speculation, Some(0));
1772 assert!(p.max_rungs_delta.is_none());
1773 }
1774
1775 #[test]
1776 fn routing_mode_as_str_roundtrips() {
1777 for mode in RoutingMode::ALL {
1778 let s = mode.as_str();
1779 let back: RoutingMode = serde_json::from_str(&format!("\"{s}\"")).unwrap();
1780 assert_eq!(*mode, back, "as_str/serde roundtrip for {s}");
1781 }
1782 }
1783
1784 #[test]
1785 fn routing_mode_defaults_to_balanced() {
1786 assert_eq!(RoutingMode::default(), RoutingMode::Balanced);
1787 }
1788
1789 #[test]
1790 fn route_routing_mode_parses_and_defaults_to_none() {
1791 let no_mode = Config::parse(
1793 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n",
1794 )
1795 .unwrap();
1796 assert_eq!(no_mode.routes[0].routing_mode, None);
1797
1798 let with_mode = Config::parse(
1800 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\nrouting_mode = \"cost\"\n",
1801 )
1802 .unwrap();
1803 assert_eq!(with_mode.routes[0].routing_mode, Some(RoutingMode::Cost));
1804 }
1805
1806 #[test]
1807 fn all_routing_modes_have_non_empty_description_and_tradeoff() {
1808 for mode in RoutingMode::ALL {
1809 let p = mode.preset();
1810 assert!(
1811 !p.description.is_empty(),
1812 "mode {} has empty description",
1813 mode.as_str()
1814 );
1815 assert!(
1816 !p.tradeoff.is_empty(),
1817 "mode {} has empty tradeoff",
1818 mode.as_str()
1819 );
1820 }
1821 }
1822
1823 #[test]
1824 fn bandit_thompson_and_band_parse_and_validate() {
1825 let toml = r#"
1826[[route]]
1827match = {}
1828mode = "enforce"
1829ladder = ["anthropic/claude-haiku-4-5"]
1830
1831[escalation]
1832speculation = 1
1833speculation_band = [0.3, 0.7]
1834
1835[escalation.bandit]
1836algorithm = "thompson"
1837discount = 0.98
1838"#;
1839 let config = Config::parse(toml).expect("thompson + band must parse");
1840 let b = config.escalation.bandit.as_ref().unwrap();
1841 assert_eq!(b.algorithm, BanditAlgorithm::Thompson);
1842 assert!((b.discount - 0.98).abs() < 1e-12);
1843 assert_eq!(config.escalation.speculation_band, Some([0.3, 0.7]));
1844
1845 let plain = Config::parse(
1847 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.bandit]\n",
1848 )
1849 .unwrap();
1850 let b = plain.escalation.bandit.as_ref().unwrap();
1851 assert_eq!(b.algorithm, BanditAlgorithm::Ucb1);
1852 assert!((b.discount - 1.0).abs() < 1e-12);
1853
1854 assert!(Config::parse(&toml.replace("discount = 0.98", "discount = 0.0")).is_err());
1856 assert!(
1857 Config::parse(&toml.replace(
1858 "speculation_band = [0.3, 0.7]",
1859 "speculation_band = [0.9, 0.2]"
1860 ))
1861 .is_err()
1862 );
1863 }
1864
1865 #[test]
1868 fn probe_absent_defaults_to_none() {
1869 let c = Config::parse("").unwrap();
1871 assert!(c.escalation.probe.is_none());
1872 }
1873
1874 #[test]
1875 fn parses_valid_probe_config() {
1876 let c = Config::parse("[escalation.probe]\nk = 5\nsample_rate = 0.1\n").unwrap();
1877 let p = c.escalation.probe.expect("[escalation.probe] should parse");
1878 assert_eq!(p.k, 5);
1879 assert!((p.sample_rate - 0.1).abs() < 1e-12);
1880 }
1881
1882 #[test]
1883 fn probe_sample_rate_boundaries_accepted() {
1884 let c0 = Config::parse("[escalation.probe]\nk = 2\nsample_rate = 0.0\n").unwrap();
1886 assert!((c0.escalation.probe.unwrap().sample_rate - 0.0).abs() < 1e-12);
1887 let c1 = Config::parse("[escalation.probe]\nk = 8\nsample_rate = 1.0\n").unwrap();
1888 assert!((c1.escalation.probe.unwrap().sample_rate - 1.0).abs() < 1e-12);
1889 }
1890
1891 #[test]
1892 fn probe_rejects_k_below_2() {
1893 let bad = "[escalation.probe]\nk = 1\nsample_rate = 0.5\n";
1894 assert!(
1895 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1896 "k=1 must be rejected"
1897 );
1898 }
1899
1900 #[test]
1901 fn probe_rejects_k_above_8() {
1902 let bad = "[escalation.probe]\nk = 9\nsample_rate = 0.5\n";
1903 assert!(
1904 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1905 "k=9 must be rejected"
1906 );
1907 }
1908
1909 #[test]
1910 fn probe_rejects_sample_rate_above_1() {
1911 let bad = "[escalation.probe]\nk = 5\nsample_rate = 1.5\n";
1912 assert!(
1913 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1914 "sample_rate=1.5 must be rejected"
1915 );
1916 }
1917
1918 #[test]
1919 fn probe_rejects_negative_sample_rate() {
1920 let bad = "[escalation.probe]\nk = 5\nsample_rate = -0.1\n";
1921 assert!(
1922 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1923 "negative sample_rate must be rejected"
1924 );
1925 }
1926
1927 #[test]
1928 fn predictor_config_parses_and_validates() {
1929 let base = "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.predictor]\nlr = 0.05\nl2 = 0.001\n";
1930 let cfg = Config::parse(base).expect("valid predictor must parse");
1931 let pred = cfg.escalation.predictor.unwrap();
1932 assert!((pred.lr - 0.05).abs() < 1e-12 && (pred.l2 - 0.001).abs() < 1e-12);
1933 let d = Config::parse("[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.predictor]\n").unwrap();
1935 assert!(d.escalation.predictor.is_some());
1936 assert!(Config::parse(&base.replace("lr = 0.05", "lr = 0.0")).is_err());
1938 assert!(Config::parse(&base.replace("lr = 0.05", "lr = 1.5")).is_err());
1939 assert!(Config::parse(&base.replace("l2 = 0.001", "l2 = -1.0")).is_err());
1940 }
1941
1942 #[test]
1947 fn unpriced_ladder_rung_is_rejected_and_an_explicit_price_fixes_it() {
1948 let unpriced =
1949 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"ollama/qwen2.5-coder:7b\"]\n";
1950 let err = Config::parse(unpriced).expect_err("an unpriced rung must not parse");
1951 let msg = err.to_string();
1952 assert!(
1953 msg.contains("ollama/qwen2.5-coder:7b") && msg.contains("[[price]]"),
1954 "the error must name the rung and the fix, got: {msg}"
1955 );
1956
1957 let declared = format!(
1959 "[[price]]\nmodel = \"ollama/qwen2.5-coder:7b\"\ninput_per_mtok = 0.0\noutput_per_mtok = 0.0\n{unpriced}"
1960 );
1961 let cfg = Config::parse(&declared).expect("an explicit zero price is legal");
1962 assert_eq!(
1963 cfg.price_table()
1964 .get("ollama/qwen2.5-coder:7b")
1965 .unwrap()
1966 .input_per_mtok,
1967 0.0
1968 );
1969
1970 assert!(
1972 Config::parse("[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n").is_ok()
1973 );
1974 }
1975
1976 #[test]
1980 fn shadow_config_parses_and_validates() {
1981 let base = "[[route]]\nmatch = {}\nmode = \"observe\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n";
1982 let none = Config::parse(base).unwrap();
1983 assert!(
1984 none.routes[0].shadow.is_none(),
1985 "shadow must be off by default"
1986 );
1987
1988 let ok = Config::parse(&format!(
1989 "{base}[route.shadow]\nsample_rate = 0.25\nmax_usd_per_day = 5.0\n"
1990 ))
1991 .unwrap();
1992 let sh = ok.routes[0].shadow.expect("shadow parsed");
1993 assert!((sh.sample_rate - 0.25).abs() < f64::EPSILON);
1994 assert!((sh.max_usd_per_day - 5.0).abs() < f64::EPSILON);
1995
1996 for bad in [
1997 "sample_rate = 1.5\nmax_usd_per_day = 5.0",
1998 "sample_rate = -0.1\nmax_usd_per_day = 5.0",
1999 "sample_rate = 0.1\nmax_usd_per_day = -1.0",
2000 ] {
2001 assert!(
2002 Config::parse(&format!("{base}[route.shadow]\n{bad}\n")).is_err(),
2003 "invalid shadow config accepted: {bad}"
2004 );
2005 }
2006 }
2007
2008 #[test]
2010 fn rollout_config_parses_and_validates() {
2011 let base = "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n";
2012 assert!(Config::parse(base).unwrap().routes[0].rollout.is_none());
2013 let ok = Config::parse(&format!(
2014 "{base}[route.rollout]\npercent = 5.0\nkey = \"session\"\n"
2015 ))
2016 .unwrap();
2017 assert!((ok.routes[0].rollout.unwrap().percent - 5.0).abs() < f64::EPSILON);
2018 assert!(Config::parse(&format!("{base}[route.rollout]\npercent = 140.0\n")).is_err());
2019 }
2020}