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)]
563 pub speculation_band: Option<[f64; 2]>,
564 #[serde(default)]
568 pub exploration: Option<ExplorationConfig>,
569 #[serde(default)]
573 pub probe: Option<ProbeConfig>,
574 #[serde(default)]
578 pub predictor: Option<PredictorConfig>,
579 #[serde(default)]
584 pub elastic: Option<ElasticConfig>,
585}
586
587#[derive(Debug, Clone, Copy, Deserialize)]
593#[serde(deny_unknown_fields)]
594pub struct PredictorConfig {
595 #[serde(default = "default_predictor_lr")]
597 pub lr: f64,
598 #[serde(default = "default_predictor_l2")]
600 pub l2: f64,
601}
602
603fn default_predictor_lr() -> f64 {
604 0.05
605}
606
607fn default_predictor_l2() -> f64 {
608 1e-4
609}
610
611#[derive(Debug, Clone, Deserialize)]
613#[serde(deny_unknown_fields)]
614pub struct AdaptiveConfig {
615 pub alpha: f64,
617 #[serde(default = "default_adaptive_gamma")]
619 pub gamma: f64,
620}
621
622fn default_adaptive_gamma() -> f64 {
623 0.02
624}
625
626#[derive(Debug, Clone, Deserialize)]
638#[serde(deny_unknown_fields)]
639pub struct ExplorationConfig {
640 pub epsilon: f64,
645}
646
647#[derive(Debug, Clone, Copy, Deserialize)]
655#[serde(deny_unknown_fields)]
656pub struct ProbeConfig {
657 pub k: u32,
660 pub sample_rate: f64,
663}
664
665#[derive(Debug, Clone, Deserialize, PartialEq)]
681#[serde(deny_unknown_fields)]
682pub struct ElasticConfig {
683 pub expensive_gates: Vec<String>,
687 pub lambda: f64,
690 #[serde(default)]
693 pub alpha: Option<f64>,
694 #[serde(default)]
696 pub delta: Option<f64>,
697 #[serde(default)]
700 pub calibration_id: Option<String>,
701}
702
703#[derive(Debug, Clone, Deserialize)]
707#[serde(deny_unknown_fields)]
708pub struct BanditConfig {
709 #[serde(default = "default_bandit_min_observations")]
712 pub min_observations: usize,
713 #[serde(default = "default_bandit_exploration")]
716 pub exploration: f64,
717 #[serde(default)]
722 pub algorithm: BanditAlgorithm,
723 #[serde(default = "default_bandit_discount")]
727 pub discount: f64,
728}
729
730#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
732#[serde(rename_all = "lowercase")]
733pub enum BanditAlgorithm {
734 #[default]
736 Ucb1,
737 Thompson,
739}
740
741fn default_bandit_discount() -> f64 {
742 1.0
743}
744
745fn default_bandit_min_observations() -> usize {
746 50
747}
748
749fn default_bandit_exploration() -> f64 {
750 1.0
751}
752
753const fn default_max_rungs() -> u32 {
754 3
755}
756
757fn default_enforce_structured() -> bool {
760 true
761}
762
763impl Default for Escalation {
764 fn default() -> Self {
765 Self {
766 max_rungs_per_request: default_max_rungs(),
767 session_promotion: None,
768 speculation: 0,
769 serve_threshold: None,
770 adaptive: None,
771 enforce_structured: default_enforce_structured(),
772 speculation_band: None,
773 bandit: None,
774 exploration: None,
775 probe: None,
776 predictor: None,
777 elastic: None,
778 }
779 }
780}
781
782#[derive(Debug, Clone, Deserialize)]
784#[serde(deny_unknown_fields)]
785pub struct SessionPromotion {
786 pub after_failures: u32,
788 pub window: String,
790}
791
792impl SessionPromotion {
793 pub fn window_duration(&self) -> Result<Duration> {
798 parse_window(&self.window)
799 }
800}
801
802fn parse_window(s: &str) -> Result<Duration> {
804 let s = s.trim();
805 let split = s
806 .find(|c: char| c.is_ascii_alphabetic())
807 .ok_or_else(|| Error::BadDuration(s.to_owned()))?;
808 let (num, unit) = s.split_at(split);
809 let n: u64 = num
810 .trim()
811 .parse()
812 .map_err(|_| Error::BadDuration(s.to_owned()))?;
813 let secs = match unit {
814 "s" => n,
815 "m" => n.saturating_mul(60),
816 "h" => n.saturating_mul(3600),
817 "d" => n.saturating_mul(86_400),
818 _ => return Err(Error::BadDuration(s.to_owned())),
819 };
820 Ok(Duration::from_secs(secs))
821}
822
823#[derive(Debug, Clone, PartialEq, Eq)]
825pub struct ModelRef {
826 pub provider: String,
828 pub model: String,
830}
831
832impl ModelRef {
833 pub fn parse(s: &str) -> Result<Self> {
838 match s.split_once('/') {
839 Some((p, m)) if !p.is_empty() && !m.is_empty() && !m.contains('/') => Ok(Self {
840 provider: p.to_owned(),
841 model: m.to_owned(),
842 }),
843 _ => Err(Error::BadModelRef(s.to_owned())),
844 }
845 }
846}
847
848const fn default_guardrail_cooldown() -> i64 {
849 3_600
850}
851
852impl Config {
853 pub fn parse(toml_str: &str) -> Result<Self> {
860 let config: Self = toml::from_str(toml_str)?;
861 for (i, route) in config.routes.iter().enumerate() {
865 if let Some(r) = &route.rollout {
866 r.validate()
867 .map_err(|e| Error::InvalidConfig(format!("route[{i}]: {e}")))?;
868 }
869 if let Some(sh) = &route.shadow {
870 sh.validate()
871 .map_err(|e| Error::InvalidConfig(format!("route[{i}]: {e}")))?;
872 }
873 }
874 if let Some(g) = &config.guardrail {
875 g.validate().map_err(Error::InvalidConfig)?;
876 }
877 let mut seen = std::collections::HashSet::new();
878 for def in &config.gate_defs {
879 if def.id.trim().is_empty() {
880 return Err(Error::InvalidConfig("gate id must not be empty".to_owned()));
881 }
882 let kinds_set = [
884 !def.cmd.is_empty(),
885 def.judge.is_some(),
886 def.consistency.is_some(),
887 def.schema.is_some(),
888 ]
889 .iter()
890 .filter(|&&b| b)
891 .count();
892 if kinds_set != 1 {
893 return Err(Error::InvalidConfig(format!(
894 "gate {:?} must set exactly one of `cmd`, `judge`, `consistency`, or `schema`",
895 def.id
896 )));
897 }
898 if let Some(judge) = &def.judge
899 && !(0.0..=1.0).contains(&judge.threshold)
900 {
901 return Err(Error::InvalidConfig(format!(
902 "gate {:?} judge threshold {} is outside [0, 1]",
903 def.id, judge.threshold
904 )));
905 }
906 if let Some(c) = &def.consistency {
907 if !(2..=8).contains(&c.k) {
908 return Err(Error::InvalidConfig(format!(
909 "gate {:?} consistency k {} is outside [2, 8]",
910 def.id, c.k
911 )));
912 }
913 if !(0.0..=1.0).contains(&c.threshold) {
914 return Err(Error::InvalidConfig(format!(
915 "gate {:?} consistency threshold {} is outside [0, 1]",
916 def.id, c.threshold
917 )));
918 }
919 }
920 if !seen.insert(def.id.as_str()) {
921 return Err(Error::InvalidConfig(format!(
922 "duplicate gate id {:?}",
923 def.id
924 )));
925 }
926 }
927 for price in &config.price_defs {
928 if price.model.trim().is_empty() {
929 return Err(Error::InvalidConfig(
930 "price model must not be empty".to_owned(),
931 ));
932 }
933 let ok = |v: f64| v.is_finite() && v >= 0.0;
934 if !ok(price.input_per_mtok) || !ok(price.output_per_mtok) {
935 return Err(Error::InvalidConfig(format!(
936 "price for {:?} must be finite and >= 0",
937 price.model
938 )));
939 }
940 }
941 config.validate_ladders_are_priced()?;
942 if let Some(b) = &config.escalation.bandit {
943 if !b.exploration.is_finite() || b.exploration < 0.0 {
944 return Err(Error::InvalidConfig(format!(
945 "bandit.exploration must be finite and >= 0, got {}",
946 b.exploration
947 )));
948 }
949 if !b.discount.is_finite() || b.discount <= 0.0 || b.discount > 1.0 {
950 return Err(Error::InvalidConfig(format!(
951 "bandit.discount must be in (0, 1], got {}",
952 b.discount
953 )));
954 }
955 }
956 if let Some([lo, hi]) = config.escalation.speculation_band {
957 let ok = |v: f64| v.is_finite() && (0.0..=1.0).contains(&v);
958 if !ok(lo) || !ok(hi) || lo > hi {
959 return Err(Error::InvalidConfig(format!(
960 "escalation.speculation_band must satisfy 0 <= low <= high <= 1, got [{lo}, {hi}]"
961 )));
962 }
963 }
964 if let Some(exp) = &config.escalation.exploration
965 && (!exp.epsilon.is_finite() || exp.epsilon <= 0.0 || exp.epsilon > 0.5)
966 {
967 return Err(Error::InvalidConfig(format!(
968 "escalation.exploration.epsilon must be finite and in (0, 0.5], got {}",
969 exp.epsilon
970 )));
971 }
972 if let Some(probe) = &config.escalation.probe {
973 if !(2..=8).contains(&probe.k) {
974 return Err(Error::InvalidConfig(format!(
975 "escalation.probe.k must be in [2, 8], got {}",
976 probe.k
977 )));
978 }
979 if !probe.sample_rate.is_finite() || !(0.0..=1.0).contains(&probe.sample_rate) {
980 return Err(Error::InvalidConfig(format!(
981 "escalation.probe.sample_rate must be finite and in [0, 1], got {}",
982 probe.sample_rate
983 )));
984 }
985 }
986 if let Some(pred) = &config.escalation.predictor {
987 if !pred.lr.is_finite() || !(0.0..=1.0).contains(&pred.lr) || pred.lr == 0.0 {
988 return Err(Error::InvalidConfig(format!(
989 "escalation.predictor.lr must be finite and in (0, 1], got {}",
990 pred.lr
991 )));
992 }
993 if !pred.l2.is_finite() || pred.l2 < 0.0 {
994 return Err(Error::InvalidConfig(format!(
995 "escalation.predictor.l2 must be finite and >= 0, got {}",
996 pred.l2
997 )));
998 }
999 }
1000 if let Some(elastic) = &config.escalation.elastic {
1001 if elastic.expensive_gates.is_empty() {
1002 return Err(Error::InvalidConfig(
1003 "escalation.elastic.expensive_gates must name at least one gate to skip".into(),
1004 ));
1005 }
1006 if !elastic.lambda.is_finite() || !(0.0..=1.0).contains(&elastic.lambda) {
1007 return Err(Error::InvalidConfig(format!(
1008 "escalation.elastic.lambda must be finite and in [0, 1], got {}",
1009 elastic.lambda
1010 )));
1011 }
1012 }
1013 Ok(config)
1014 }
1015
1016 #[must_use]
1018 pub fn route_for(&self, f: &Features) -> Option<&Route> {
1019 self.routes.iter().find(|r| r.match_.matches(f))
1020 }
1021
1022 #[must_use]
1024 pub fn price_table(&self) -> crate::cost::PriceTable {
1025 self.price_defs
1026 .iter()
1027 .fold(crate::cost::PriceTable::defaults(), |table, p| {
1028 table.with_override(
1029 p.model.clone(),
1030 crate::cost::ModelPrice {
1031 input_per_mtok: p.input_per_mtok,
1032 output_per_mtok: p.output_per_mtok,
1033 },
1034 )
1035 })
1036 }
1037
1038 fn validate_ladders_are_priced(&self) -> Result<()> {
1049 let prices = self.price_table();
1050 for (i, route) in self.routes.iter().enumerate() {
1051 for rung in &route.ladder {
1052 if prices.get(rung).is_none() {
1053 return Err(Error::InvalidConfig(format!(
1054 "route[{i}] ladder rung {rung:?} has no price, so its cost would be \
1055 recorded as $0.00 and any [budget] cap would never trip. Declare it:\n\n\
1056 [[price]]\nmodel = {rung:?}\ninput_per_mtok = 0.0\noutput_per_mtok = 0.0\n\n\
1057 (use the real per-1M-token prices; 0.0 is correct only for a model you \
1058 host yourself)"
1059 )));
1060 }
1061 }
1062 }
1063 Ok(())
1064 }
1065}
1066
1067#[cfg(test)]
1068mod tests {
1069 use super::*;
1070 use crate::features::Features;
1071
1072 const SPEC_CONFIG: &str = r#"
1073[[route]]
1074match = { agent = "claude-code", subagent = ["test-runner", "explore"] }
1075mode = "enforce"
1076ladder = ["anthropic/claude-haiku-4-5", "anthropic/claude-sonnet-5"]
1077gates = ["schema", "judge-diff"]
1078
1079[[route]]
1080match = { task_kind = "code_edit" }
1081mode = "enforce"
1082ladder = ["anthropic/claude-sonnet-5", "anthropic/claude-opus-4-8"]
1083gates = ["patch-applies", "lint-diff", "judge-diff"]
1084deferred_gates = ["compiles", "tests"]
1085
1086[[route]]
1087match = {}
1088mode = "observe"
1089ladder = ["anthropic/claude-opus-4-8"]
1090
1091[budget]
1092per_request_usd = 0.50
1093per_session_usd = 10.00
1094per_day_usd = 250.00
1095on_exhausted = "serve_best_attempt"
1096
1097[escalation]
1098max_rungs_per_request = 3
1099session_promotion = { after_failures = 3, window = "30m" }
1100"#;
1101
1102 #[test]
1103 fn parses_the_spec_example() {
1104 let c = Config::parse(SPEC_CONFIG).unwrap();
1105 assert_eq!(c.routes.len(), 3);
1106 assert_eq!(c.routes[0].mode, Mode::Enforce);
1107 assert_eq!(
1108 c.routes[0].ladder,
1109 ["anthropic/claude-haiku-4-5", "anthropic/claude-sonnet-5"]
1110 );
1111 assert_eq!(c.routes[1].deferred_gates, ["compiles", "tests"]);
1112 assert_eq!(c.budget.per_request_usd, Some(0.50));
1113 assert_eq!(c.budget.on_exhausted, OnExhausted::ServeBestAttempt);
1114 assert_eq!(c.escalation.max_rungs_per_request, 3);
1115 let sp = c.escalation.session_promotion.as_ref().unwrap();
1116 assert_eq!(sp.after_failures, 3);
1117 assert_eq!(sp.window_duration().unwrap(), Duration::from_secs(1800));
1118 }
1119
1120 #[test]
1121 fn first_matching_route_wins() {
1122 let c = Config::parse(SPEC_CONFIG).unwrap();
1123
1124 let mut f = Features::new(TaskKind::Explore);
1126 f.agent = Some("claude-code".into());
1127 f.subagent = Some("test-runner".into());
1128 let r = c.route_for(&f).unwrap();
1129 assert_eq!(r.ladder[0], "anthropic/claude-haiku-4-5");
1130
1131 let f2 = Features::new(TaskKind::CodeEdit);
1133 let r2 = c.route_for(&f2).unwrap();
1134 assert_eq!(r2.gates, ["patch-applies", "lint-diff", "judge-diff"]);
1135
1136 let f3 = Features::new(TaskKind::Chat);
1138 let r3 = c.route_for(&f3).unwrap();
1139 assert_eq!(r3.mode, Mode::Observe);
1140 }
1141
1142 #[test]
1143 fn shipped_example_config_parses() {
1144 let toml = include_str!("../../../firstpass.example.toml");
1147 let c = Config::parse(toml).expect("firstpass.example.toml must parse");
1148 assert_eq!(c.routes.len(), 3);
1149 assert_eq!(c.routes[0].mode, Mode::Enforce);
1150 }
1151
1152 #[test]
1153 fn parses_gate_definitions() {
1154 let toml = r#"
1155[[route]]
1156match = {}
1157mode = "enforce"
1158ladder = ["anthropic/claude-haiku-4-5"]
1159gates = ["my-tests"]
1160
1161[[gate]]
1162id = "my-tests"
1163cmd = ["pytest", "-q"]
1164
1165[[gate]]
1166id = "judge"
1167cmd = ["bash", "-c", "./judge.sh"]
1168timeout_ms = 60000
1169"#;
1170 let c = Config::parse(toml).unwrap();
1171 assert_eq!(c.gate_defs.len(), 2);
1172 assert_eq!(c.gate_defs[0].id, "my-tests");
1173 assert_eq!(c.gate_defs[0].cmd, ["pytest", "-q"]);
1174 assert_eq!(c.gate_defs[0].timeout_ms, 30_000, "default timeout applies");
1175 assert_eq!(c.gate_defs[1].timeout_ms, 60_000);
1176 }
1177
1178 #[test]
1179 fn rejects_invalid_gate_definitions() {
1180 let empty_cmd = "[[gate]]\nid = \"g\"\ncmd = []\n";
1181 assert!(matches!(
1182 Config::parse(empty_cmd),
1183 Err(Error::InvalidConfig(_))
1184 ));
1185
1186 let dup = "[[gate]]\nid = \"g\"\ncmd = [\"a\"]\n[[gate]]\nid = \"g\"\ncmd = [\"b\"]\n";
1187 assert!(matches!(Config::parse(dup), Err(Error::InvalidConfig(_))));
1188 }
1189
1190 #[test]
1191 fn parses_consistency_gate_definition() {
1192 let toml = r#"
1193[[gate]]
1194id = "uncertainty"
1195consistency = { model = "anthropic/claude-haiku-4-5", k = 5, threshold = 0.6 }
1196"#;
1197 let c = Config::parse(toml).unwrap();
1198 assert_eq!(c.gate_defs.len(), 1);
1199 let cons = c.gate_defs[0].consistency.as_ref().unwrap();
1200 assert_eq!(cons.model, "anthropic/claude-haiku-4-5");
1201 assert_eq!(cons.k, 5);
1202 assert!((cons.threshold - 0.6).abs() < 1e-9);
1203 }
1204
1205 #[test]
1206 fn consistency_k_defaults_to_3() {
1207 let toml = "[[gate]]\nid = \"u\"\nconsistency = { model = \"anthropic/claude-haiku-4-5\", threshold = 0.7 }\n";
1208 let c = Config::parse(toml).unwrap();
1209 assert_eq!(c.gate_defs[0].consistency.as_ref().unwrap().k, 3);
1210 }
1211
1212 #[test]
1213 fn rejects_exactly_one_of_violations_for_consistency() {
1214 let both = "[[gate]]\nid = \"g\"\ncmd = [\"x\"]\nconsistency = { model = \"a/b\", threshold = 0.5 }\n";
1216 assert!(matches!(Config::parse(both), Err(Error::InvalidConfig(_))));
1217
1218 let bad_k =
1220 "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", k = 1, threshold = 0.5 }\n";
1221 assert!(matches!(Config::parse(bad_k), Err(Error::InvalidConfig(_))));
1222
1223 let bad_k2 =
1224 "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", k = 9, threshold = 0.5 }\n";
1225 assert!(matches!(
1226 Config::parse(bad_k2),
1227 Err(Error::InvalidConfig(_))
1228 ));
1229
1230 let bad_thresh =
1232 "[[gate]]\nid = \"g\"\nconsistency = { model = \"a/b\", threshold = 1.1 }\n";
1233 assert!(matches!(
1234 Config::parse(bad_thresh),
1235 Err(Error::InvalidConfig(_))
1236 ));
1237 }
1238
1239 #[test]
1240 fn parses_adaptive_conformal_config() {
1241 let c = Config::parse("[escalation.adaptive]\nalpha = 0.1\n").unwrap();
1242 let a = c
1243 .escalation
1244 .adaptive
1245 .expect("[escalation.adaptive] should parse");
1246 assert!((a.alpha - 0.1).abs() < 1e-9);
1247 assert!((a.gamma - 0.02).abs() < 1e-9, "gamma defaults to 0.02");
1248 assert!(Config::parse("").unwrap().escalation.adaptive.is_none());
1250 }
1251
1252 #[test]
1253 fn parses_provider_entries_and_ladders_can_reference_them() {
1254 let c = Config::parse(
1255 r#"
1256[[provider]]
1257id = "groq"
1258dialect = "openai"
1259base_url = "https://api.groq.com/openai"
1260api_key_env = "GROQ_API_KEY"
1261
1262[[provider]]
1263id = "ollama"
1264dialect = "openai"
1265base_url = "http://localhost:11434"
1266
1267# A bring-your-own provider has no built-in price, so the ladder must declare one or the
1268# receipt would report $0.00 for every Groq call.
1269[[price]]
1270model = "groq/llama-3.3-70b-versatile"
1271input_per_mtok = 0.59
1272output_per_mtok = 0.79
1273
1274[[route]]
1275match = {}
1276mode = "enforce"
1277ladder = ["groq/llama-3.3-70b-versatile", "anthropic/claude-sonnet-5"]
1278"#,
1279 )
1280 .unwrap();
1281 assert_eq!(c.providers.len(), 2);
1282 let groq = &c.providers[0];
1283 assert_eq!(groq.id, "groq");
1284 assert_eq!(groq.dialect, Dialect::Openai);
1285 assert_eq!(groq.base_url, "https://api.groq.com/openai");
1286 assert_eq!(groq.api_key_env.as_deref(), Some("GROQ_API_KEY"));
1287 assert_eq!(c.providers[1].id, "ollama");
1289 assert!(c.providers[1].api_key_env.is_none());
1290 assert!(Config::parse("").unwrap().providers.is_empty());
1292 }
1293
1294 #[test]
1295 fn parses_aws_sigv4_provider_and_defaults_auth_to_api_key() {
1296 let c = Config::parse(
1297 r#"
1298[[provider]]
1299id = "bedrock"
1300dialect = "anthropic"
1301auth = "aws_sigv4"
1302region = "us-east-1"
1303"#,
1304 )
1305 .unwrap();
1306 let bedrock = &c.providers[0];
1307 assert_eq!(bedrock.auth, AuthScheme::AwsSigv4);
1308 assert_eq!(bedrock.region.as_deref(), Some("us-east-1"));
1309 assert!(bedrock.project.is_none());
1310
1311 let c2 = Config::parse(
1314 r#"
1315[[provider]]
1316id = "groq"
1317dialect = "openai"
1318base_url = "https://api.groq.com/openai"
1319"#,
1320 )
1321 .unwrap();
1322 assert_eq!(c2.providers[0].auth, AuthScheme::ApiKey);
1323 }
1324
1325 #[test]
1326 fn all_documented_provider_shapes_parse() {
1327 let c = Config::parse(
1331 r#"
1332[[provider]]
1333id = "groq"
1334dialect = "openai"
1335base_url = "https://api.groq.com/openai"
1336api_key_env = "GROQ_API_KEY"
1337
1338[[provider]]
1339id = "ollama"
1340dialect = "openai"
1341base_url = "http://localhost:11434"
1342
1343[[provider]]
1344id = "gemini"
1345dialect = "gemini"
1346base_url = "https://generativelanguage.googleapis.com"
1347api_key_env = "GEMINI_API_KEY"
1348
1349[[provider]]
1350id = "bedrock"
1351dialect = "anthropic"
1352auth = "aws_sigv4"
1353region = "us-east-1"
1354
1355[[provider]]
1356id = "vertex"
1357dialect = "anthropic"
1358auth = "gcp_oauth"
1359region = "us-east5"
1360project = "my-gcp-project"
1361"#,
1362 )
1363 .expect("every documented provider shape must parse");
1364 assert_eq!(c.providers.len(), 5);
1365
1366 let gemini = c.providers.iter().find(|p| p.id == "gemini").unwrap();
1367 assert_eq!(gemini.dialect, Dialect::Gemini);
1368 assert_eq!(gemini.auth, AuthScheme::ApiKey);
1369
1370 let vertex = c.providers.iter().find(|p| p.id == "vertex").unwrap();
1371 assert_eq!(vertex.auth, AuthScheme::GcpOauth);
1372 assert_eq!(vertex.region.as_deref(), Some("us-east5"));
1373 assert_eq!(vertex.project.as_deref(), Some("my-gcp-project"));
1374 }
1375
1376 #[test]
1377 fn empty_match_is_wildcard() {
1378 let m = Match::default();
1379 assert!(m.matches(&Features::new(TaskKind::Other)));
1380 }
1381
1382 #[test]
1383 fn subagent_list_membership() {
1384 let c = Config::parse(SPEC_CONFIG).unwrap();
1385 let route0 = &c.routes[0];
1386 let mut f = Features::new(TaskKind::Other);
1387 f.agent = Some("claude-code".into());
1388 f.subagent = Some("docs-writer".into()); assert!(!route0.match_.matches(&f));
1390 f.subagent = Some("explore".into());
1391 assert!(route0.match_.matches(&f));
1392 }
1393
1394 #[test]
1395 fn model_ref_parsing() {
1396 let m = ModelRef::parse("anthropic/claude-haiku-4-5").unwrap();
1397 assert_eq!(m.provider, "anthropic");
1398 assert_eq!(m.model, "claude-haiku-4-5");
1399 assert!(ModelRef::parse("no-slash").is_err());
1400 assert!(ModelRef::parse("/model").is_err());
1401 assert!(ModelRef::parse("a/b/c").is_err());
1402 }
1403
1404 #[test]
1405 fn window_parsing_units_and_errors() {
1406 assert_eq!(parse_window("90s").unwrap(), Duration::from_secs(90));
1407 assert_eq!(parse_window("30m").unwrap(), Duration::from_secs(1800));
1408 assert_eq!(parse_window("2h").unwrap(), Duration::from_secs(7200));
1409 assert_eq!(parse_window("1d").unwrap(), Duration::from_secs(86_400));
1410 assert!(parse_window("30x").is_err());
1411 assert!(parse_window("abc").is_err());
1412 }
1413
1414 #[test]
1415 fn empty_config_defaults() {
1416 let c = Config::parse("").unwrap();
1417 assert!(c.routes.is_empty());
1418 assert_eq!(c.escalation.max_rungs_per_request, 3);
1419 assert_eq!(c.budget.on_exhausted, OnExhausted::ServeBestAttempt);
1420 }
1421
1422 #[test]
1425 fn parses_exploration_config() {
1426 let c = Config::parse("[escalation.exploration]\nepsilon = 0.1\n").unwrap();
1427 let exp = c
1428 .escalation
1429 .exploration
1430 .expect("[escalation.exploration] should parse");
1431 assert!((exp.epsilon - 0.1).abs() < 1e-12);
1432 assert!(Config::parse("").unwrap().escalation.exploration.is_none());
1434 }
1435
1436 #[test]
1437 fn exploration_epsilon_boundary_valid() {
1438 let c = Config::parse("[escalation.exploration]\nepsilon = 0.5\n").unwrap();
1440 assert!((c.escalation.exploration.unwrap().epsilon - 0.5).abs() < 1e-12);
1441 }
1442
1443 #[test]
1444 fn exploration_epsilon_above_half_rejected() {
1445 let bad = "[escalation.exploration]\nepsilon = 0.51\n";
1446 assert!(
1447 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1448 "epsilon > 0.5 must be rejected"
1449 );
1450 }
1451
1452 #[test]
1453 fn exploration_epsilon_zero_rejected() {
1454 let bad = "[escalation.exploration]\nepsilon = 0.0\n";
1455 assert!(
1456 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1457 "epsilon = 0 must be rejected (must be strictly positive)"
1458 );
1459 }
1460
1461 #[test]
1462 fn exploration_epsilon_negative_rejected() {
1463 let bad = "[escalation.exploration]\nepsilon = -0.1\n";
1464 assert!(
1465 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1466 "epsilon < 0 must be rejected"
1467 );
1468 }
1469
1470 #[test]
1471 fn gate_def_schema_and_on_abstain_parse() {
1472 let toml = r#"
1473[[route]]
1474match = {}
1475mode = "enforce"
1476ladder = ["anthropic/claude-haiku-4-5"]
1477gates = ["extract-shape"]
1478
1479[[gate]]
1480id = "extract-shape"
1481schema = { type = "object", required = ["name"] }
1482on_abstain = "fail_closed"
1483"#;
1484 let config = Config::parse(toml).expect("schema gate def must parse");
1485 let def = &config.gate_defs[0];
1486 assert_eq!(def.id, "extract-shape");
1487 let schema = def.schema.as_ref().expect("schema captured");
1488 assert_eq!(schema["type"], "object");
1489 assert_eq!(def.on_abstain, AbstainPolicy::FailClosed);
1490 }
1491
1492 #[test]
1493 fn gate_def_on_abstain_defaults_fail_open() {
1494 let toml = r#"
1495[[route]]
1496match = {}
1497mode = "enforce"
1498ladder = ["anthropic/claude-haiku-4-5"]
1499
1500[[gate]]
1501id = "tests"
1502cmd = ["true"]
1503"#;
1504 let config = Config::parse(toml).expect("parse");
1505 assert_eq!(config.gate_defs[0].on_abstain, AbstainPolicy::FailOpen);
1506 }
1507
1508 #[test]
1509 fn gate_def_rejects_schema_plus_cmd() {
1510 let toml = r#"
1511[[route]]
1512match = {}
1513mode = "enforce"
1514ladder = ["anthropic/claude-haiku-4-5"]
1515
1516[[gate]]
1517id = "both"
1518cmd = ["true"]
1519schema = { type = "object" }
1520"#;
1521 let err = Config::parse(toml).unwrap_err();
1522 assert!(
1523 err.to_string().contains("exactly one"),
1524 "two kinds must be rejected: {err}"
1525 );
1526 }
1527
1528 #[test]
1529 fn price_overrides_parse_and_validate() {
1530 let toml = r#"
1531[[route]]
1532match = {}
1533mode = "observe"
1534ladder = ["anthropic/claude-haiku-4-5"]
1535
1536[[price]]
1537model = "anthropic/claude-haiku-4-5"
1538input_per_mtok = 0.8
1539output_per_mtok = 4.0
1540"#;
1541 let config = Config::parse(toml).expect("price override must parse");
1542 assert_eq!(config.price_defs[0].model, "anthropic/claude-haiku-4-5");
1543 assert!((config.price_defs[0].input_per_mtok - 0.8).abs() < 1e-12);
1544
1545 let bad = toml.replace("input_per_mtok = 0.8", "input_per_mtok = -1.0");
1546 assert!(Config::parse(&bad).is_err(), "negative price rejected");
1547 }
1548
1549 #[test]
1554 fn balanced_preset_is_strict_noop() {
1555 let p = RoutingMode::Balanced.preset();
1556 assert!(
1557 p.speculation.is_none(),
1558 "Balanced must not override speculation"
1559 );
1560 assert!(
1561 p.max_rungs_delta.is_none(),
1562 "Balanced must not override max_rungs"
1563 );
1564 assert!(!p.start_at_top, "Balanced must not set start_at_top");
1565 }
1566
1567 #[test]
1568 fn cost_preset_disables_speculation() {
1569 let p = RoutingMode::Cost.preset();
1570 assert_eq!(p.speculation, Some(0));
1571 assert!(p.max_rungs_delta.is_none());
1572 assert!(!p.start_at_top);
1573 }
1574
1575 #[test]
1576 fn quality_preset_bumps_max_rungs_and_disables_speculation() {
1577 let p = RoutingMode::Quality.preset();
1578 assert_eq!(p.max_rungs_delta, Some(1));
1579 assert_eq!(p.speculation, Some(0));
1580 assert!(!p.start_at_top);
1581 }
1582
1583 #[test]
1584 fn latency_preset_enables_speculation() {
1585 let p = RoutingMode::Latency.preset();
1586 assert_eq!(p.speculation, Some(1));
1587 assert!(p.max_rungs_delta.is_none());
1588 assert!(!p.start_at_top);
1589 }
1590
1591 #[test]
1592 fn max_preset_sets_start_at_top_and_disables_speculation() {
1593 let p = RoutingMode::Max.preset();
1594 assert!(p.start_at_top);
1595 assert_eq!(p.speculation, Some(0));
1596 assert!(p.max_rungs_delta.is_none());
1597 }
1598
1599 #[test]
1600 fn routing_mode_as_str_roundtrips() {
1601 for mode in RoutingMode::ALL {
1602 let s = mode.as_str();
1603 let back: RoutingMode = serde_json::from_str(&format!("\"{s}\"")).unwrap();
1604 assert_eq!(*mode, back, "as_str/serde roundtrip for {s}");
1605 }
1606 }
1607
1608 #[test]
1609 fn routing_mode_defaults_to_balanced() {
1610 assert_eq!(RoutingMode::default(), RoutingMode::Balanced);
1611 }
1612
1613 #[test]
1614 fn route_routing_mode_parses_and_defaults_to_none() {
1615 let no_mode = Config::parse(
1617 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n",
1618 )
1619 .unwrap();
1620 assert_eq!(no_mode.routes[0].routing_mode, None);
1621
1622 let with_mode = Config::parse(
1624 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\nrouting_mode = \"cost\"\n",
1625 )
1626 .unwrap();
1627 assert_eq!(with_mode.routes[0].routing_mode, Some(RoutingMode::Cost));
1628 }
1629
1630 #[test]
1631 fn all_routing_modes_have_non_empty_description_and_tradeoff() {
1632 for mode in RoutingMode::ALL {
1633 let p = mode.preset();
1634 assert!(
1635 !p.description.is_empty(),
1636 "mode {} has empty description",
1637 mode.as_str()
1638 );
1639 assert!(
1640 !p.tradeoff.is_empty(),
1641 "mode {} has empty tradeoff",
1642 mode.as_str()
1643 );
1644 }
1645 }
1646
1647 #[test]
1648 fn bandit_thompson_and_band_parse_and_validate() {
1649 let toml = r#"
1650[[route]]
1651match = {}
1652mode = "enforce"
1653ladder = ["anthropic/claude-haiku-4-5"]
1654
1655[escalation]
1656speculation = 1
1657speculation_band = [0.3, 0.7]
1658
1659[escalation.bandit]
1660algorithm = "thompson"
1661discount = 0.98
1662"#;
1663 let config = Config::parse(toml).expect("thompson + band must parse");
1664 let b = config.escalation.bandit.as_ref().unwrap();
1665 assert_eq!(b.algorithm, BanditAlgorithm::Thompson);
1666 assert!((b.discount - 0.98).abs() < 1e-12);
1667 assert_eq!(config.escalation.speculation_band, Some([0.3, 0.7]));
1668
1669 let plain = Config::parse(
1671 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.bandit]\n",
1672 )
1673 .unwrap();
1674 let b = plain.escalation.bandit.as_ref().unwrap();
1675 assert_eq!(b.algorithm, BanditAlgorithm::Ucb1);
1676 assert!((b.discount - 1.0).abs() < 1e-12);
1677
1678 assert!(Config::parse(&toml.replace("discount = 0.98", "discount = 0.0")).is_err());
1680 assert!(
1681 Config::parse(&toml.replace(
1682 "speculation_band = [0.3, 0.7]",
1683 "speculation_band = [0.9, 0.2]"
1684 ))
1685 .is_err()
1686 );
1687 }
1688
1689 #[test]
1692 fn probe_absent_defaults_to_none() {
1693 let c = Config::parse("").unwrap();
1695 assert!(c.escalation.probe.is_none());
1696 }
1697
1698 #[test]
1699 fn parses_valid_probe_config() {
1700 let c = Config::parse("[escalation.probe]\nk = 5\nsample_rate = 0.1\n").unwrap();
1701 let p = c.escalation.probe.expect("[escalation.probe] should parse");
1702 assert_eq!(p.k, 5);
1703 assert!((p.sample_rate - 0.1).abs() < 1e-12);
1704 }
1705
1706 #[test]
1707 fn probe_sample_rate_boundaries_accepted() {
1708 let c0 = Config::parse("[escalation.probe]\nk = 2\nsample_rate = 0.0\n").unwrap();
1710 assert!((c0.escalation.probe.unwrap().sample_rate - 0.0).abs() < 1e-12);
1711 let c1 = Config::parse("[escalation.probe]\nk = 8\nsample_rate = 1.0\n").unwrap();
1712 assert!((c1.escalation.probe.unwrap().sample_rate - 1.0).abs() < 1e-12);
1713 }
1714
1715 #[test]
1716 fn probe_rejects_k_below_2() {
1717 let bad = "[escalation.probe]\nk = 1\nsample_rate = 0.5\n";
1718 assert!(
1719 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1720 "k=1 must be rejected"
1721 );
1722 }
1723
1724 #[test]
1725 fn probe_rejects_k_above_8() {
1726 let bad = "[escalation.probe]\nk = 9\nsample_rate = 0.5\n";
1727 assert!(
1728 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1729 "k=9 must be rejected"
1730 );
1731 }
1732
1733 #[test]
1734 fn probe_rejects_sample_rate_above_1() {
1735 let bad = "[escalation.probe]\nk = 5\nsample_rate = 1.5\n";
1736 assert!(
1737 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1738 "sample_rate=1.5 must be rejected"
1739 );
1740 }
1741
1742 #[test]
1743 fn probe_rejects_negative_sample_rate() {
1744 let bad = "[escalation.probe]\nk = 5\nsample_rate = -0.1\n";
1745 assert!(
1746 matches!(Config::parse(bad), Err(Error::InvalidConfig(_))),
1747 "negative sample_rate must be rejected"
1748 );
1749 }
1750
1751 #[test]
1752 fn predictor_config_parses_and_validates() {
1753 let base = "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.predictor]\nlr = 0.05\nl2 = 0.001\n";
1754 let cfg = Config::parse(base).expect("valid predictor must parse");
1755 let pred = cfg.escalation.predictor.unwrap();
1756 assert!((pred.lr - 0.05).abs() < 1e-12 && (pred.l2 - 0.001).abs() < 1e-12);
1757 let d = Config::parse("[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n[escalation.predictor]\n").unwrap();
1759 assert!(d.escalation.predictor.is_some());
1760 assert!(Config::parse(&base.replace("lr = 0.05", "lr = 0.0")).is_err());
1762 assert!(Config::parse(&base.replace("lr = 0.05", "lr = 1.5")).is_err());
1763 assert!(Config::parse(&base.replace("l2 = 0.001", "l2 = -1.0")).is_err());
1764 }
1765
1766 #[test]
1771 fn unpriced_ladder_rung_is_rejected_and_an_explicit_price_fixes_it() {
1772 let unpriced =
1773 "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"ollama/qwen2.5-coder:7b\"]\n";
1774 let err = Config::parse(unpriced).expect_err("an unpriced rung must not parse");
1775 let msg = err.to_string();
1776 assert!(
1777 msg.contains("ollama/qwen2.5-coder:7b") && msg.contains("[[price]]"),
1778 "the error must name the rung and the fix, got: {msg}"
1779 );
1780
1781 let declared = format!(
1783 "[[price]]\nmodel = \"ollama/qwen2.5-coder:7b\"\ninput_per_mtok = 0.0\noutput_per_mtok = 0.0\n{unpriced}"
1784 );
1785 let cfg = Config::parse(&declared).expect("an explicit zero price is legal");
1786 assert_eq!(
1787 cfg.price_table()
1788 .get("ollama/qwen2.5-coder:7b")
1789 .unwrap()
1790 .input_per_mtok,
1791 0.0
1792 );
1793
1794 assert!(
1796 Config::parse("[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n").is_ok()
1797 );
1798 }
1799
1800 #[test]
1804 fn shadow_config_parses_and_validates() {
1805 let base = "[[route]]\nmatch = {}\nmode = \"observe\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n";
1806 let none = Config::parse(base).unwrap();
1807 assert!(
1808 none.routes[0].shadow.is_none(),
1809 "shadow must be off by default"
1810 );
1811
1812 let ok = Config::parse(&format!(
1813 "{base}[route.shadow]\nsample_rate = 0.25\nmax_usd_per_day = 5.0\n"
1814 ))
1815 .unwrap();
1816 let sh = ok.routes[0].shadow.expect("shadow parsed");
1817 assert!((sh.sample_rate - 0.25).abs() < f64::EPSILON);
1818 assert!((sh.max_usd_per_day - 5.0).abs() < f64::EPSILON);
1819
1820 for bad in [
1821 "sample_rate = 1.5\nmax_usd_per_day = 5.0",
1822 "sample_rate = -0.1\nmax_usd_per_day = 5.0",
1823 "sample_rate = 0.1\nmax_usd_per_day = -1.0",
1824 ] {
1825 assert!(
1826 Config::parse(&format!("{base}[route.shadow]\n{bad}\n")).is_err(),
1827 "invalid shadow config accepted: {bad}"
1828 );
1829 }
1830 }
1831
1832 #[test]
1834 fn rollout_config_parses_and_validates() {
1835 let base = "[[route]]\nmatch = {}\nmode = \"enforce\"\nladder = [\"anthropic/claude-haiku-4-5\"]\n";
1836 assert!(Config::parse(base).unwrap().routes[0].rollout.is_none());
1837 let ok = Config::parse(&format!(
1838 "{base}[route.rollout]\npercent = 5.0\nkey = \"session\"\n"
1839 ))
1840 .unwrap();
1841 assert!((ok.routes[0].rollout.unwrap().percent - 5.0).abs() < f64::EPSILON);
1842 assert!(Config::parse(&format!("{base}[route.rollout]\npercent = 140.0\n")).is_err());
1843 }
1844}