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 = "default_enforce_structured")]
547 pub enforce_structured: bool,
548 #[serde(default)]
553 pub bandit: Option<BanditConfig>,
554 #[serde(default)]
562 pub condense: Option<CondenseConfig>,
563 #[serde(default)]
572 pub prompt_cache: bool,
573 #[serde(default)]
581 pub verified_cache: Option<VerifiedCacheConfig>,
582 #[serde(default)]
591 pub speculation_band: Option<[f64; 2]>,
592 #[serde(default)]
596 pub exploration: Option<ExplorationConfig>,
597 #[serde(default)]
601 pub probe: Option<ProbeConfig>,
602 #[serde(default)]
606 pub predictor: Option<PredictorConfig>,
607 #[serde(default)]
612 pub elastic: Option<ElasticConfig>,
613}
614
615#[derive(Debug, Clone, Copy, Deserialize)]
621#[serde(deny_unknown_fields)]
622pub struct PredictorConfig {
623 #[serde(default = "default_predictor_lr")]
625 pub lr: f64,
626 #[serde(default = "default_predictor_l2")]
628 pub l2: f64,
629}
630
631fn default_predictor_lr() -> f64 {
632 0.05
633}
634
635fn default_predictor_l2() -> f64 {
636 1e-4
637}
638
639#[derive(Debug, Clone, Deserialize)]
641#[serde(deny_unknown_fields)]
642pub struct AdaptiveConfig {
643 pub alpha: f64,
645 #[serde(default = "default_adaptive_gamma")]
647 pub gamma: f64,
648}
649
650fn default_adaptive_gamma() -> f64 {
651 0.02
652}
653
654#[derive(Debug, Clone, Deserialize)]
666#[serde(deny_unknown_fields)]
667pub struct ExplorationConfig {
668 pub epsilon: f64,
673}
674
675#[derive(Debug, Clone, Copy, Deserialize)]
683#[serde(deny_unknown_fields)]
684pub struct ProbeConfig {
685 pub k: u32,
688 pub sample_rate: f64,
691}
692
693#[derive(Debug, Clone, Deserialize, PartialEq)]
709#[serde(deny_unknown_fields)]
710pub struct ElasticConfig {
711 pub expensive_gates: Vec<String>,
715 pub lambda: f64,
718 #[serde(default)]
721 pub alpha: Option<f64>,
722 #[serde(default)]
724 pub delta: Option<f64>,
725 #[serde(default)]
728 pub calibration_id: Option<String>,
729}
730
731#[derive(Debug, Clone, Deserialize)]
733#[serde(deny_unknown_fields)]
734pub struct CondenseConfig {
735 #[serde(default = "default_condense_keep_head")]
737 pub keep_head: usize,
738 #[serde(default = "default_condense_keep_tail")]
740 pub keep_tail: usize,
741}
742
743const fn default_condense_keep_head() -> usize {
744 2
745}
746
747const fn default_condense_keep_tail() -> usize {
748 6
749}
750
751#[derive(Debug, Clone, Deserialize)]
753#[serde(deny_unknown_fields)]
754pub struct VerifiedCacheConfig {
755 #[serde(default = "default_cache_ttl_secs")]
760 pub ttl_secs: u64,
761 #[serde(default = "default_cache_max_entries")]
764 pub max_entries: usize,
765 #[serde(default)]
776 pub redis_url: Option<String>,
777}
778
779const fn default_cache_ttl_secs() -> u64 {
780 15 * 60
781}
782
783const fn default_cache_max_entries() -> usize {
784 10_000
785}
786
787#[derive(Debug, Clone, Deserialize)]
791#[serde(deny_unknown_fields)]
792pub struct BanditConfig {
793 #[serde(default = "default_bandit_min_observations")]
796 pub min_observations: usize,
797 #[serde(default = "default_bandit_exploration")]
800 pub exploration: f64,
801 #[serde(default)]
806 pub algorithm: BanditAlgorithm,
807 #[serde(default = "default_bandit_discount")]
811 pub discount: f64,
812}
813
814#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
816#[serde(rename_all = "lowercase")]
817pub enum BanditAlgorithm {
818 #[default]
820 Ucb1,
821 Thompson,
823}
824
825fn default_bandit_discount() -> f64 {
826 1.0
827}
828
829fn default_bandit_min_observations() -> usize {
830 50
831}
832
833fn default_bandit_exploration() -> f64 {
834 1.0
835}
836
837const fn default_max_rungs() -> u32 {
838 3
839}
840
841fn default_enforce_structured() -> bool {
844 true
845}
846
847impl Default for Escalation {
848 fn default() -> Self {
849 Self {
850 max_rungs_per_request: default_max_rungs(),
851 session_promotion: None,
852 speculation: 0,
853 serve_threshold: None,
854 adaptive: None,
855 enforce_structured: default_enforce_structured(),
856 speculation_band: None,
857 bandit: None,
858 condense: None,
859 prompt_cache: false,
860 verified_cache: None,
861 exploration: None,
862 probe: None,
863 predictor: None,
864 elastic: None,
865 }
866 }
867}
868
869#[derive(Debug, Clone, Deserialize)]
871#[serde(deny_unknown_fields)]
872pub struct SessionPromotion {
873 pub after_failures: u32,
875 pub window: String,
878 #[serde(default = "default_promotion_probe_every")]
885 pub probe_every: u32,
886 #[serde(default = "default_promotion_max_sessions")]
891 pub max_sessions: usize,
892 #[serde(default)]
899 pub redis_url: Option<String>,
900}
901
902const fn default_promotion_probe_every() -> u32 {
903 5
906}
907
908const fn default_promotion_max_sessions() -> usize {
909 10_000
910}
911
912impl SessionPromotion {
913 pub fn window_duration(&self) -> Result<Duration> {
918 parse_window(&self.window)
919 }
920}
921
922fn parse_window(s: &str) -> Result<Duration> {
924 let s = s.trim();
925 let split = s
926 .find(|c: char| c.is_ascii_alphabetic())
927 .ok_or_else(|| Error::BadDuration(s.to_owned()))?;
928 let (num, unit) = s.split_at(split);
929 let n: u64 = num
930 .trim()
931 .parse()
932 .map_err(|_| Error::BadDuration(s.to_owned()))?;
933 let secs = match unit {
934 "s" => n,
935 "m" => n.saturating_mul(60),
936 "h" => n.saturating_mul(3600),
937 "d" => n.saturating_mul(86_400),
938 _ => return Err(Error::BadDuration(s.to_owned())),
939 };
940 Ok(Duration::from_secs(secs))
941}
942
943#[derive(Debug, Clone, PartialEq, Eq)]
945pub struct ModelRef {
946 pub provider: String,
948 pub model: String,
950}
951
952impl ModelRef {
953 pub fn parse(s: &str) -> Result<Self> {
958 match s.split_once('/') {
959 Some((p, m)) if !p.is_empty() && !m.is_empty() && !m.contains('/') => Ok(Self {
960 provider: p.to_owned(),
961 model: m.to_owned(),
962 }),
963 _ => Err(Error::BadModelRef(s.to_owned())),
964 }
965 }
966}
967
968const fn default_guardrail_cooldown() -> i64 {
969 3_600
970}
971
972impl Config {
973 pub fn parse(toml_str: &str) -> Result<Self> {
980 let config: Self = toml::from_str(toml_str)?;
981 for (i, route) in config.routes.iter().enumerate() {
985 if let Some(r) = &route.rollout {
986 r.validate()
987 .map_err(|e| Error::InvalidConfig(format!("route[{i}]: {e}")))?;
988 }
989 if let Some(sh) = &route.shadow {
990 sh.validate()
991 .map_err(|e| Error::InvalidConfig(format!("route[{i}]: {e}")))?;
992 }
993 }
994 if let Some(g) = &config.guardrail {
995 g.validate().map_err(Error::InvalidConfig)?;
996 }
997 if let Some(p) = &config.escalation.session_promotion {
998 p.window_duration()?;
1000 if p.probe_every == 0 {
1005 return Err(Error::InvalidConfig(
1006 "[escalation.session_promotion] probe_every must be >= 1. It is how a promoted \
1007 session ever returns to a cheaper rung; 0 would pin it permanently."
1008 .to_owned(),
1009 ));
1010 }
1011 if p.max_sessions == 0 {
1012 return Err(Error::InvalidConfig(
1013 "[escalation.session_promotion] max_sessions must be >= 1".to_owned(),
1014 ));
1015 }
1016 }
1017 let mut seen = std::collections::HashSet::new();
1018 for def in &config.gate_defs {
1019 if def.id.trim().is_empty() {
1020 return Err(Error::InvalidConfig("gate id must not be empty".to_owned()));
1021 }
1022 let kinds_set = [
1024 !def.cmd.is_empty(),
1025 def.judge.is_some(),
1026 def.consistency.is_some(),
1027 def.schema.is_some(),
1028 ]
1029 .iter()
1030 .filter(|&&b| b)
1031 .count();
1032 if kinds_set != 1 {
1033 return Err(Error::InvalidConfig(format!(
1034 "gate {:?} must set exactly one of `cmd`, `judge`, `consistency`, or `schema`",
1035 def.id
1036 )));
1037 }
1038 if let Some(judge) = &def.judge
1039 && !(0.0..=1.0).contains(&judge.threshold)
1040 {
1041 return Err(Error::InvalidConfig(format!(
1042 "gate {:?} judge threshold {} is outside [0, 1]",
1043 def.id, judge.threshold
1044 )));
1045 }
1046 if let Some(c) = &def.consistency {
1047 if !(2..=8).contains(&c.k) {
1048 return Err(Error::InvalidConfig(format!(
1049 "gate {:?} consistency k {} is outside [2, 8]",
1050 def.id, c.k
1051 )));
1052 }
1053 if !(0.0..=1.0).contains(&c.threshold) {
1054 return Err(Error::InvalidConfig(format!(
1055 "gate {:?} consistency threshold {} is outside [0, 1]",
1056 def.id, c.threshold
1057 )));
1058 }
1059 }
1060 if !seen.insert(def.id.as_str()) {
1061 return Err(Error::InvalidConfig(format!(
1062 "duplicate gate id {:?}",
1063 def.id
1064 )));
1065 }
1066 }
1067 for price in &config.price_defs {
1068 if price.model.trim().is_empty() {
1069 return Err(Error::InvalidConfig(
1070 "price model must not be empty".to_owned(),
1071 ));
1072 }
1073 let ok = |v: f64| v.is_finite() && v >= 0.0;
1074 if !ok(price.input_per_mtok) || !ok(price.output_per_mtok) {
1075 return Err(Error::InvalidConfig(format!(
1076 "price for {:?} must be finite and >= 0",
1077 price.model
1078 )));
1079 }
1080 }
1081 config.validate_ladders_are_priced()?;
1082 if let Some(b) = &config.escalation.bandit {
1083 if !b.exploration.is_finite() || b.exploration < 0.0 {
1084 return Err(Error::InvalidConfig(format!(
1085 "bandit.exploration must be finite and >= 0, got {}",
1086 b.exploration
1087 )));
1088 }
1089 if !b.discount.is_finite() || b.discount <= 0.0 || b.discount > 1.0 {
1090 return Err(Error::InvalidConfig(format!(
1091 "bandit.discount must be in (0, 1], got {}",
1092 b.discount
1093 )));
1094 }
1095 }
1096 if let Some([lo, hi]) = config.escalation.speculation_band {
1097 let ok = |v: f64| v.is_finite() && (0.0..=1.0).contains(&v);
1098 if !ok(lo) || !ok(hi) || lo > hi {
1099 return Err(Error::InvalidConfig(format!(
1100 "escalation.speculation_band must satisfy 0 <= low <= high <= 1, got [{lo}, {hi}]"
1101 )));
1102 }
1103 }
1104 if let Some(exp) = &config.escalation.exploration
1105 && (!exp.epsilon.is_finite() || exp.epsilon <= 0.0 || exp.epsilon > 0.5)
1106 {
1107 return Err(Error::InvalidConfig(format!(
1108 "escalation.exploration.epsilon must be finite and in (0, 0.5], got {}",
1109 exp.epsilon
1110 )));
1111 }
1112 if let Some(probe) = &config.escalation.probe {
1113 if !(2..=8).contains(&probe.k) {
1114 return Err(Error::InvalidConfig(format!(
1115 "escalation.probe.k must be in [2, 8], got {}",
1116 probe.k
1117 )));
1118 }
1119 if !probe.sample_rate.is_finite() || !(0.0..=1.0).contains(&probe.sample_rate) {
1120 return Err(Error::InvalidConfig(format!(
1121 "escalation.probe.sample_rate must be finite and in [0, 1], got {}",
1122 probe.sample_rate
1123 )));
1124 }
1125 }
1126 if let Some(pred) = &config.escalation.predictor {
1127 if !pred.lr.is_finite() || !(0.0..=1.0).contains(&pred.lr) || pred.lr == 0.0 {
1128 return Err(Error::InvalidConfig(format!(
1129 "escalation.predictor.lr must be finite and in (0, 1], got {}",
1130 pred.lr
1131 )));
1132 }
1133 if !pred.l2.is_finite() || pred.l2 < 0.0 {
1134 return Err(Error::InvalidConfig(format!(
1135 "escalation.predictor.l2 must be finite and >= 0, got {}",
1136 pred.l2
1137 )));
1138 }
1139 }
1140 if let Some(elastic) = &config.escalation.elastic {
1141 if elastic.expensive_gates.is_empty() {
1142 return Err(Error::InvalidConfig(
1143 "escalation.elastic.expensive_gates must name at least one gate to skip".into(),
1144 ));
1145 }
1146 if !elastic.lambda.is_finite() || !(0.0..=1.0).contains(&elastic.lambda) {
1147 return Err(Error::InvalidConfig(format!(
1148 "escalation.elastic.lambda must be finite and in [0, 1], got {}",
1149 elastic.lambda
1150 )));
1151 }
1152 }
1153 Ok(config)
1154 }
1155
1156 #[must_use]
1158 pub fn route_for(&self, f: &Features) -> Option<&Route> {
1159 self.routes.iter().find(|r| r.match_.matches(f))
1160 }
1161
1162 #[must_use]
1164 pub fn price_table(&self) -> crate::cost::PriceTable {
1165 self.price_defs
1166 .iter()
1167 .fold(crate::cost::PriceTable::defaults(), |table, p| {
1168 table.with_override(
1169 p.model.clone(),
1170 crate::cost::ModelPrice {
1171 input_per_mtok: p.input_per_mtok,
1172 output_per_mtok: p.output_per_mtok,
1173 },
1174 )
1175 })
1176 }
1177
1178 fn validate_ladders_are_priced(&self) -> Result<()> {
1189 let prices = self.price_table();
1190 for (i, route) in self.routes.iter().enumerate() {
1191 for rung in &route.ladder {
1192 if prices.get(rung).is_none() {
1193 return Err(Error::InvalidConfig(format!(
1194 "route[{i}] ladder rung {rung:?} has no price, so its cost would be \
1195 recorded as $0.00 and any [budget] cap would never trip. Declare it:\n\n\
1196 [[price]]\nmodel = {rung:?}\ninput_per_mtok = 0.0\noutput_per_mtok = 0.0\n\n\
1197 (use the real per-1M-token prices; 0.0 is correct only for a model you \
1198 host yourself)"
1199 )));
1200 }
1201 }
1202 }
1203 Ok(())
1204 }
1205}
1206
1207#[cfg(test)]
1208mod tests {
1209 use super::*;
1210 use crate::features::Features;
1211
1212 const SPEC_CONFIG: &str = r#"
1213[[route]]
1214match = { agent = "claude-code", subagent = ["test-runner", "explore"] }
1215mode = "enforce"
1216ladder = ["anthropic/claude-haiku-4-5", "anthropic/claude-sonnet-5"]
1217gates = ["schema", "judge-diff"]
1218
1219[[route]]
1220match = { task_kind = "code_edit" }
1221mode = "enforce"
1222ladder = ["anthropic/claude-sonnet-5", "anthropic/claude-opus-4-8"]
1223gates = ["patch-applies", "lint-diff", "judge-diff"]
1224deferred_gates = ["compiles", "tests"]
1225
1226[[route]]
1227match = {}
1228mode = "observe"
1229ladder = ["anthropic/claude-opus-4-8"]
1230
1231[budget]
1232per_request_usd = 0.50
1233per_session_usd = 10.00
1234per_day_usd = 250.00
1235on_exhausted = "serve_best_attempt"
1236
1237[escalation]
1238max_rungs_per_request = 3
1239session_promotion = { after_failures = 3, window = "30m" }
1240"#;
1241
1242 #[test]
1243 fn parses_the_spec_example() {
1244 let c = Config::parse(SPEC_CONFIG).unwrap();
1245 assert_eq!(c.routes.len(), 3);
1246 assert_eq!(c.routes[0].mode, Mode::Enforce);
1247 assert_eq!(
1248 c.routes[0].ladder,
1249 ["anthropic/claude-haiku-4-5", "anthropic/claude-sonnet-5"]
1250 );
1251 assert_eq!(c.routes[1].deferred_gates, ["compiles", "tests"]);
1252 assert_eq!(c.budget.per_request_usd, Some(0.50));
1253 assert_eq!(c.budget.on_exhausted, OnExhausted::ServeBestAttempt);
1254 assert_eq!(c.escalation.max_rungs_per_request, 3);
1255 let sp = c.escalation.session_promotion.as_ref().unwrap();
1256 assert_eq!(sp.after_failures, 3);
1257 assert_eq!(sp.window_duration().unwrap(), Duration::from_secs(1800));
1258 }
1259
1260 #[test]
1261 fn first_matching_route_wins() {
1262 let c = Config::parse(SPEC_CONFIG).unwrap();
1263
1264 let mut f = Features::new(TaskKind::Explore);
1266 f.agent = Some("claude-code".into());
1267 f.subagent = Some("test-runner".into());
1268 let r = c.route_for(&f).unwrap();
1269 assert_eq!(r.ladder[0], "anthropic/claude-haiku-4-5");
1270
1271 let f2 = Features::new(TaskKind::CodeEdit);
1273 let r2 = c.route_for(&f2).unwrap();
1274 assert_eq!(r2.gates, ["patch-applies", "lint-diff", "judge-diff"]);
1275
1276 let f3 = Features::new(TaskKind::Chat);
1278 let r3 = c.route_for(&f3).unwrap();
1279 assert_eq!(r3.mode, Mode::Observe);
1280 }
1281
1282 #[test]
1283 fn shipped_example_config_parses() {
1284 let toml = include_str!("../../../firstpass.example.toml");
1287 let c = Config::parse(toml).expect("firstpass.example.toml must parse");
1288 assert_eq!(c.routes.len(), 3);
1289 assert_eq!(c.routes[0].mode, Mode::Enforce);
1290 }
1291
1292 #[test]
1293 fn parses_gate_definitions() {
1294 let toml = r#"
1295[[route]]
1296match = {}
1297mode = "enforce"
1298ladder = ["anthropic/claude-haiku-4-5"]
1299gates = ["my-tests"]
1300
1301[[gate]]
1302id = "my-tests"
1303cmd = ["pytest", "-q"]
1304
1305[[gate]]
1306id = "judge"
1307cmd = ["bash", "-c", "./judge.sh"]
1308timeout_ms = 60000
1309"#;
1310 let c = Config::parse(toml).unwrap();
1311 assert_eq!(c.gate_defs.len(), 2);
1312 assert_eq!(c.gate_defs[0].id, "my-tests");
1313 assert_eq!(c.gate_defs[0].cmd, ["pytest", "-q"]);
1314 assert_eq!(c.gate_defs[0].timeout_ms, 30_000, "default timeout applies");
1315 assert_eq!(c.gate_defs[1].timeout_ms, 60_000);
1316 }
1317
1318 #[test]
1319 fn rejects_invalid_gate_definitions() {
1320 let empty_cmd = "[[gate]]\nid = \"g\"\ncmd = []\n";
1321 assert!(matches!(
1322 Config::parse(empty_cmd),
1323 Err(Error::InvalidConfig(_))
1324 ));
1325
1326 let dup = "[[gate]]\nid = \"g\"\ncmd = [\"a\"]\n[[gate]]\nid = \"g\"\ncmd = [\"b\"]\n";
1327 assert!(matches!(Config::parse(dup), Err(Error::InvalidConfig(_))));
1328 }
1329
1330 #[test]
1331 fn parses_consistency_gate_definition() {
1332 let toml = r#"
1333[[gate]]
1334id = "uncertainty"
1335consistency = { model = "anthropic/claude-haiku-4-5", k = 5, threshold = 0.6 }
1336"#;
1337 let c = Config::parse(toml).unwrap();
1338 assert_eq!(c.gate_defs.len(), 1);
1339 let cons = c.gate_defs[0].consistency.as_ref().unwrap();
1340 assert_eq!(cons.model, "anthropic/claude-haiku-4-5");
1341 assert_eq!(cons.k, 5);
1342 assert!((cons.threshold - 0.6).abs() < 1e-9);
1343 }
1344
1345 #[test]
1346 fn consistency_k_defaults_to_3() {
1347 let toml = "[[gate]]\nid = \"u\"\nconsistency = { model = \"anthropic/claude-haiku-4-5\", threshold = 0.7 }\n";
1348 let c = Config::parse(toml).unwrap();
1349 assert_eq!(c.gate_defs[0].consistency.as_ref().unwrap().k, 3);
1350 }
1351
1352 #[test]
1353 fn rejects_exactly_one_of_violations_for_consistency() {
1354 let both = "[[gate]]\nid = \"g\"\ncmd = [\"x\"]\nconsistency = { model = \"a/b\", threshold = 0.5 }\n";
1356 assert!(matches!(Config::parse(both), Err(Error::InvalidConfig(_))));
1357
1358 let bad_k =
1360 "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", k = 1, threshold = 0.5 }\n";
1361 assert!(matches!(Config::parse(bad_k), Err(Error::InvalidConfig(_))));
1362
1363 let bad_k2 =
1364 "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", k = 9, threshold = 0.5 }\n";
1365 assert!(matches!(
1366 Config::parse(bad_k2),
1367 Err(Error::InvalidConfig(_))
1368 ));
1369
1370 let bad_thresh =
1372 "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", threshold = 1.1 }\n";
1373 assert!(matches!(
1374 Config::parse(bad_thresh),
1375 Err(Error::InvalidConfig(_))
1376 ));
1377 }
1378
1379 #[test]
1380 fn parses_adaptive_conformal_config() {
1381 let c = Config::parse("[escalation.adaptive]\nalpha = 0.1\n").unwrap();
1382 let a = c
1383 .escalation
1384 .adaptive
1385 .expect("[escalation.adaptive] should parse");
1386 assert!((a.alpha - 0.1).abs() < 1e-9);
1387 assert!((a.gamma - 0.02).abs() < 1e-9, "gamma defaults to 0.02");
1388 assert!(Config::parse("").unwrap().escalation.adaptive.is_none());
1390 }
1391
1392 #[test]
1393 fn parses_provider_entries_and_ladders_can_reference_them() {
1394 let c = Config::parse(
1395 r#"
1396[[provider]]
1397id = "groq"
1398dialect = "openai"
1399base_url = "https://api.groq.com/openai"
1400api_key_env = "GROQ_API_KEY"
1401
1402[[provider]]
1403id = "ollama"
1404dialect = "openai"
1405base_url = "http://localhost:11434"
1406
1407# A bring-your-own provider has no built-in price, so the ladder must declare one or the
1408# receipt would report $0.00 for every Groq call.
1409[[price]]
1410model = "groq/llama-3.3-70b-versatile"
1411input_per_mtok = 0.59
1412output_per_mtok = 0.79
1413
1414[[route]]
1415match = {}
1416mode = "enforce"
1417ladder = ["groq/llama-3.3-70b-versatile", "anthropic/claude-sonnet-5"]
1418"#,
1419 )
1420 .unwrap();
1421 assert_eq!(c.providers.len(), 2);
1422 let groq = &c.providers[0];
1423 assert_eq!(groq.id, "groq");
1424 assert_eq!(groq.dialect, Dialect::Openai);
1425 assert_eq!(groq.base_url, "https://api.groq.com/openai");
1426 assert_eq!(groq.api_key_env.as_deref(), Some("GROQ_API_KEY"));
1427 assert_eq!(c.providers[1].id, "ollama");
1429 assert!(c.providers[1].api_key_env.is_none());
1430 assert!(Config::parse("").unwrap().providers.is_empty());
1432 }
1433
1434 #[test]
1435 fn parses_aws_sigv4_provider_and_defaults_auth_to_api_key() {
1436 let c = Config::parse(
1437 r#"
1438[[provider]]
1439id = "bedrock"
1440dialect = "anthropic"
1441auth = "aws_sigv4"
1442region = "us-east-1"
1443"#,
1444 )
1445 .unwrap();
1446 let bedrock = &c.providers[0];
1447 assert_eq!(bedrock.auth, AuthScheme::AwsSigv4);
1448 assert_eq!(bedrock.region.as_deref(), Some("us-east-1"));
1449 assert!(bedrock.project.is_none());
1450
1451 let c2 = Config::parse(
1454 r#"
1455[[provider]]
1456id = "groq"
1457dialect = "openai"
1458base_url = "https://api.groq.com/openai"
1459"#,
1460 )
1461 .unwrap();
1462 assert_eq!(c2.providers[0].auth, AuthScheme::ApiKey);
1463 }
1464
1465 #[test]
1466 fn all_documented_provider_shapes_parse() {
1467 let c = Config::parse(
1471 r#"
1472[[provider]]
1473id = "groq"
1474dialect = "openai"
1475base_url = "https://api.groq.com/openai"
1476api_key_env = "GROQ_API_KEY"
1477
1478[[provider]]
1479id = "ollama"
1480dialect = "openai"
1481base_url = "http://localhost:11434"
1482
1483[[provider]]
1484id = "gemini"
1485dialect = "gemini"
1486base_url = "https://generativelanguage.googleapis.com"
1487api_key_env = "GEMINI_API_KEY"
1488
1489[[provider]]
1490id = "bedrock"
1491dialect = "anthropic"
1492auth = "aws_sigv4"
1493region = "us-east-1"
1494
1495[[provider]]
1496id = "vertex"
1497dialect = "anthropic"
1498auth = "gcp_oauth"
1499region = "us-east5"
1500project = "my-gcp-project"
1501"#,
1502 )
1503 .expect("every documented provider shape must parse");
1504 assert_eq!(c.providers.len(), 5);
1505
1506 let gemini = c.providers.iter().find(|p| p.id == "gemini").unwrap();
1507 assert_eq!(gemini.dialect, Dialect::Gemini);
1508 assert_eq!(gemini.auth, AuthScheme::ApiKey);
1509
1510 let vertex = c.providers.iter().find(|p| p.id == "vertex").unwrap();
1511 assert_eq!(vertex.auth, AuthScheme::GcpOauth);
1512 assert_eq!(vertex.region.as_deref(), Some("us-east5"));
1513 assert_eq!(vertex.project.as_deref(), Some("my-gcp-project"));
1514 }
1515
1516 #[test]
1517 fn empty_match_is_wildcard() {
1518 let m = Match::default();
1519 assert!(m.matches(&Features::new(TaskKind::Other)));
1520 }
1521
1522 #[test]
1523 fn subagent_list_membership() {
1524 let c = Config::parse(SPEC_CONFIG).unwrap();
1525 let route0 = &c.routes[0];
1526 let mut f = Features::new(TaskKind::Other);
1527 f.agent = Some("claude-code".into());
1528 f.subagent = Some("docs-writer".into()); assert!(!route0.match_.matches(&f));
1530 f.subagent = Some("explore".into());
1531 assert!(route0.match_.matches(&f));
1532 }
1533
1534 #[test]
1535 fn model_ref_parsing() {
1536 let m = ModelRef::parse("anthropic/claude-haiku-4-5").unwrap();
1537 assert_eq!(m.provider, "anthropic");
1538 assert_eq!(m.model, "claude-haiku-4-5");
1539 assert!(ModelRef::parse("no-slash").is_err());
1540 assert!(ModelRef::parse("/model").is_err());
1541 assert!(ModelRef::parse("a/b/c").is_err());
1542 }
1543
1544 #[test]
1545 fn window_parsing_units_and_errors() {
1546 assert_eq!(parse_window("90s").unwrap(), Duration::from_secs(90));
1547 assert_eq!(parse_window("30m").unwrap(), Duration::from_secs(1800));
1548 assert_eq!(parse_window("2h").unwrap(), Duration::from_secs(7200));
1549 assert_eq!(parse_window("1d").unwrap(), Duration::from_secs(86_400));
1550 assert!(parse_window("30x").is_err());
1551 assert!(parse_window("abc").is_err());
1552 }
1553
1554 #[test]
1555 fn empty_config_defaults() {
1556 let c = Config::parse("").unwrap();
1557 assert!(c.routes.is_empty());
1558 assert_eq!(c.escalation.max_rungs_per_request, 3);
1559 assert_eq!(c.budget.on_exhausted, OnExhausted::ServeBestAttempt);
1560 }
1561
1562 #[test]
1565 fn parses_exploration_config() {
1566 let c = Config::parse("[escalation.exploration]\nepsilon = 0.1\n").unwrap();
1567 let exp = c
1568 .escalation
1569 .exploration
1570 .expect("[escalation.exploration] should parse");
1571 assert!((exp.epsilon - 0.1).abs() < 1e-12);
1572 assert!(Config::parse("").unwrap().escalation.exploration.is_none());
1574 }
1575
1576 #[test]
1577 fn exploration_epsilon_boundary_valid() {
1578 let c = Config::parse("[escalation.exploration]\nepsilon = 0.5\n").unwrap();
1580 assert!((c.escalation.exploration.unwrap().epsilon - 0.5).abs() < 1e-12);
1581 }
1582
1583 #[test]
1584 fn exploration_epsilon_above_half_rejected() {
1585 let bad = "[escalation.exploration]\nepsilon = 0.51\n";
1586 assert!(
1587 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1588 "epsilon > 0.5 must be rejected"
1589 );
1590 }
1591
1592 #[test]
1593 fn exploration_epsilon_zero_rejected() {
1594 let bad = "[escalation.exploration]\nepsilon = 0.0\n";
1595 assert!(
1596 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1597 "epsilon = 0 must be rejected (must be strictly positive)"
1598 );
1599 }
1600
1601 #[test]
1602 fn exploration_epsilon_negative_rejected() {
1603 let bad = "[escalation.exploration]\nepsilon = -0.1\n";
1604 assert!(
1605 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1606 "epsilon < 0 must be rejected"
1607 );
1608 }
1609
1610 #[test]
1611 fn gate_def_schema_and_on_abstain_parse() {
1612 let toml = r#"
1613[[route]]
1614match = {}
1615mode = "enforce"
1616ladder = ["anthropic/claude-haiku-4-5"]
1617gates = ["extract-shape"]
1618
1619[[gate]]
1620id = "extract-shape"
1621schema = { type = "object", required = ["name"] }
1622on_abstain = "fail_closed"
1623"#;
1624 let config = Config::parse(toml).expect("schema gate def must parse");
1625 let def = &config.gate_defs[0];
1626 assert_eq!(def.id, "extract-shape");
1627 let schema = def.schema.as_ref().expect("schema captured");
1628 assert_eq!(schema["type"], "object");
1629 assert_eq!(def.on_abstain, AbstainPolicy::FailClosed);
1630 }
1631
1632 #[test]
1633 fn gate_def_on_abstain_defaults_fail_open() {
1634 let toml = r#"
1635[[route]]
1636match = {}
1637mode = "enforce"
1638ladder = ["anthropic/claude-haiku-4-5"]
1639
1640[[gate]]
1641id = "tests"
1642cmd = ["true"]
1643"#;
1644 let config = Config::parse(toml).expect("parse");
1645 assert_eq!(config.gate_defs[0].on_abstain, AbstainPolicy::FailOpen);
1646 }
1647
1648 #[test]
1649 fn gate_def_rejects_schema_plus_cmd() {
1650 let toml = r#"
1651[[route]]
1652match = {}
1653mode = "enforce"
1654ladder = ["anthropic/claude-haiku-4-5"]
1655
1656[[gate]]
1657id = "both"
1658cmd = ["true"]
1659schema = { type = "object" }
1660"#;
1661 let err = Config::parse(toml).unwrap_err();
1662 assert!(
1663 err.to_string().contains("exactly one"),
1664 "two kinds must be rejected: {err}"
1665 );
1666 }
1667
1668 #[test]
1669 fn price_overrides_parse_and_validate() {
1670 let toml = r#"
1671[[route]]
1672match = {}
1673mode = "observe"
1674ladder = ["anthropic/claude-haiku-4-5"]
1675
1676[[price]]
1677model = "anthropic/claude-haiku-4-5"
1678input_per_mtok = 0.8
1679output_per_mtok = 4.0
1680"#;
1681 let config = Config::parse(toml).expect("price override must parse");
1682 assert_eq!(config.price_defs[0].model, "anthropic/claude-haiku-4-5");
1683 assert!((config.price_defs[0].input_per_mtok - 0.8).abs() < 1e-12);
1684
1685 let bad = toml.replace("input_per_mtok = 0.8", "input_per_mtok = -1.0");
1686 assert!(Config::parse(&bad).is_err(), "negative price rejected");
1687 }
1688
1689 #[test]
1694 fn balanced_preset_is_strict_noop() {
1695 let p = RoutingMode::Balanced.preset();
1696 assert!(
1697 p.speculation.is_none(),
1698 "Balanced must not override speculation"
1699 );
1700 assert!(
1701 p.max_rungs_delta.is_none(),
1702 "Balanced must not override max_rungs"
1703 );
1704 assert!(!p.start_at_top, "Balanced must not set start_at_top");
1705 }
1706
1707 #[test]
1708 fn cost_preset_disables_speculation() {
1709 let p = RoutingMode::Cost.preset();
1710 assert_eq!(p.speculation, Some(0));
1711 assert!(p.max_rungs_delta.is_none());
1712 assert!(!p.start_at_top);
1713 }
1714
1715 #[test]
1716 fn quality_preset_bumps_max_rungs_and_disables_speculation() {
1717 let p = RoutingMode::Quality.preset();
1718 assert_eq!(p.max_rungs_delta, Some(1));
1719 assert_eq!(p.speculation, Some(0));
1720 assert!(!p.start_at_top);
1721 }
1722
1723 #[test]
1724 fn latency_preset_enables_speculation() {
1725 let p = RoutingMode::Latency.preset();
1726 assert_eq!(p.speculation, Some(1));
1727 assert!(p.max_rungs_delta.is_none());
1728 assert!(!p.start_at_top);
1729 }
1730
1731 #[test]
1732 fn max_preset_sets_start_at_top_and_disables_speculation() {
1733 let p = RoutingMode::Max.preset();
1734 assert!(p.start_at_top);
1735 assert_eq!(p.speculation, Some(0));
1736 assert!(p.max_rungs_delta.is_none());
1737 }
1738
1739 #[test]
1740 fn routing_mode_as_str_roundtrips() {
1741 for mode in RoutingMode::ALL {
1742 let s = mode.as_str();
1743 let back: RoutingMode = serde_json::from_str(&format!("\"{s}\"")).unwrap();
1744 assert_eq!(*mode, back, "as_str/serde roundtrip for {s}");
1745 }
1746 }
1747
1748 #[test]
1749 fn routing_mode_defaults_to_balanced() {
1750 assert_eq!(RoutingMode::default(), RoutingMode::Balanced);
1751 }
1752
1753 #[test]
1754 fn route_routing_mode_parses_and_defaults_to_none() {
1755 let no_mode = Config::parse(
1757 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n",
1758 )
1759 .unwrap();
1760 assert_eq!(no_mode.routes[0].routing_mode, None);
1761
1762 let with_mode = Config::parse(
1764 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\nrouting_mode = \"cost\"\n",
1765 )
1766 .unwrap();
1767 assert_eq!(with_mode.routes[0].routing_mode, Some(RoutingMode::Cost));
1768 }
1769
1770 #[test]
1771 fn all_routing_modes_have_non_empty_description_and_tradeoff() {
1772 for mode in RoutingMode::ALL {
1773 let p = mode.preset();
1774 assert!(
1775 !p.description.is_empty(),
1776 "mode {} has empty description",
1777 mode.as_str()
1778 );
1779 assert!(
1780 !p.tradeoff.is_empty(),
1781 "mode {} has empty tradeoff",
1782 mode.as_str()
1783 );
1784 }
1785 }
1786
1787 #[test]
1788 fn bandit_thompson_and_band_parse_and_validate() {
1789 let toml = r#"
1790[[route]]
1791match = {}
1792mode = "enforce"
1793ladder = ["anthropic/claude-haiku-4-5"]
1794
1795[escalation]
1796speculation = 1
1797speculation_band = [0.3, 0.7]
1798
1799[escalation.bandit]
1800algorithm = "thompson"
1801discount = 0.98
1802"#;
1803 let config = Config::parse(toml).expect("thompson + band must parse");
1804 let b = config.escalation.bandit.as_ref().unwrap();
1805 assert_eq!(b.algorithm, BanditAlgorithm::Thompson);
1806 assert!((b.discount - 0.98).abs() < 1e-12);
1807 assert_eq!(config.escalation.speculation_band, Some([0.3, 0.7]));
1808
1809 let plain = Config::parse(
1811 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.bandit]\n",
1812 )
1813 .unwrap();
1814 let b = plain.escalation.bandit.as_ref().unwrap();
1815 assert_eq!(b.algorithm, BanditAlgorithm::Ucb1);
1816 assert!((b.discount - 1.0).abs() < 1e-12);
1817
1818 assert!(Config::parse(&toml.replace("discount = 0.98", "discount = 0.0")).is_err());
1820 assert!(
1821 Config::parse(&toml.replace(
1822 "speculation_band = [0.3, 0.7]",
1823 "speculation_band = [0.9, 0.2]"
1824 ))
1825 .is_err()
1826 );
1827 }
1828
1829 #[test]
1832 fn probe_absent_defaults_to_none() {
1833 let c = Config::parse("").unwrap();
1835 assert!(c.escalation.probe.is_none());
1836 }
1837
1838 #[test]
1839 fn parses_valid_probe_config() {
1840 let c = Config::parse("[escalation.probe]\nk = 5\nsample_rate = 0.1\n").unwrap();
1841 let p = c.escalation.probe.expect("[escalation.probe] should parse");
1842 assert_eq!(p.k, 5);
1843 assert!((p.sample_rate - 0.1).abs() < 1e-12);
1844 }
1845
1846 #[test]
1847 fn probe_sample_rate_boundaries_accepted() {
1848 let c0 = Config::parse("[escalation.probe]\nk = 2\nsample_rate = 0.0\n").unwrap();
1850 assert!((c0.escalation.probe.unwrap().sample_rate - 0.0).abs() < 1e-12);
1851 let c1 = Config::parse("[escalation.probe]\nk = 8\nsample_rate = 1.0\n").unwrap();
1852 assert!((c1.escalation.probe.unwrap().sample_rate - 1.0).abs() < 1e-12);
1853 }
1854
1855 #[test]
1856 fn probe_rejects_k_below_2() {
1857 let bad = "[escalation.probe]\nk = 1\nsample_rate = 0.5\n";
1858 assert!(
1859 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1860 "k=1 must be rejected"
1861 );
1862 }
1863
1864 #[test]
1865 fn probe_rejects_k_above_8() {
1866 let bad = "[escalation.probe]\nk = 9\nsample_rate = 0.5\n";
1867 assert!(
1868 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1869 "k=9 must be rejected"
1870 );
1871 }
1872
1873 #[test]
1874 fn probe_rejects_sample_rate_above_1() {
1875 let bad = "[escalation.probe]\nk = 5\nsample_rate = 1.5\n";
1876 assert!(
1877 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1878 "sample_rate=1.5 must be rejected"
1879 );
1880 }
1881
1882 #[test]
1883 fn probe_rejects_negative_sample_rate() {
1884 let bad = "[escalation.probe]\nk = 5\nsample_rate = -0.1\n";
1885 assert!(
1886 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1887 "negative sample_rate must be rejected"
1888 );
1889 }
1890
1891 #[test]
1892 fn predictor_config_parses_and_validates() {
1893 let base = "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.predictor]\nlr = 0.05\nl2 = 0.001\n";
1894 let cfg = Config::parse(base).expect("valid predictor must parse");
1895 let pred = cfg.escalation.predictor.unwrap();
1896 assert!((pred.lr - 0.05).abs() < 1e-12 && (pred.l2 - 0.001).abs() < 1e-12);
1897 let d = Config::parse("[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.predictor]\n").unwrap();
1899 assert!(d.escalation.predictor.is_some());
1900 assert!(Config::parse(&base.replace("lr = 0.05", "lr = 0.0")).is_err());
1902 assert!(Config::parse(&base.replace("lr = 0.05", "lr = 1.5")).is_err());
1903 assert!(Config::parse(&base.replace("l2 = 0.001", "l2 = -1.0")).is_err());
1904 }
1905
1906 #[test]
1911 fn unpriced_ladder_rung_is_rejected_and_an_explicit_price_fixes_it() {
1912 let unpriced =
1913 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"ollama/qwen2.5-coder:7b\"]\n";
1914 let err = Config::parse(unpriced).expect_err("an unpriced rung must not parse");
1915 let msg = err.to_string();
1916 assert!(
1917 msg.contains("ollama/qwen2.5-coder:7b") && msg.contains("[[price]]"),
1918 "the error must name the rung and the fix, got: {msg}"
1919 );
1920
1921 let declared = format!(
1923 "[[price]]\nmodel = \"ollama/qwen2.5-coder:7b\"\ninput_per_mtok = 0.0\noutput_per_mtok = 0.0\n{unpriced}"
1924 );
1925 let cfg = Config::parse(&declared).expect("an explicit zero price is legal");
1926 assert_eq!(
1927 cfg.price_table()
1928 .get("ollama/qwen2.5-coder:7b")
1929 .unwrap()
1930 .input_per_mtok,
1931 0.0
1932 );
1933
1934 assert!(
1936 Config::parse("[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n").is_ok()
1937 );
1938 }
1939
1940 #[test]
1944 fn shadow_config_parses_and_validates() {
1945 let base = "[[route]]\nmatch = {}\nmode = \"observe\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n";
1946 let none = Config::parse(base).unwrap();
1947 assert!(
1948 none.routes[0].shadow.is_none(),
1949 "shadow must be off by default"
1950 );
1951
1952 let ok = Config::parse(&format!(
1953 "{base}[route.shadow]\nsample_rate = 0.25\nmax_usd_per_day = 5.0\n"
1954 ))
1955 .unwrap();
1956 let sh = ok.routes[0].shadow.expect("shadow parsed");
1957 assert!((sh.sample_rate - 0.25).abs() < f64::EPSILON);
1958 assert!((sh.max_usd_per_day - 5.0).abs() < f64::EPSILON);
1959
1960 for bad in [
1961 "sample_rate = 1.5\nmax_usd_per_day = 5.0",
1962 "sample_rate = -0.1\nmax_usd_per_day = 5.0",
1963 "sample_rate = 0.1\nmax_usd_per_day = -1.0",
1964 ] {
1965 assert!(
1966 Config::parse(&format!("{base}[route.shadow]\n{bad}\n")).is_err(),
1967 "invalid shadow config accepted: {bad}"
1968 );
1969 }
1970 }
1971
1972 #[test]
1974 fn rollout_config_parses_and_validates() {
1975 let base = "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n";
1976 assert!(Config::parse(base).unwrap().routes[0].rollout.is_none());
1977 let ok = Config::parse(&format!(
1978 "{base}[route.rollout]\npercent = 5.0\nkey = \"session\"\n"
1979 ))
1980 .unwrap();
1981 assert!((ok.routes[0].rollout.unwrap().percent - 5.0).abs() < f64::EPSILON);
1982 assert!(Config::parse(&format!("{base}[route.rollout]\npercent = 140.0\n")).is_err());
1983 }
1984}