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