Skip to main content

switchyard_runner/
config.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Version-1 TOML deployment loading for the shared runner.
5
6use std::collections::{BTreeMap, BTreeSet, HashMap};
7use std::fs;
8use std::path::Path;
9use std::sync::Arc;
10use std::time::Duration;
11
12use libsy::{Algorithm, RuntimeModels};
13use parking_lot::Mutex;
14use serde::de::DeserializeOwned;
15use serde::{Deserialize, Deserializer};
16use serde_json::Value;
17use switchyard_llm_client::{
18    AuxiliaryOperation, Backend, ClientRouter, DEFAULT_MAX_RETRIES, HttpBackendConfig, ModelConfig,
19    OpenAiDecisionClient, ResponsesReasoningPolicy, SystemOneClient, TranslatingLlmClient,
20};
21use switchyard_protocol::{
22    LlmClientError, ModelId, RoutedDecisionClient, RoutedLlmClient, WireFormat,
23};
24
25use crate::algorithm_factory::AlgorithmAndModels;
26use crate::eligibility::{EligibilityPolicy, validate_labels};
27use crate::route::ExecutionLane;
28use crate::runner::ModelPropertiesProbe;
29use crate::{
30    AlgorithmFactory, AlgorithmSpec, AuxiliaryTarget, CallerAuthKind, DecisionTarget,
31    ModelCapabilities, Route, Runner, RunnerError,
32};
33
34const SUPPORTED_SCHEMA_VERSION: u32 = 1;
35const MAX_CONFIGURED_RETRIES: u32 = 10;
36
37/// This function returns a deployment's declared credential variable names without reading their values.
38/// It parses the deployment and checks its schema version before returning names from LLM and decision clients.
39pub fn api_key_variables(source: &str) -> Result<BTreeSet<String>, RunnerError> {
40    let config: DeploymentConfig = toml::from_str(source).map_err(|_| {
41        RunnerError::configuration(
42            "Could not parse the server config to read credential references.",
43        )
44    })?;
45    if config.schema_version != SUPPORTED_SCHEMA_VERSION {
46        return Err(RunnerError::configuration(
47            "Unsupported server config schema version.",
48        ));
49    }
50    let mut variables: BTreeSet<_> = config
51        .llm_clients
52        .values()
53        .filter_map(|client| client.api_key_env.clone())
54        .collect();
55    for client in config.decision_clients.values() {
56        variables.insert(client.api_key_env.clone());
57    }
58    if variables
59        .iter()
60        .any(|name| name.trim().is_empty() || name.contains(['\0', '=']))
61    {
62        return Err(RunnerError::configuration(
63            "Invalid credential environment variable name.",
64        ));
65    }
66    Ok(variables)
67}
68
69/// RouteTargets lists the targets one route calls, as the runner reads them from the server config.
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct RouteTargets {
72    /// This field names the route's table under `[routes]`.
73    pub name: String,
74    /// This field holds the public model ID that callers send.
75    pub id: ModelId,
76    /// This field holds the route's `type`, such as `stage_router`.
77    pub kind: &'static str,
78    /// This field lists the targets that answer requests, in algorithm order. It includes
79    /// targets that only delegated sub-agent work uses.
80    pub answer_targets: Vec<ConfiguredTarget>,
81    /// This field lists the targets the route calls only to decide, such as a judge or an advisor.
82    pub judge_targets: Vec<ConfiguredTarget>,
83}
84
85/// ConfiguredTarget names one target that a route uses.
86#[derive(Clone, Debug, PartialEq, Eq)]
87pub struct ConfiguredTarget {
88    pub name: String,
89    /// This field holds the client and model from the `[targets]` or `[decision_targets]`
90    /// entry with this name. It is `None` when no entry has the name; the server refuses to
91    /// start with such a config.
92    pub model: Option<TargetModel>,
93}
94
95/// TargetModel identifies the model a target sends requests to and the client that serves it.
96#[derive(Clone, Debug, PartialEq, Eq)]
97pub struct TargetModel {
98    pub client: String,
99    pub id: ModelId,
100}
101
102/// This function lists each route's targets without building clients or reading credentials.
103/// It returns the same parse error the server reports for a config that does not match the schema.
104pub fn route_targets(source: &str) -> Result<Vec<RouteTargets>, RunnerError> {
105    let config: DeploymentConfig = toml::from_str(source).map_err(|error| {
106        RunnerError::configuration_source(format!("failed to parse TOML: {error}"), error)
107    })?;
108    config.check_schema_version()?;
109    Ok(config
110        .routes
111        .iter()
112        .map(|(name, route)| RouteTargets {
113            name: name.clone(),
114            id: route.id.clone(),
115            kind: (&route.algorithm).into(),
116            answer_targets: config.configured_targets(route.routing_target_names()),
117            judge_targets: config.configured_targets(route.algorithm.judge_target_names()),
118        })
119        .collect())
120}
121
122type RunnerResult<T> = Result<T, RunnerError>;
123
124pub(crate) fn load_runner(path: impl AsRef<Path>) -> RunnerResult<Runner> {
125    let path = path.as_ref();
126    let source = fs::read_to_string(path).map_err(|error| {
127        RunnerError::configuration_source(
128            format!("failed to read server config {}: {error}", path.display()),
129            error,
130        )
131    })?;
132    runner_from_toml(&source).map_err(|error| {
133        RunnerError::configuration_source(
134            format!("invalid server config {}: {error}", path.display()),
135            error,
136        )
137    })
138}
139
140pub(crate) fn runner_from_toml(source: &str) -> RunnerResult<Runner> {
141    AlgorithmFactory::from_toml(source)?.config.build()
142}
143
144#[derive(Debug, Deserialize)]
145#[serde(deny_unknown_fields)]
146pub(crate) struct DeploymentConfig {
147    schema_version: u32,
148    fallback_client: Option<String>,
149    #[serde(default)]
150    llm_clients: BTreeMap<String, LlmClientConfig>,
151    targets: BTreeMap<String, TargetConfig>,
152    #[serde(default)]
153    decision_clients: BTreeMap<String, DecisionClientConfig>,
154    #[serde(default)]
155    decision_targets: BTreeMap<String, DecisionTargetConfig>,
156    routes: BTreeMap<String, RouteConfig>,
157}
158
159#[derive(Debug)]
160pub(crate) struct RouteConfig {
161    pub(crate) id: ModelId,
162    context_window: Option<u32>,
163    tool_calling: Option<bool>,
164    reasoning: Option<bool>,
165    vision: Option<bool>,
166    algorithm: AlgorithmSpec,
167    infra: Option<libsy::InfraPolicy>,
168    eligibility: Option<TargetEligibilityConfig>,
169}
170
171/// A route's algorithm and model groups with their source configuration.
172pub(crate) struct RouteSetup<'a> {
173    pub(crate) route_name: &'a str,
174    pub(crate) config: &'a RouteConfig,
175    pub(crate) algorithm: Arc<dyn Algorithm>,
176    pub(crate) models: RuntimeModels,
177}
178
179#[derive(Debug, Deserialize)]
180#[serde(deny_unknown_fields)]
181struct TargetEligibilityConfig {
182    #[serde(default)]
183    require_explicit_requirements: bool,
184    #[serde(default)]
185    target_alternatives: BTreeMap<String, Vec<String>>,
186    #[serde(default)]
187    scope: RequirementScope,
188}
189
190#[derive(Debug, Default, Deserialize)]
191#[serde(rename_all = "snake_case")]
192enum RequirementScope {
193    #[default]
194    Request,
195    Task,
196}
197
198struct TargetPromptPolicy {
199    prompts: HashMap<ModelId, String>,
200    routing_answer_target: Option<ModelId>,
201}
202
203// Algorithms keep their role names; calls use the selected target's name.
204struct ResolvedLlmTarget<'a> {
205    name: &'a str,
206    config: &'a TargetConfig,
207}
208
209type LaneTargets<'a> = BTreeMap<&'a str, ResolvedLlmTarget<'a>>;
210type TargetOverrides<'a> = BTreeMap<&'a str, &'a str>;
211type LaneDecisions<'a> = BTreeMap<&'a str, ResolvedDecisionTarget<'a>>;
212
213// Replacements bind logical names once; mappings never chain.
214fn bound_target<'a>(name: &'a str, overrides: &TargetOverrides<'a>) -> &'a str {
215    overrides.get(name).copied().unwrap_or(name)
216}
217
218fn callable_targets(algorithm: &AlgorithmSpec) -> BTreeSet<&str> {
219    algorithm.callable_target_names().into_iter().collect()
220}
221
222fn check_random_targets(
223    algorithm: &AlgorithmSpec,
224    targets: &LaneTargets<'_>,
225    has_overrides: bool,
226) -> RunnerResult<()> {
227    if matches!(algorithm, AlgorithmSpec::Random { .. }) && has_overrides {
228        let mut models = BTreeSet::new();
229        for name in algorithm.routing_target_names() {
230            let target = targets[name].name;
231            if !models.insert(target) {
232                return Err(LlmClientError::InvalidRequest {
233                    message: format!(
234                        "random route alternatives map multiple pool entries to target {target}; use distinct targets"
235                    ),
236                }
237                .into());
238            }
239        }
240    }
241    Ok(())
242}
243
244// Routing uses target names; telemetry uses provider IDs.
245fn build_resolved_algorithm<'a>(
246    route_name: &str,
247    algorithm: &AlgorithmSpec,
248    targets: &LaneTargets<'_>,
249    decisions: impl Iterator<Item = (&'a str, &'a ModelId)>,
250) -> RunnerResult<AlgorithmAndModels> {
251    let model_ids = targets
252        .iter()
253        .map(|(name, target)| ((*name).to_owned(), ModelId::from(target.name)))
254        .chain(decisions.map(|(name, model)| (name.to_owned(), model.clone())))
255        .collect();
256    let (algorithm, models) = algorithm
257        .build_with_runtime_models(route_name, &model_ids)
258        .map_err(|error| RunnerError::configuration_source(error.to_string(), error))?;
259    let provider_models = targets
260        .values()
261        .map(|target| (ModelId::from(target.name), target.config.id.clone()))
262        .collect();
263    Ok((algorithm, models.with_provider_models(provider_models)))
264}
265
266pub(crate) type TargetBindings = Vec<(String, String)>;
267pub(crate) const MAX_ELIGIBLE_LANES: usize = 128;
268
269// Cache by resolved targets, so equivalent requirements reuse algorithm-owned state.
270pub(crate) struct EligibleLanes {
271    deployment: Arc<DeploymentConfig>,
272    route_name: String,
273    clients: Arc<BTreeMap<String, Arc<TranslatingLlmClient>>>,
274    decision_clients: Arc<BTreeMap<String, Arc<dyn RoutedDecisionClient>>>,
275    lanes: Mutex<BTreeMap<TargetBindings, Arc<ExecutionLane>>>,
276}
277
278impl EligibleLanes {
279    pub(crate) fn select(
280        &self,
281        requirements: &BTreeSet<String>,
282        standard: &Arc<ExecutionLane>,
283    ) -> RunnerResult<Arc<ExecutionLane>> {
284        let Some(key) = self
285            .deployment
286            .select_eligible_targets(&self.route_name, requirements)?
287        else {
288            return Ok(Arc::clone(standard));
289        };
290        let mut lanes = self.lanes.lock();
291        if let Some(lane) = lanes.get(&key) {
292            return Ok(Arc::clone(lane));
293        }
294        if lanes.len() >= MAX_ELIGIBLE_LANES {
295            return Err(LlmClientError::TemporarilyUnavailable.into());
296        }
297        let algorithm = self
298            .deployment
299            .bound_algorithm_spec(&self.route_name, &key)?;
300        let overrides = key
301            .iter()
302            .map(|(name, target)| (name.as_str(), target.as_str()))
303            .collect();
304        let targets = self
305            .deployment
306            .resolve_lane_targets(&algorithm, &overrides)?;
307        check_random_targets(
308            &algorithm,
309            &targets,
310            key.iter().any(|(name, target)| name != target),
311        )?;
312        let decisions = self.deployment.resolve_decision_targets(
313            &self.route_name,
314            &algorithm,
315            &overrides,
316            &self.decision_clients,
317        )?;
318        // Construction is synchronous; no model I/O or await occurs under this lock.
319        let (mut lane, _) = self.deployment.build_lane(
320            &self.route_name,
321            &algorithm,
322            &targets,
323            &decisions,
324            &self.clients,
325            None,
326        )?;
327        lane.inherit_pricing(standard);
328        let lane = Arc::new(lane);
329        lanes.insert(key, Arc::clone(&lane));
330        Ok(lane)
331    }
332}
333
334struct DecisionTargetMapping<'a> {
335    target_name: &'a str,
336    model_id: &'a ModelId,
337}
338
339#[derive(Clone, Copy)]
340struct ResolvedDecisionTarget<'a> {
341    model: &'a ModelId,
342    client: &'a Arc<dyn RoutedDecisionClient>,
343}
344
345impl<'de> Deserialize<'de> for RouteConfig {
346    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
347    where
348        D: Deserializer<'de>,
349    {
350        let mut table = toml::Table::deserialize(deserializer)?;
351        let id = take_required(&mut table, "id")?;
352        let context_window = take_optional(&mut table, "context_window")?;
353        let tool_calling = take_optional(&mut table, "tool_calling")?;
354        let reasoning = take_optional(&mut table, "reasoning")?;
355        let vision = take_optional(&mut table, "vision")?;
356        let infra = take_optional(&mut table, "infra")?;
357        let eligibility = take_optional(&mut table, "eligibility")?;
358        let algorithm = AlgorithmSpec::deserialize(toml::Value::Table(table))
359            .map_err(serde::de::Error::custom)?;
360        Ok(Self {
361            id,
362            context_window,
363            tool_calling,
364            reasoning,
365            vision,
366            algorithm,
367            infra,
368            eligibility,
369        })
370    }
371}
372
373fn take_required<T, E>(table: &mut toml::Table, name: &'static str) -> Result<T, E>
374where
375    T: DeserializeOwned,
376    E: serde::de::Error,
377{
378    let value = table.remove(name).ok_or_else(|| E::missing_field(name))?;
379    T::deserialize(value).map_err(E::custom)
380}
381
382fn take_optional<T, E>(table: &mut toml::Table, name: &'static str) -> Result<Option<T>, E>
383where
384    T: DeserializeOwned,
385    E: serde::de::Error,
386{
387    table
388        .remove(name)
389        .map(|value| T::deserialize(value).map_err(E::custom))
390        .transpose()
391}
392
393impl RouteConfig {
394    fn capabilities(&self) -> ModelCapabilities {
395        ModelCapabilities {
396            context_window: self.context_window,
397            tool_calling: self.tool_calling,
398            reasoning: self.reasoning,
399            vision: self.vision,
400        }
401    }
402
403    fn routing_target_names(&self) -> Vec<&str> {
404        self.algorithm.routing_target_names()
405    }
406
407    fn callable_target_names(&self) -> Vec<&str> {
408        self.algorithm.callable_target_names()
409    }
410}
411
412impl DeploymentConfig {
413    /// Judges called through a decision target use the default decision settings
414    /// when the route omits a `decision` table.
415    pub(crate) fn infer_decision_judges(&mut self) {
416        for route in self.routes.values_mut() {
417            route
418                .algorithm
419                .infer_decision_judges(|name| self.decision_targets.contains_key(name));
420        }
421    }
422
423    pub(crate) fn requires_target_admission(&self) -> bool {
424        self.routes
425            .values()
426            .any(|route| route.eligibility.is_some())
427    }
428
429    pub(crate) fn eligibility_policy(&self, route_name: &str) -> Option<EligibilityPolicy> {
430        let config = self.routes.get(route_name)?.eligibility.as_ref()?;
431        Some(EligibilityPolicy::new(
432            config.require_explicit_requirements,
433            matches!(config.scope, RequirementScope::Task),
434        ))
435    }
436
437    pub(crate) fn route_target_models(
438        &self,
439        route_name: &str,
440    ) -> RunnerResult<BTreeMap<ModelId, TargetModel>> {
441        let route = self
442            .routes
443            .get(route_name)
444            .ok_or_else(|| RunnerError::configuration(format!("unknown route {route_name}")))?;
445        route
446            .callable_target_names()
447            .into_iter()
448            .chain(
449                route
450                    .eligibility
451                    .iter()
452                    .flat_map(|config| config.target_alternatives.values().flatten())
453                    .map(String::as_str),
454            )
455            .map(|name| {
456                if let Some(target) = self.decision_targets.get(name) {
457                    Ok((
458                        target.id.clone(),
459                        TargetModel {
460                            client: target.decision_client.clone(),
461                            id: target.id.clone(),
462                        },
463                    ))
464                } else {
465                    let target = self.targets.get(name).ok_or_else(|| {
466                        RunnerError::configuration(format!(
467                            "route {route_name} references unknown target {name}"
468                        ))
469                    })?;
470                    Ok((
471                        ModelId::from(name),
472                        TargetModel {
473                            client: target.llm_client.clone(),
474                            id: target.id.clone(),
475                        },
476                    ))
477                }
478            })
479            .collect()
480    }
481
482    /// None keeps the standard setup; Some contains eligible target mappings.
483    /// An empty selection never falls back to standard targets.
484    pub(crate) fn select_eligible_targets(
485        &self,
486        route_name: &str,
487        requirements: &BTreeSet<String>,
488    ) -> RunnerResult<Option<TargetBindings>> {
489        let route = self
490            .routes
491            .get(route_name)
492            .ok_or_else(|| RunnerError::configuration(format!("unknown route {route_name}")))?;
493        let config = route
494            .eligibility
495            .as_ref()
496            .ok_or_else(|| RunnerError::configuration("route has no eligibility configuration"))?;
497        let callable = callable_targets(&route.algorithm);
498        let bindings: Vec<_> = callable
499            .iter()
500            .filter_map(|name| {
501                std::iter::once(*name)
502                    .chain(
503                        config
504                            .target_alternatives
505                            .get(*name)
506                            .into_iter()
507                            .flatten()
508                            .map(String::as_str),
509                    )
510                    .find(|target| {
511                        self.target_labels(target)
512                            .is_some_and(|labels| requirements.is_subset(labels))
513                    })
514                    .map(|target| (*name, target))
515            })
516            .collect();
517        if bindings.len() == callable.len() && bindings.iter().all(|(name, target)| name == target)
518        {
519            return Ok(None);
520        }
521        Ok(Some(
522            bindings
523                .into_iter()
524                .map(|(name, target)| (name.to_owned(), target.to_owned()))
525                .collect(),
526        ))
527    }
528
529    fn bound_algorithm_spec(
530        &self,
531        route_name: &str,
532        bindings: &TargetBindings,
533    ) -> RunnerResult<AlgorithmSpec> {
534        let route = self
535            .routes
536            .get(route_name)
537            .ok_or_else(|| RunnerError::configuration(format!("unknown route {route_name}")))?;
538        let allowed = bindings.iter().map(|(name, _)| name.as_str()).collect();
539        route.algorithm.restricted_to(&allowed).map_err(|error| {
540            LlmClientError::InvalidRequest {
541                message: error.to_string(),
542            }
543            .into()
544        })
545    }
546
547    pub(crate) fn build_bound_algorithm(
548        &self,
549        route_name: &str,
550        bindings: &TargetBindings,
551    ) -> RunnerResult<AlgorithmAndModels> {
552        let algorithm = self.bound_algorithm_spec(route_name, bindings)?;
553        let overrides = bindings
554            .iter()
555            .map(|(name, target)| (name.as_str(), target.as_str()))
556            .collect();
557        let targets = self.resolve_lane_targets(&algorithm, &overrides)?;
558        check_random_targets(
559            &algorithm,
560            &targets,
561            bindings.iter().any(|(name, target)| name != target),
562        )?;
563        let decisions = self
564            .resolve_decision_models(route_name, &algorithm, &overrides)?
565            .into_iter()
566            .map(|mapping| (mapping.target_name, mapping.model_id));
567        let (algorithm, models) =
568            build_resolved_algorithm(route_name, &algorithm, &targets, decisions)?;
569        Ok((algorithm, models.with_target_restriction()))
570    }
571
572    fn resolve_decision_models<'a>(
573        &'a self,
574        route_name: &str,
575        algorithm: &'a AlgorithmSpec,
576        overrides: &TargetOverrides<'_>,
577    ) -> RunnerResult<Vec<DecisionTargetMapping<'a>>> {
578        algorithm
579            .decision_target_names()
580            .into_iter()
581            .map(|name| {
582                let bound = bound_target(name, overrides);
583                let target = self.decision_targets.get(bound).ok_or_else(|| {
584                    RunnerError::configuration(format!(
585                        "route {route_name} requires unknown decision target {bound}"
586                    ))
587                })?;
588                Ok(DecisionTargetMapping {
589                    target_name: name,
590                    model_id: &target.id,
591                })
592            })
593            .collect()
594    }
595
596    // Host-owned Decision calls identify the model, not the selected target or client.
597    pub(crate) fn validate_decision_models(&self, route_name: &str) -> RunnerResult<()> {
598        let route = self
599            .routes
600            .get(route_name)
601            .ok_or_else(|| RunnerError::configuration(format!("unknown route {route_name}")))?;
602        let mut clients = HashMap::new();
603        for name in route.algorithm.decision_target_names() {
604            let alternatives = route
605                .eligibility
606                .as_ref()
607                .and_then(|config| config.target_alternatives.get(name));
608            for candidate in
609                std::iter::once(name).chain(alternatives.into_iter().flatten().map(String::as_str))
610            {
611                let target = self.decision_targets.get(candidate).ok_or_else(|| {
612                    RunnerError::configuration(format!(
613                        "route {route_name} requires unknown decision target {candidate}"
614                    ))
615                })?;
616                if clients
617                    .insert(&target.id, &target.decision_client)
618                    .is_some_and(|client| client != &target.decision_client)
619                {
620                    return Err(RunnerError::configuration(format!(
621                        "route {route_name} maps decision model {} to different clients",
622                        target.id
623                    )));
624                }
625            }
626        }
627        Ok(())
628    }
629
630    fn target_labels(&self, name: &str) -> Option<&BTreeSet<String>> {
631        self.targets
632            .get(name)
633            .map(|target| &target.labels)
634            .or_else(|| self.decision_targets.get(name).map(|target| &target.labels))
635    }
636
637    fn check_schema_version(&self) -> RunnerResult<()> {
638        if self.schema_version == SUPPORTED_SCHEMA_VERSION {
639            return Ok(());
640        }
641        Err(RunnerError::configuration(format!(
642            "unsupported schema_version {}; expected {SUPPORTED_SCHEMA_VERSION}",
643            self.schema_version
644        )))
645    }
646
647    /// This function looks up each name in `[targets]`, then in `[decision_targets]`. The server
648    /// rejects a name defined in both, so the lookup order does not change the result.
649    fn configured_targets(&self, names: Vec<&str>) -> Vec<ConfiguredTarget> {
650        names
651            .into_iter()
652            .map(|name| ConfiguredTarget {
653                name: name.to_string(),
654                model: self
655                    .targets
656                    .get(name)
657                    .map(|target| (&target.llm_client, &target.id))
658                    .or_else(|| {
659                        self.decision_targets
660                            .get(name)
661                            .map(|target| (&target.decision_client, &target.id))
662                    })
663                    .map(|(client, id)| TargetModel {
664                        client: client.clone(),
665                        id: id.clone(),
666                    }),
667            })
668            .collect()
669    }
670
671    fn decision_target(&self, name: &str) -> Option<DecisionTarget> {
672        let target = self.targets.get(name)?;
673        let client = self.llm_clients.get(&target.llm_client)?;
674        Some(DecisionTarget {
675            target: name.to_string(),
676            model: target.id.clone(),
677            format: client.format.wire_format(),
678            base_url: client.base_url.as_str().to_string(),
679            extra_body: target.extra_body.clone(),
680            reasoning_effort: target.reasoning_effort.clone(),
681        })
682    }
683
684    /// Checks route identity and target references without constructing clients.
685    pub(crate) fn validate(&self) -> RunnerResult<()> {
686        self.check_schema_version()?;
687
688        let mut route_names_by_id = HashMap::new();
689        for (route_name, config) in &self.routes {
690            validate_value("route name", route_name)?;
691            validate_value(&format!("route {route_name} id"), &config.id)?;
692            if let Some(first_route_name) =
693                route_names_by_id.insert(config.id.as_str(), route_name.as_str())
694            {
695                return Err(RunnerError::configuration(format!(
696                    "routes {first_route_name} and {route_name} both use id {}; route ids must be unique",
697                    config.id
698                )));
699            }
700        }
701
702        for (name, target) in &self.targets {
703            validate_labels(&target.labels)
704                .map_err(|error| RunnerError::configuration(error.to_string()))?;
705            validate_value("target name", name)?;
706            validate_value(&format!("target {name} id"), &target.id)?;
707            if !self.llm_clients.contains_key(&target.llm_client) {
708                return Err(RunnerError::configuration(format!(
709                    "target {name} references unknown llm client {}",
710                    target.llm_client
711                )));
712            }
713        }
714        let mut decision_approvals = HashMap::new();
715        for (name, target) in &self.decision_targets {
716            validate_labels(&target.labels)
717                .map_err(|error| RunnerError::configuration(error.to_string()))?;
718            if decision_approvals
719                .insert((&target.decision_client, &target.id), &target.labels)
720                .is_some_and(|approved| approved != &target.labels)
721            {
722                return Err(RunnerError::configuration(format!(
723                    "decision target {name} shares a model and client with an alias but disagrees on approval labels"
724                )));
725            }
726            validate_value("decision target name", name)?;
727            validate_value(&format!("decision target {name} id"), &target.id)?;
728            if self.targets.contains_key(name) {
729                return Err(RunnerError::configuration(format!(
730                    "target {name} is defined as both an LLM and decision target"
731                )));
732            }
733            // Algorithms route LLM targets by name and decision targets by id.
734            if self.targets.contains_key(target.id.as_str()) {
735                return Err(RunnerError::configuration(format!(
736                    "decision target {name} id {} is also an LLM target name; rename one of them",
737                    target.id
738                )));
739            }
740            if !self.decision_clients.contains_key(&target.decision_client) {
741                return Err(RunnerError::configuration(format!(
742                    "decision target {name} references unknown decision client {}",
743                    target.decision_client
744                )));
745            }
746        }
747        for (route_name, config) in &self.routes {
748            if let Some(eligibility) = &config.eligibility {
749                self.validate_eligibility(route_name, &config.algorithm, eligibility)?;
750            }
751        }
752        Ok(())
753    }
754
755    /// Resolves each route once; native and host-owned execution share this path.
756    pub(crate) fn build_algorithms(&self) -> impl Iterator<Item = RunnerResult<RouteSetup<'_>>> {
757        let targets = self.build_targets();
758        self.routes.iter().map(move |(route_name, config)| {
759            let decision_targets = config.algorithm.decision_target_names();
760            for name in config.callable_target_names() {
761                let (exists, kind) = if decision_targets.contains(&name) {
762                    (self.decision_targets.contains_key(name), "decision")
763                } else {
764                    (self.targets.contains_key(name), "LLM")
765                };
766                if !exists {
767                    return Err(RunnerError::configuration(format!(
768                        "route references unknown target {name}; route {route_name} requires target kind {kind}"
769                    )));
770                }
771            }
772            for name in config.routing_target_names() {
773                if !self.targets.contains_key(name) {
774                    return Err(RunnerError::configuration(format!(
775                        "route {route_name} completion target {name} must be an LLM target"
776                    )));
777                }
778            }
779            if config.context_window == Some(0) {
780                return Err(RunnerError::configuration(format!(
781                    "route {route_name} context_window must be greater than zero"
782                )));
783            }
784            let (algorithm, models) = config
785                .algorithm
786                .build_with_runtime_models(route_name, &targets)
787                .map_err(|error| RunnerError::configuration_source(error.to_string(), error))?;
788            let models = models.with_provider_models(
789                config
790                    .callable_target_names()
791                    .into_iter()
792                    .filter_map(|name| {
793                        self.targets
794                            .get(name)
795                            .map(|target| (ModelId::from(name), target.id.clone()))
796                    })
797                    .collect(),
798            );
799            if let Some(infra) = &config.infra {
800                if !matches!(&config.algorithm, AlgorithmSpec::LlmClassifier { config }
801                    if matches!(config.mode, None | Some(crate::ClassifierMode::Capability))
802                        && config.escalation.is_none())
803                {
804                    return Err(RunnerError::configuration(format!(
805                        "route {route_name}: infra requires capability llm_classifier without escalation"
806                    )));
807                }
808                infra.validate().map_err(|error| {
809                    RunnerError::configuration_source(format!("route {route_name}: {error}"), error)
810                })?;
811            }
812            Ok(RouteSetup {
813                route_name: route_name.as_str(),
814                config,
815                algorithm,
816                models,
817            })
818        })
819    }
820
821    pub(crate) fn validate_target_approvals(&self) -> RunnerResult<()> {
822        let mut approvals = HashMap::new();
823        for (target_name, target) in &self.targets {
824            if let Some((first_name, labels)) = approvals.insert(
825                (&target.llm_client, &target.id),
826                (target_name, &target.labels),
827            ) && labels != &target.labels
828            {
829                return Err(RunnerError::configuration(format!(
830                    "targets {first_name} and {target_name} share a model and llm client but disagree on approval labels"
831                )));
832            }
833        }
834        Ok(())
835    }
836
837    fn build(self: Arc<Self>) -> RunnerResult<Runner> {
838        self.validate()?;
839        self.validate_target_approvals()?;
840
841        let mut provider_api_keys = Vec::new();
842        let clients = Arc::new(self.build_clients(&mut provider_api_keys)?);
843        let decision_clients = Arc::new(self.build_decision_clients(&mut provider_api_keys)?);
844        let fallback_base_url = self.fallback_base_url()?;
845        let mut routes = Vec::with_capacity(self.routes.len());
846        let mut model_properties_probes = BTreeMap::new();
847        for entry in self.build_algorithms() {
848            let RouteSetup {
849                route_name,
850                config,
851                algorithm,
852                models,
853            } = entry?;
854            let capabilities = config.capabilities();
855            if let AlgorithmSpec::Vgr { config: vgr } = &config.algorithm
856                && let Some(probe) =
857                    self.build_model_properties_probe(&vgr.efficient_target, &clients)
858            {
859                model_properties_probes.insert(config.id.clone(), probe);
860            }
861            let no_overrides = TargetOverrides::new();
862            let standard_targets = self.resolve_lane_targets(&config.algorithm, &no_overrides)?;
863            let decisions = self.resolve_decision_targets(
864                route_name,
865                &config.algorithm,
866                &no_overrides,
867                &decision_clients,
868            )?;
869            let (standard, caller_auth) = self.build_lane(
870                route_name,
871                &config.algorithm,
872                &standard_targets,
873                &decisions,
874                &clients,
875                Some((algorithm, models)),
876            )?;
877            // Judges are included so a judge answer maps to its provider model too.
878            let mut target_names = callable_targets(&config.algorithm);
879            if let Some(eligibility) = &config.eligibility {
880                target_names.extend(
881                    eligibility
882                        .target_alternatives
883                        .values()
884                        .flatten()
885                        .map(String::as_str),
886                );
887            }
888            let route_targets = target_names
889                .into_iter()
890                .filter_map(|name| self.decision_target(name))
891                .collect();
892            let mut route = Route::from_lane(standard, caller_auth, capabilities, route_targets)
893                .with_infra(config.infra.clone());
894            if let Some(eligibility) = &config.eligibility {
895                let policy = EligibilityPolicy::new(
896                    eligibility.require_explicit_requirements,
897                    matches!(eligibility.scope, RequirementScope::Task),
898                );
899                route = route.with_eligibility(
900                    policy,
901                    EligibleLanes {
902                        deployment: Arc::clone(&self),
903                        route_name: route_name.to_owned(),
904                        clients: Arc::clone(&clients),
905                        decision_clients: Arc::clone(&decision_clients),
906                        lanes: Mutex::new(BTreeMap::new()),
907                    },
908                );
909            }
910            routes.push((config.id.clone(), route));
911        }
912        let runner = Runner::new(routes)
913            .with_fallback_url(fallback_base_url)
914            .with_provider_api_keys(provider_api_keys)
915            .with_model_properties_probes(model_properties_probes);
916        Ok(runner)
917    }
918
919    // Alternatives preserve the router's existing roles and never chain.
920    fn validate_eligibility(
921        &self,
922        route_name: &str,
923        algorithm: &AlgorithmSpec,
924        config: &TargetEligibilityConfig,
925    ) -> RunnerResult<()> {
926        if !algorithm.supports_target_restrictions() {
927            return Err(RunnerError::configuration(format!(
928                "route {route_name} cannot use eligibility with prefill_router"
929            )));
930        }
931        let callable = callable_targets(algorithm);
932        for (source, alternatives) in &config.target_alternatives {
933            if !callable.contains(source.as_str()) {
934                return Err(RunnerError::configuration(format!(
935                    "route {route_name} target_alternatives source {source} is not used by the algorithm"
936                )));
937            }
938            if alternatives.is_empty() {
939                return Err(RunnerError::configuration(
940                    "target alternatives must not be empty",
941                ));
942            }
943            for target in alternatives {
944                let same_kind = (self.targets.contains_key(source)
945                    && self.targets.contains_key(target))
946                    || (self.decision_targets.contains_key(source)
947                        && self.decision_targets.contains_key(target));
948                if !same_kind {
949                    return Err(RunnerError::configuration(format!(
950                        "route {route_name} alternative {target} must exist and match the target kind of {source}"
951                    )));
952                }
953            }
954        }
955        for name in callable.into_iter().chain(
956            config
957                .target_alternatives
958                .values()
959                .flatten()
960                .map(String::as_str),
961        ) {
962            if let Some(target) = self.targets.get(name)
963                && self
964                    .llm_clients
965                    .get(&target.llm_client)
966                    .is_some_and(|client| client.forward_auth)
967            {
968                return Err(RunnerError::configuration(format!(
969                    "route {route_name} cannot use eligibility with forwarded caller authentication"
970                )));
971            }
972        }
973        Ok(())
974    }
975
976    fn resolve_lane_targets<'a>(
977        &'a self,
978        algorithm: &'a AlgorithmSpec,
979        overrides: &TargetOverrides<'_>,
980    ) -> RunnerResult<LaneTargets<'a>> {
981        let decisions = algorithm.decision_target_names();
982        callable_targets(algorithm)
983            .into_iter()
984            .filter(|name| !decisions.contains(name))
985            .map(|name| {
986                let bound = bound_target(name, overrides);
987                let (resolved_name, config) =
988                    self.targets.get_key_value(bound).ok_or_else(|| {
989                        RunnerError::configuration(format!(
990                            "route references unknown target {bound}"
991                        ))
992                    })?;
993                Ok((
994                    name,
995                    ResolvedLlmTarget {
996                        name: resolved_name.as_str(),
997                        config,
998                    },
999                ))
1000            })
1001            .collect()
1002    }
1003
1004    fn resolve_decision_targets<'a>(
1005        &'a self,
1006        route_name: &str,
1007        algorithm: &'a AlgorithmSpec,
1008        overrides: &TargetOverrides<'_>,
1009        clients: &'a BTreeMap<String, Arc<dyn RoutedDecisionClient>>,
1010    ) -> RunnerResult<LaneDecisions<'a>> {
1011        algorithm
1012            .decision_target_names()
1013            .into_iter()
1014            .map(|name| {
1015                let bound = bound_target(name, overrides);
1016                let target = self.decision_targets.get(bound).ok_or_else(|| {
1017                    RunnerError::configuration(format!(
1018                        "route {route_name} requires unknown decision target {bound}"
1019                    ))
1020                })?;
1021                let client = clients.get(&target.decision_client).ok_or_else(|| {
1022                    RunnerError::configuration(format!(
1023                        "decision target {bound} references unknown decision client {}",
1024                        target.decision_client
1025                    ))
1026                })?;
1027                Ok((
1028                    name,
1029                    ResolvedDecisionTarget {
1030                        model: &target.id,
1031                        client,
1032                    },
1033                ))
1034            })
1035            .collect()
1036    }
1037
1038    fn build_lane(
1039        &self,
1040        route_name: &str,
1041        route: &AlgorithmSpec,
1042        targets: &LaneTargets<'_>,
1043        decisions: &LaneDecisions<'_>,
1044        clients: &BTreeMap<String, Arc<TranslatingLlmClient>>,
1045        built: Option<AlgorithmAndModels>,
1046    ) -> RunnerResult<(ExecutionLane, Option<CallerAuthKind>)> {
1047        let (algorithm, mut models) = if let Some(built) = built {
1048            built
1049        } else {
1050            build_resolved_algorithm(
1051                route_name,
1052                route,
1053                targets,
1054                decisions.iter().map(|(name, target)| (*name, target.model)),
1055            )?
1056        };
1057        let (route_clients, caller_auth) =
1058            self.build_route_clients(route_name, route, targets, decisions, clients)?;
1059        let anthropic_auxiliary_target =
1060            self.build_anthropic_auxiliary_target(route, targets, clients);
1061        let responses_auxiliary_target =
1062            self.build_responses_auxiliary_target(route, targets, clients);
1063        if self
1064            .routes
1065            .get(route_name)
1066            .is_some_and(|config| config.eligibility.is_some())
1067        {
1068            models = models.with_target_restriction();
1069        }
1070        Ok((
1071            ExecutionLane::new(
1072                algorithm,
1073                route_clients,
1074                anthropic_auxiliary_target,
1075                responses_auxiliary_target,
1076                models,
1077            ),
1078            caller_auth,
1079        ))
1080    }
1081
1082    fn build_clients(
1083        &self,
1084        provider_api_keys: &mut Vec<String>,
1085    ) -> RunnerResult<BTreeMap<String, Arc<TranslatingLlmClient>>> {
1086        let mut models_by_client = self
1087            .llm_clients
1088            .keys()
1089            .map(|name| (name.clone(), Vec::new()))
1090            .collect::<BTreeMap<String, Vec<ModelConfig>>>();
1091
1092        for (name, client_config) in &self.llm_clients {
1093            validate_value("llm client name", name)?;
1094            if client_config.responses_reasoning.is_some()
1095                && !matches!(client_config.format, ClientFormat::OpenAiResponses)
1096            {
1097                return Err(RunnerError::configuration(format!(
1098                    "llm client {name} responses_reasoning is only valid for openai_responses"
1099                )));
1100            }
1101            let backend = build_backend(
1102                name,
1103                client_config,
1104                &BTreeMap::new(),
1105                &BTreeSet::new(),
1106                None,
1107            )?;
1108            let (Backend::OpenAiChat(config)
1109            | Backend::OpenAiResponses(config)
1110            | Backend::Anthropic(config)) = backend;
1111            if let Some(key) = config.api_key {
1112                provider_api_keys.push(key);
1113            }
1114        }
1115        for (target_name, target) in &self.targets {
1116            let client_config = self.llm_clients.get(&target.llm_client).ok_or_else(|| {
1117                RunnerError::configuration(format!(
1118                    "target {target_name} references unknown llm client {}",
1119                    target.llm_client
1120                ))
1121            })?;
1122            let model_configs = models_by_client
1123                .get_mut(&target.llm_client)
1124                .ok_or_else(|| {
1125                    RunnerError::configuration("validated llm client was not initialized")
1126                })?;
1127            if let Some(effort) = &target.reasoning_effort {
1128                if effort.trim().is_empty() {
1129                    return Err(RunnerError::configuration(format!(
1130                        "target {target_name} reasoning_effort must not be empty"
1131                    )));
1132                }
1133                // Anthropic rejects any other value with a 400 on every request.
1134                if matches!(client_config.format, ClientFormat::AnthropicMessages)
1135                    && !ANTHROPIC_EFFORTS.contains(&effort.as_str())
1136                {
1137                    return Err(RunnerError::configuration(format!(
1138                        "target {target_name} reasoning_effort {effort:?} is not an anthropic_messages effort; use one of {}",
1139                        ANTHROPIC_EFFORTS.join(", ")
1140                    )));
1141                }
1142            }
1143            model_configs.push(
1144                ModelConfig::new(
1145                    target_name.as_str(),
1146                    build_backend(
1147                        &target.llm_client,
1148                        client_config,
1149                        &target.extra_body,
1150                        &target.omit_body_fields,
1151                        target.reasoning_effort.clone(),
1152                    )?,
1153                    None,
1154                )
1155                .with_responses_reasoning(client_config.responses_reasoning.unwrap_or_default())
1156                .with_provider_model(target.id.clone()),
1157            );
1158        }
1159
1160        let mut clients = BTreeMap::new();
1161        for (name, model_configs) in models_by_client {
1162            let mut client = TranslatingLlmClient::new(&model_configs)
1163                .map_err(|error| RunnerError::configuration(error.to_string()))?;
1164            if !self.llm_clients[&name].fallback_on_rate_limit {
1165                client = client.without_rate_limit_cooldown();
1166            }
1167            clients.insert(name, Arc::new(client));
1168        }
1169        Ok(clients)
1170    }
1171
1172    fn build_decision_clients(
1173        &self,
1174        provider_api_keys: &mut Vec<String>,
1175    ) -> RunnerResult<BTreeMap<String, Arc<dyn RoutedDecisionClient>>> {
1176        self.decision_clients
1177            .iter()
1178            .map(|(name, config)| {
1179                validate_value("decision client name", name)?;
1180                let DecisionClientConfig {
1181                    format,
1182                    endpoint,
1183                    api_key_env,
1184                    timeout_ms,
1185                } = config;
1186                if *timeout_ms == 0 {
1187                    return Err(RunnerError::configuration(format!(
1188                        "decision client {name} timeout_ms must be at least 1"
1189                    )));
1190                }
1191                let api_key = read_api_key(&format!("decision client {name}"), api_key_env)?;
1192                let timeout = Duration::from_millis(*timeout_ms);
1193                let client = match format {
1194                    DecisionFormat::SystemOne => {
1195                        SystemOneClient::new(endpoint.0.clone(), api_key.clone(), timeout)
1196                            .map(|client| Arc::new(client) as Arc<dyn RoutedDecisionClient>)
1197                    }
1198                    DecisionFormat::OpenaiDecisions => {
1199                        OpenAiDecisionClient::new(endpoint.0.clone(), api_key.clone(), timeout)
1200                            .map(|client| Arc::new(client) as Arc<dyn RoutedDecisionClient>)
1201                    }
1202                }
1203                .map_err(|error| RunnerError::configuration(error.to_string()))?;
1204                provider_api_keys.push(api_key);
1205                Ok((name.clone(), client))
1206            })
1207            .collect()
1208    }
1209
1210    /// Algorithms route on LLM target names, so targets that share a provider model keep
1211    /// their own settings. The LLM client sends each target's `id` upstream. Decision targets
1212    /// route on their `id`, which the decision client sends as is.
1213    fn build_targets(&self) -> BTreeMap<String, ModelId> {
1214        self.targets
1215            .keys()
1216            .map(|name| (name.clone(), ModelId::from(name.as_str())))
1217            .chain(
1218                self.decision_targets
1219                    .iter()
1220                    .map(|(name, config)| (name.clone(), config.id.clone())),
1221            )
1222            .collect()
1223    }
1224
1225    /// Builds the client router for one route. The second value is the caller credential family
1226    /// that the route's forwarding clients need, or `None` when no client forwards the caller's
1227    /// credential. A request through the other family's APIs fails before any upstream call.
1228    fn build_route_clients(
1229        &self,
1230        route_name: &str,
1231        route: &AlgorithmSpec,
1232        targets: &LaneTargets<'_>,
1233        decisions: &LaneDecisions<'_>,
1234        clients: &BTreeMap<String, Arc<TranslatingLlmClient>>,
1235    ) -> RunnerResult<(ClientRouter, Option<CallerAuthKind>)> {
1236        let TargetPromptPolicy {
1237            prompts,
1238            routing_answer_target,
1239        } = self.build_route_target_prompts(route_name, route, targets)?;
1240        let mut by_model = HashMap::new();
1241        let mut caller_auth = None;
1242        let mut has_mixed_families = false;
1243        let mut forwarding_origins = BTreeSet::new();
1244        let mut decisions_by_model = HashMap::new();
1245        for name in route.callable_target_names() {
1246            if let Some(target) = decisions.get(name) {
1247                if let Some(previous) =
1248                    decisions_by_model.insert(target.model.clone(), Arc::clone(target.client))
1249                    && !Arc::ptr_eq(&previous, target.client)
1250                {
1251                    return Err(RunnerError::configuration(format!(
1252                        "route {route_name} maps decision model {} to different clients",
1253                        target.model
1254                    )));
1255                }
1256                continue;
1257            }
1258            let target = targets.get(name).ok_or_else(|| {
1259                RunnerError::configuration(format!("route references unknown target {name}"))
1260            })?;
1261            let client = clients.get(&target.config.llm_client).ok_or_else(|| {
1262                RunnerError::configuration(format!("target {name} has no constructed llm client"))
1263            })?;
1264            let client_config =
1265                self.llm_clients
1266                    .get(&target.config.llm_client)
1267                    .ok_or_else(|| {
1268                        RunnerError::configuration(format!(
1269                            "target {name} references unknown llm client {}",
1270                            target.config.llm_client
1271                        ))
1272                    })?;
1273            if client_config.forward_auth {
1274                let target_auth = client_config.format.caller_auth_kind();
1275                has_mixed_families |= caller_auth.is_some_and(|kind| kind != target_auth);
1276                caller_auth = Some(target_auth);
1277                forwarding_origins.insert(client_config.base_url.0.origin().ascii_serialization());
1278            }
1279            let client: Arc<dyn RoutedLlmClient> = client.clone();
1280            by_model.insert(ModelId::from(target.name), client);
1281        }
1282        // Only forwarding clients count: an api_key_env client sends the server's own key.
1283        // Forwarding clients must share one credential family unless they all use the same
1284        // scheme, host, and port, such as one LLM gateway that accepts the caller's gateway key
1285        // on every endpoint. Such a route serves Chat Completions and Responses callers because
1286        // Anthropic clients forward the caller's `authorization` header unchanged.
1287        if has_mixed_families {
1288            if forwarding_origins.len() > 1 {
1289                let origins = Vec::from_iter(forwarding_origins).join(", ");
1290                return Err(RunnerError::configuration(format!(
1291                    "route {route_name} cannot forward both Anthropic and OpenAI caller credentials to different origins ({origins}); point all of its forwarding clients at one origin (same scheme, host, and port), such as an LLM gateway, or set api_key_env instead of forward_auth on one provider's clients"
1292                )));
1293            }
1294            caller_auth = Some(CallerAuthKind::OpenAi);
1295        }
1296        let completion_targets = route
1297            .routing_target_names()
1298            .into_iter()
1299            .map(|name| ModelId::from(targets[name].name))
1300            .collect::<Vec<_>>();
1301        let router = ClientRouter::new_with_decision_clients(
1302            by_model,
1303            decisions_by_model,
1304            prompts,
1305            routing_answer_target,
1306            &completion_targets,
1307        )
1308        .without_rate_limit_fallback(
1309            route
1310                .routing_target_names()
1311                .into_iter()
1312                .filter_map(|name| {
1313                    let target = &targets[name];
1314                    (!self.llm_clients[&target.config.llm_client].fallback_on_rate_limit)
1315                        .then(|| ModelId::from(target.name))
1316                })
1317                .collect(),
1318        );
1319        Ok((router, caller_auth))
1320    }
1321
1322    /// Builds the effective prompt policy for this route's completion targets.
1323    fn build_route_target_prompts(
1324        &self,
1325        route_name: &str,
1326        route: &AlgorithmSpec,
1327        targets: &LaneTargets<'_>,
1328    ) -> RunnerResult<TargetPromptPolicy> {
1329        let mut prompts = HashMap::new();
1330        for name in route.routing_target_names() {
1331            let target = targets.get(name).ok_or_else(|| {
1332                RunnerError::configuration(format!("route references unknown target {name}"))
1333            })?;
1334            if let Some(prompt) = &target.config.system_prompt {
1335                prompts.insert(ModelId::from(target.name), prompt.clone());
1336            }
1337        }
1338        let mut policy = TargetPromptPolicy {
1339            prompts,
1340            routing_answer_target: None,
1341        };
1342        let Some((response_name, dependency_name)) = route.routing_response_and_dependency() else {
1343            return Ok(policy);
1344        };
1345        let response = &targets[response_name];
1346        if !policy.prompts.contains_key(response.name) {
1347            return Ok(policy);
1348        }
1349        if std::iter::once(dependency_name)
1350            .chain(route.judge_target_names())
1351            .any(|name| {
1352                targets
1353                    .get(name)
1354                    .is_some_and(|dependency| dependency.name == response.name)
1355            })
1356        {
1357            return Err(RunnerError::configuration(format!(
1358                "route {route_name} cannot apply system_prompt to target {response_name}: it is also the routing-only target"
1359            )));
1360        }
1361        policy.routing_answer_target = Some(ModelId::from(response.name));
1362        Ok(policy)
1363    }
1364
1365    fn fallback_base_url(&self) -> RunnerResult<Option<String>> {
1366        let Some(name) = &self.fallback_client else {
1367            return Ok(None);
1368        };
1369        let config = self.llm_clients.get(name).ok_or_else(|| {
1370            RunnerError::configuration(format!(
1371                "fallback_client references unknown llm client {name}"
1372            ))
1373        })?;
1374        Ok(Some(config.base_url.as_str().to_string()))
1375    }
1376
1377    fn build_model_properties_probe(
1378        &self,
1379        efficient_target_name: &str,
1380        clients: &BTreeMap<String, Arc<TranslatingLlmClient>>,
1381    ) -> Option<ModelPropertiesProbe> {
1382        let efficient_target = self.targets.get(efficient_target_name)?;
1383        let client_config = self.llm_clients.get(&efficient_target.llm_client)?;
1384        if !matches!(
1385            client_config.context_discovery,
1386            Some(ContextDiscovery::LlamaCpp)
1387        ) {
1388            return None;
1389        }
1390        let client = clients.get(&efficient_target.llm_client)?;
1391        Some(ModelPropertiesProbe {
1392            model: ModelId::from(efficient_target_name),
1393            format: client_config.format.wire_format(),
1394            client: Arc::clone(client),
1395        })
1396    }
1397
1398    fn build_anthropic_auxiliary_target(
1399        &self,
1400        route: &AlgorithmSpec,
1401        targets: &LaneTargets<'_>,
1402        clients: &BTreeMap<String, Arc<TranslatingLlmClient>>,
1403    ) -> Option<AuxiliaryTarget> {
1404        route
1405            .routing_target_names()
1406            .into_iter()
1407            .enumerate()
1408            .filter_map(|(index, name)| {
1409                let config = targets.get(name)?;
1410                let target = self.build_auxiliary_target(
1411                    config.name,
1412                    config.config,
1413                    clients,
1414                    AuxiliaryOperation::AnthropicCountTokens,
1415                )?;
1416                Some((
1417                    count_tokens_priority(config.name, &config.config.id),
1418                    index,
1419                    target,
1420                ))
1421            })
1422            .min_by_key(|(priority, index, _)| (*priority, *index))
1423            .map(|(_, _, target)| target)
1424    }
1425
1426    fn build_responses_auxiliary_target(
1427        &self,
1428        route: &AlgorithmSpec,
1429        targets: &LaneTargets<'_>,
1430        clients: &BTreeMap<String, Arc<TranslatingLlmClient>>,
1431    ) -> Option<AuxiliaryTarget> {
1432        route.routing_target_names().into_iter().find_map(|name| {
1433            let target = targets.get(name)?;
1434            self.build_auxiliary_target(
1435                target.name,
1436                target.config,
1437                clients,
1438                AuxiliaryOperation::ResponsesInputTokens,
1439            )
1440        })
1441    }
1442
1443    fn build_auxiliary_target(
1444        &self,
1445        name: &str,
1446        target: &TargetConfig,
1447        clients: &BTreeMap<String, Arc<TranslatingLlmClient>>,
1448        operation: AuxiliaryOperation,
1449    ) -> Option<AuxiliaryTarget> {
1450        let client = clients.get(&target.llm_client)?;
1451        let model = ModelId::from(name);
1452        client
1453            .supports_auxiliary(&model, operation)
1454            .then(|| AuxiliaryTarget {
1455                model,
1456                client: client.clone(),
1457            })
1458    }
1459}
1460
1461/// Values Anthropic accepts for `output_config.effort`.
1462const ANTHROPIC_EFFORTS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"];
1463
1464fn count_tokens_priority(target_name: &str, model_id: &ModelId) -> usize {
1465    let target_name = target_name.to_ascii_lowercase();
1466    let model_id = model_id.to_ascii_lowercase();
1467    ["opus", "sonnet", "haiku"]
1468        .iter()
1469        .position(|hint| target_name.contains(hint) || model_id.contains(hint))
1470        .unwrap_or(3)
1471}
1472
1473/// A client endpoint, parsed when the config loads rather than checked afterwards.
1474///
1475/// Holding a `HttpBaseUrl` is proof the value is an absolute HTTP(S) URL, so no
1476/// later stage has to re-check it or can forget to.
1477#[derive(Clone, Debug)]
1478struct HttpBaseUrl(reqwest::Url);
1479
1480impl HttpBaseUrl {
1481    fn as_str(&self) -> &str {
1482        self.0.as_str()
1483    }
1484}
1485
1486impl<'de> Deserialize<'de> for HttpBaseUrl {
1487    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1488    where
1489        D: serde::Deserializer<'de>,
1490    {
1491        let raw = String::deserialize(deserializer)?;
1492        let url = reqwest::Url::parse(raw.trim()).map_err(|error| {
1493            serde::de::Error::custom(format!("base_url must be an absolute HTTP(S) URL: {error}"))
1494        })?;
1495        if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
1496            return Err(serde::de::Error::custom(
1497                "base_url must be an absolute HTTP(S) URL",
1498            ));
1499        }
1500        Ok(Self(url))
1501    }
1502}
1503
1504#[derive(Debug, Deserialize)]
1505#[serde(deny_unknown_fields)]
1506struct LlmClientConfig {
1507    format: ClientFormat,
1508    base_url: HttpBaseUrl,
1509    /// Opt-in context discovery for VGR's efficient target. Unset disables discovery.
1510    context_discovery: Option<ContextDiscovery>,
1511    api_key_env: Option<String>,
1512    #[serde(default)]
1513    forward_auth: bool,
1514    #[serde(default)]
1515    extra_headers: BTreeMap<String, String>,
1516    #[serde(default = "default_max_retries")]
1517    max_retries: u32,
1518    #[serde(default = "default_fallback_on_rate_limit")]
1519    fallback_on_rate_limit: bool,
1520    /// Cooldown after an exhausted transient completion failure. Defaults to 5 seconds; zero disables it.
1521    #[serde(default = "default_failure_cooldown_ms")]
1522    failure_cooldown_ms: u64,
1523    /// Deadline in milliseconds for all attempts and the complete response. Unset is unbounded.
1524    timeout_ms: Option<u64>,
1525    responses_reasoning: Option<ResponsesReasoningPolicy>,
1526}
1527
1528#[derive(Debug, Deserialize)]
1529#[serde(rename_all = "snake_case")]
1530enum ContextDiscovery {
1531    LlamaCpp,
1532}
1533
1534#[derive(Debug, Deserialize)]
1535#[serde(deny_unknown_fields)]
1536struct DecisionClientConfig {
1537    format: DecisionFormat,
1538    endpoint: HttpBaseUrl,
1539    api_key_env: String,
1540    timeout_ms: u64,
1541}
1542
1543#[derive(Debug, Deserialize)]
1544#[serde(rename_all = "snake_case")]
1545enum DecisionFormat {
1546    SystemOne,
1547    OpenaiDecisions,
1548}
1549
1550#[derive(Debug, Deserialize)]
1551#[serde(deny_unknown_fields)]
1552struct DecisionTargetConfig {
1553    #[serde(default)]
1554    labels: BTreeSet<String>,
1555    id: ModelId,
1556    decision_client: String,
1557}
1558
1559#[derive(Debug, Deserialize)]
1560#[serde(deny_unknown_fields)]
1561struct TargetConfig {
1562    #[serde(default)]
1563    labels: BTreeSet<String>,
1564    id: ModelId,
1565    llm_client: String,
1566    #[serde(default)]
1567    extra_body: BTreeMap<String, Value>,
1568    /// Top-level request fields dropped from the outbound body before `extra_body` is merged.
1569    /// For providers that reject an otherwise standard field.
1570    #[serde(default)]
1571    omit_body_fields: BTreeSet<String>,
1572    system_prompt: Option<String>,
1573    /// Reasoning effort forced on every request to this target, replacing the caller's value.
1574    reasoning_effort: Option<String>,
1575}
1576
1577#[derive(Clone, Copy, Debug, Deserialize)]
1578enum ClientFormat {
1579    #[serde(rename = "openai_chat")]
1580    OpenAiChat,
1581    #[serde(rename = "openai_responses")]
1582    OpenAiResponses,
1583    #[serde(rename = "anthropic_messages")]
1584    AnthropicMessages,
1585}
1586
1587impl ClientFormat {
1588    const fn wire_format(self) -> WireFormat {
1589        match self {
1590            Self::OpenAiChat => WireFormat::OpenAiChat,
1591            Self::OpenAiResponses => WireFormat::OpenAiResponses,
1592            Self::AnthropicMessages => WireFormat::AnthropicMessages,
1593        }
1594    }
1595
1596    const fn caller_auth_kind(self) -> CallerAuthKind {
1597        match self {
1598            Self::AnthropicMessages => CallerAuthKind::Anthropic,
1599            Self::OpenAiChat | Self::OpenAiResponses => CallerAuthKind::OpenAi,
1600        }
1601    }
1602}
1603
1604fn build_backend(
1605    client_name: &str,
1606    config: &LlmClientConfig,
1607    extra_body: &BTreeMap<String, Value>,
1608    omit_body_fields: &BTreeSet<String>,
1609    reasoning_effort: Option<String>,
1610) -> RunnerResult<Backend> {
1611    if config.max_retries > MAX_CONFIGURED_RETRIES {
1612        return Err(RunnerError::configuration(format!(
1613            "llm client {client_name} max_retries must be at most {MAX_CONFIGURED_RETRIES}"
1614        )));
1615    }
1616    if config.timeout_ms == Some(0) {
1617        return Err(RunnerError::configuration(format!(
1618            "llm client {client_name} timeout_ms must be at least 1"
1619        )));
1620    }
1621    if config.forward_auth && config.api_key_env.is_some() {
1622        return Err(RunnerError::configuration(format!(
1623            "llm client {client_name} cannot set both forward_auth and api_key_env"
1624        )));
1625    }
1626    let api_key = config
1627        .api_key_env
1628        .as_deref()
1629        .map(|variable| read_api_key(&format!("llm client {client_name}"), variable))
1630        .transpose()?;
1631    let http = HttpBackendConfig {
1632        base_url: config.base_url.as_str().to_string(),
1633        api_key,
1634        forward_auth: config.forward_auth,
1635        extra_headers: config.extra_headers.clone(),
1636        extra_body: extra_body.clone(),
1637        omit_body_fields: omit_body_fields.clone(),
1638        reasoning_effort,
1639        max_retries: config.max_retries,
1640        failure_cooldown: Duration::from_millis(config.failure_cooldown_ms),
1641        timeout: config.timeout_ms.map(Duration::from_millis),
1642    };
1643    let backend = match config.format {
1644        ClientFormat::OpenAiChat => Backend::OpenAiChat(http),
1645        ClientFormat::OpenAiResponses => Backend::OpenAiResponses(http),
1646        ClientFormat::AnthropicMessages => Backend::Anthropic(http),
1647    };
1648    Ok(backend)
1649}
1650
1651fn read_api_key(client: &str, variable: &str) -> RunnerResult<String> {
1652    if variable.trim().is_empty() {
1653        return Err(RunnerError::configuration(format!(
1654            "{client} api_key_env must not be empty"
1655        )));
1656    }
1657    // A name with `=` is often a pasted `NAME=key` line, so this error omits the name.
1658    if variable.contains(['\0', '=']) {
1659        return Err(RunnerError::configuration(format!(
1660            "{client} api_key_env must not contain '=' or NUL"
1661        )));
1662    }
1663    let api_key = std::env::var(variable).map_err(|error| {
1664        // VarError can contain the raw credential, so errors report only its category.
1665        let reason = match error {
1666            std::env::VarError::NotPresent => "environment variable not found",
1667            std::env::VarError::NotUnicode(_) => "environment variable is not valid Unicode",
1668        };
1669        RunnerError::configuration(format!(
1670            "{client} could not read api_key_env {variable}: {reason}"
1671        ))
1672    })?;
1673    if api_key.trim().is_empty() {
1674        return Err(RunnerError::configuration(format!(
1675            "{client} api_key_env {variable} is empty"
1676        )));
1677    }
1678    Ok(api_key)
1679}
1680
1681// A function so that serde default can use it.
1682const fn default_max_retries() -> u32 {
1683    DEFAULT_MAX_RETRIES
1684}
1685
1686const fn default_fallback_on_rate_limit() -> bool {
1687    true
1688}
1689
1690const fn default_failure_cooldown_ms() -> u64 {
1691    5000
1692}
1693
1694fn validate_value(label: &str, value: &str) -> RunnerResult<()> {
1695    if value.trim().is_empty() || value.trim() != value {
1696        return Err(RunnerError::configuration(format!(
1697            "{label} must be non-empty and have no surrounding whitespace"
1698        )));
1699    }
1700    Ok(())
1701}
1702
1703#[cfg(test)]
1704mod tests {
1705    use super::*;
1706
1707    #[test]
1708    fn route_presentation_fields_are_split_from_the_algorithm() {
1709        let route: RouteConfig = toml::from_str(
1710            r#"
1711type = "random"
1712id = "switchyard/random"
1713context_window = 128000
1714tool_calling = true
1715reasoning = false
1716targets = ["fast", "strong"]
1717weights = [1.0, 2.0]
1718seed = 7
1719"#,
1720        )
1721        .expect("route should deserialize");
1722
1723        assert_eq!(route.id, "switchyard/random");
1724        assert_eq!(route.context_window, Some(128_000));
1725        assert_eq!(route.tool_calling, Some(true));
1726        assert_eq!(route.reasoning, Some(false));
1727        assert_eq!(route.algorithm.routing_target_names(), ["fast", "strong"]);
1728    }
1729
1730    #[test]
1731    fn route_algorithm_unknown_fields_are_rejected() {
1732        let error = toml::from_str::<RouteConfig>(
1733            r#"
1734type = "passthrough"
1735id = "switchyard/fast"
1736target = "fast"
1737bogus = true
1738"#,
1739        )
1740        .expect_err("unknown route keys must be rejected");
1741
1742        assert!(error.to_string().contains("bogus"), "{error}");
1743    }
1744
1745    #[test]
1746    fn deployment_errors_keep_one_path_context() {
1747        let path = Path::new("/definitely/missing/switchyard-routes.toml");
1748        let error = match load_runner(path) {
1749            Ok(_) => panic!("missing config should fail"),
1750            Err(error) => error,
1751        };
1752        let message = error.to_string();
1753
1754        assert_eq!(message.matches(&path.display().to_string()).count(), 1);
1755        assert!(message.starts_with("failed to read server config"));
1756    }
1757}
1758#[cfg(test)]
1759mod deployment_tests {
1760    use super::*;
1761    use crate::require_target_labels;
1762    use serde_json::json;
1763    use switchyard_protocol::{Category, Request};
1764
1765    const VALID_CONFIG: &str = r#"
1766schema_version = 1
1767
1768[llm_clients.primary]
1769format = "openai_chat"
1770base_url = "https://example.test/v1"
1771
1772[llm_clients.responses]
1773format = "openai_responses"
1774base_url = "https://example.test/v1"
1775
1776[llm_clients.anthropic]
1777format = "anthropic_messages"
1778base_url = "https://example.test"
1779
1780[targets.classifier]
1781id = "classifier/model"
1782llm_client = "primary"
1783
1784[targets.strong]
1785id = "strong/model"
1786llm_client = "responses"
1787
1788[targets.weak]
1789id = "weak/model"
1790llm_client = "anthropic"
1791
1792[routes.noop]
1793id = "switchyard/noop"
1794type = "noop"
1795
1796[routes.random]
1797id = "switchyard/random"
1798type = "random"
1799targets = ["strong", "weak"]
1800
1801[routes.classifier]
1802id = "switchyard/classifier"
1803type = "llm_classifier"
1804classifier_target = "classifier"
1805strong_target = "strong"
1806weak_target = "weak"
1807base_threshold = 0.5
1808
1809[routes.passthrough]
1810id = "switchyard/passthrough"
1811type = "passthrough"
1812target = "weak"
1813
1814[routes.plan_execute]
1815id = "switchyard/plan-execute"
1816type = "stage_router"
1817capable_target = "strong"
1818efficient_target = "weak"
1819picker = "capable_first"
1820confidence_threshold = 0.0
1821efficient_hold_turns = -1
1822capable_system_prompt = "Inspect the task and plan before modifying files."
1823"#;
1824
1825    fn decision_eligibility_config() -> String {
1826        let config = VALID_CONFIG
1827            .replace(
1828                "id = \"strong/model\"",
1829                "id = \"strong/model\"\nlabels = ['private']",
1830            )
1831            .replace(
1832                "id = \"weak/model\"",
1833                "id = \"weak/model\"\nlabels = ['private']",
1834            );
1835        format!(
1836            r#"{config}
1837
1838[decision_clients.privacy]
1839format = "system_one"
1840endpoint = "https://example.test/v1/systemone"
1841api_key_env = "PATH"
1842timeout_ms = 5000
1843
1844[decision_targets.standard]
1845id = "decision/standard"
1846decision_client = "privacy"
1847labels = ["private"]
1848
1849[routes.typed]
1850id = "switchyard/typed"
1851type = "llm_classifier"
1852mode = "capability"
1853classifier_target = "standard"
1854strong_target = "strong"
1855weak_target = "weak"
1856
1857[routes.typed.decision]
1858cutoff = 0.4
1859
1860[routes.typed.eligibility]
1861"#
1862        )
1863    }
1864
1865    fn eligible_pool_config() -> String {
1866        let config = VALID_CONFIG
1867            .replace("id = \"strong/model\"", "id = \"strong/model\"\nlabels = ['private']")
1868            .replace(
1869                "type = \"passthrough\"\ntarget = \"weak\"",
1870                "type = \"random\"\ntargets = [\"weak\", \"strong\"]\nweights = [3.0, 1.0]\nseed = 7",
1871            );
1872        format!(
1873            r#"{config}
1874
1875[routes.passthrough.eligibility]
1876"#
1877        )
1878    }
1879
1880    #[tokio::test]
1881    async fn eligibility_requires_approved_roles_and_decision_targets() -> RunnerResult<()> {
1882        let configured = decision_eligibility_config();
1883        let runner = Runner::from_toml(&configured)?;
1884        let route = runner
1885            .route("switchyard/typed")
1886            .expect("typed eligible route should exist");
1887        assert_eq!(
1888            route.models().models_for(&Category::Judge),
1889            [ModelId::from("decision/standard")]
1890        );
1891
1892        for (config, expected) in [
1893            (
1894                configured.replace(
1895                    "decision_client = \"privacy\"\nlabels = [\"private\"]",
1896                    "decision_client = \"privacy\"",
1897                ),
1898                "required target standard",
1899            ),
1900            (
1901                configured.replace(
1902                    "id = \"weak/model\"\nlabels = ['private']",
1903                    "id = \"weak/model\"",
1904                ),
1905                "required target weak",
1906            ),
1907        ] {
1908            let runner = Runner::from_toml(&config)?;
1909            let mut request = Request::default();
1910            require_target_labels(&mut request, ["private"])?;
1911            let message = runner
1912                .route("switchyard/typed")
1913                .expect("typed route")
1914                .decide(request)
1915                .await
1916                .err()
1917                .expect("unapproved role must fail before model I/O")
1918                .to_string();
1919            assert!(
1920                message.contains(expected),
1921                "expected {expected:?}, got {message}"
1922            );
1923        }
1924        Ok(())
1925    }
1926
1927    #[tokio::test]
1928    async fn label_requirements_select_only_approved_targets() -> RunnerResult<()> {
1929        let configured = eligible_pool_config();
1930        let runner = Runner::from_toml(&configured)?;
1931        let route = runner
1932            .route("switchyard/passthrough")
1933            .expect("eligible route should exist");
1934
1935        let mut request = Request::default();
1936        require_target_labels(&mut request, ["private"])?;
1937        let outcome = route.decide(request).await?;
1938        assert_eq!(outcome.selected_model_id()?, "strong");
1939        assert_eq!(
1940            &runner
1941                .describe_decision(&ModelId::from("switchyard/passthrough"), &outcome)
1942                .expect("selected target metadata")
1943                .selected
1944                .target,
1945            outcome.selected_model_id()?.as_str()
1946        );
1947        for (config, route_id, expected) in [
1948            (
1949                configured.replace("labels = ['private']", "labels = []"),
1950                "switchyard/passthrough",
1951                "without an eligible target",
1952            ),
1953            (
1954                format!("{configured}\n[routes.plan_execute.eligibility]\n"),
1955                "switchyard/plan-execute",
1956                "required target weak",
1957            ),
1958        ] {
1959            let runner = Runner::from_toml(&config)?;
1960            let mut request = Request::default();
1961            require_target_labels(&mut request, ["private"])?;
1962            let error = runner
1963                .route(route_id)
1964                .expect("configured route")
1965                .decide(request)
1966                .await
1967                .err()
1968                .expect("no eligible setup");
1969            assert!(error.to_string().contains(expected), "{error}");
1970        }
1971        Ok(())
1972    }
1973
1974    #[tokio::test]
1975    async fn ordinary_routes_reject_label_requirements() -> RunnerResult<()> {
1976        let runner = Runner::from_toml(VALID_CONFIG)?;
1977        let ordinary = runner.route("switchyard/random").expect("ordinary route");
1978        for labels in [&[][..], &["private"][..]] {
1979            let mut request = Request::default();
1980            require_target_labels(&mut request, labels)?;
1981            assert!(ordinary.decide(request).await.is_err());
1982        }
1983        Ok(())
1984    }
1985
1986    fn alternative_config(algorithm: &str) -> String {
1987        let globals = VALID_CONFIG.split("[routes.noop]").next().expect("globals");
1988        let mut config = globals.to_string();
1989        for name in ["weak", "strong", "classifier"] {
1990            config.push_str(&format!(
1991                "\n[targets.approved_{name}]\nid = 'approved/{name}'\nllm_client = 'primary'\nlabels = ['private']\n"
1992            ));
1993        }
1994        config.push_str(&format!(
1995            "\n[routes.test]\nid = 'route'\n{algorithm}\n[routes.test.eligibility.target_alternatives]\n"
1996        ));
1997        let spec: AlgorithmSpec = toml::from_str(algorithm).expect("test algorithm");
1998        for name in spec
1999            .callable_target_names()
2000            .into_iter()
2001            .collect::<BTreeSet<_>>()
2002        {
2003            config.push_str(&format!("{name} = ['approved_{name}']\n"));
2004        }
2005        config
2006    }
2007
2008    // Alternatives preserve fixed roles and selected-target metadata.
2009    #[tokio::test]
2010    async fn alternatives_preserve_router_roles() -> RunnerResult<()> {
2011        for (algorithm, initial) in [
2012            ("type = 'passthrough'\ntarget = 'weak'", "weak"),
2013            (
2014                "type = 'stage_router'\ncapable_target = 'strong'\nefficient_target = 'weak'\npicker = 'capable_first'\nconfidence_threshold = 0.0",
2015                "strong",
2016            ),
2017        ] {
2018            let runner = Runner::from_toml(&alternative_config(algorithm))?;
2019            let route = runner.route("route").expect("route");
2020            let standard = route.decide(Request::default()).await?;
2021            assert_eq!(standard.selected_model_id()?.as_str(), initial);
2022            let mut request = Request::default();
2023            require_target_labels(&mut request, ["private"])?;
2024            let outcome = route.decide(request).await?;
2025            assert_eq!(outcome.selected_model_id()?, &format!("approved_{initial}"));
2026            assert!(
2027                outcome
2028                    .selected_model_ids
2029                    .iter()
2030                    .all(|model| model.starts_with("approved_"))
2031            );
2032            let description = runner
2033                .describe_decision(&ModelId::from("route"), &outcome)
2034                .expect("mapped metadata");
2035            assert_eq!(description.selected.target, format!("approved_{initial}"));
2036        }
2037        Ok(())
2038    }
2039
2040    // Invalid references fail at load; unavailable approved bindings fail at admission.
2041    #[tokio::test]
2042    async fn alternatives_reject_invalid_bindings() -> RunnerResult<()> {
2043        let config = alternative_config(
2044            "type = 'auto'\ncapable_target = 'strong'\nefficient_target = 'weak'",
2045        );
2046        for (invalid, expected) in [
2047            (
2048                format!("{config}typo = ['approved_weak']\n"),
2049                "not used by the algorithm",
2050            ),
2051            (
2052                config.replace("weak = ['approved_weak']", "weak = ['missing']"),
2053                "must exist and match the target kind",
2054            ),
2055            (
2056                config.replace("weak = ['approved_weak']", "weak = []"),
2057                "target alternatives must not be empty",
2058            ),
2059            (
2060                config.replace(
2061                    "[llm_clients.primary]",
2062                    "[llm_clients.primary]\nforward_auth = true",
2063                ),
2064                "forwarded caller authentication",
2065            ),
2066        ] {
2067            let message = error_message(&invalid);
2068            assert!(
2069                message.contains(expected),
2070                "expected {expected:?}, got {message}"
2071            );
2072        }
2073        let random =
2074            alternative_config("type = 'random'\ntargets = ['weak', 'strong']\nweights = [0, 1]")
2075                .replace("strong = ['approved_strong']", "strong = ['approved_weak']");
2076        for (source, expected) in [
2077            (
2078                config.replace("weak = ['approved_weak']", "weak = ['strong']"),
2079                "required target weak",
2080            ),
2081            (random, "multiple pool entries to target approved_weak"),
2082        ] {
2083            let runner = Runner::from_toml(&source)?;
2084            let mut request = Request::default();
2085            require_target_labels(&mut request, ["private"])?;
2086            let error = runner
2087                .route("route")
2088                .expect("configured route")
2089                .decide(request)
2090                .await
2091                .err()
2092                .expect("invalid eligible bindings");
2093            assert!(error.to_string().contains(expected), "{error}");
2094        }
2095        Runner::from_toml(&config.replace("id = 'approved/weak'", "id = 'weak/model'"))?;
2096        let shared_model =
2097            alternative_config("type = 'random'\ntargets = ['weak', 'strong']\nweights = [0, 1]")
2098                .replace("id = 'approved/strong'", "id = 'approved/weak'");
2099        let runner = Runner::from_toml(&shared_model)?;
2100        let mut request = Request::default();
2101        require_target_labels(&mut request, ["private"])?;
2102        assert_eq!(
2103            runner
2104                .route("route")
2105                .expect("route")
2106                .decide(request)
2107                .await?
2108                .selected_model_id()?,
2109            "approved_strong"
2110        );
2111        let wrong_kind = format!(
2112            "{}\n[routes.typed.eligibility.target_alternatives]\nstandard = ['weak']\n",
2113            decision_eligibility_config()
2114        );
2115        assert!(error_message(&wrong_kind).contains("must exist and match the target kind"));
2116        Ok(())
2117    }
2118
2119    // A secondary verifier must not inherit the answer target's prompt after binding.
2120    #[tokio::test]
2121    async fn alternatives_reject_prompted_vgr_secondary_judge_alias() -> RunnerResult<()> {
2122        let source = alternative_config(
2123            "type = 'vgr'\nefficient_target = 'weak'\ncapable_target = 'strong'\njudge_target = 'strong'\ncapable_judge_target = 'classifier'",
2124        )
2125        .replace(
2126            "classifier = ['approved_classifier']",
2127            "classifier = ['approved_weak']",
2128        )
2129        .replace(
2130            "[targets.approved_weak]",
2131            "[targets.approved_weak]\nsystem_prompt = 'Answer the user.'",
2132        );
2133        let runner = Runner::from_toml(&source)?;
2134        let mut request = Request::default();
2135        require_target_labels(&mut request, ["private"])?;
2136        let error = runner
2137            .route("route")
2138            .expect("VGR route")
2139            .decide(request)
2140            .await
2141            .err()
2142            .expect("secondary judge alias must fail before model I/O");
2143        assert!(matches!(error, RunnerError::Configuration { .. }));
2144        assert!(error.to_string().contains("routing-only target"), "{error}");
2145        Ok(())
2146    }
2147
2148    #[test]
2149    fn factory_decision_ids_identify_one_client_across_alternatives() -> RunnerResult<()> {
2150        let source = format!(
2151            r#"{}
2152[decision_clients.other]
2153format = "system_one"
2154endpoint = "https://private.example.test/v1/decisions"
2155api_key_env = "PATH"
2156timeout_ms = 5000
2157
2158[decision_targets.alternative]
2159id = "decision/alternative"
2160decision_client = "other"
2161labels = ["private"]
2162
2163[routes.typed.eligibility.target_alternatives]
2164standard = ["alternative"]
2165"#,
2166            decision_eligibility_config()
2167        );
2168        AlgorithmFactory::from_toml(&source)?.build_configured()?;
2169
2170        let shared_id = source.replace("decision/alternative", "decision/standard");
2171        let ambiguous = shared_id.replace(
2172            "decision_client = \"privacy\"\nlabels = [\"private\"]",
2173            "decision_client = \"privacy\"",
2174        );
2175        Runner::from_toml(&ambiguous)?;
2176        let later_alternative = format!(
2177            r#"{}
2178[decision_targets.later]
2179id = "decision/standard"
2180decision_client = "other"
2181labels = ["private", "customer_data"]
2182"#,
2183            source.replace("[\"alternative\"]", "[\"alternative\", \"later\"]")
2184        );
2185        for source in [&ambiguous, &later_alternative] {
2186            let error = AlgorithmFactory::from_toml(source)?
2187                .build_configured()
2188                .err()
2189                .expect("ambiguous endpoint must fail during construction");
2190            assert!(
2191                error
2192                    .to_string()
2193                    .contains("maps decision model decision/standard to different clients"),
2194                "{error}"
2195            );
2196        }
2197
2198        let same_client = shared_id.replace(
2199            "decision_client = \"other\"",
2200            "decision_client = \"privacy\"",
2201        );
2202        AlgorithmFactory::from_toml(&same_client)?.build_configured()?;
2203        let separate_routes = format!(
2204            r#"{}
2205[routes.other]
2206id = "switchyard/other"
2207type = "llm_classifier"
2208classifier_target = "alternative"
2209strong_target = "strong"
2210weak_target = "weak"
2211"#,
2212            shared_id.replace("standard = [\"alternative\"]", "")
2213        );
2214        AlgorithmFactory::from_toml(&separate_routes)?.build_configured()?;
2215        Ok(())
2216    }
2217
2218    // Decision IDs remain provider keys, so bindings cannot give one ID two clients.
2219    #[tokio::test]
2220    async fn alternatives_reject_ambiguous_composite_decision_clients() -> RunnerResult<()> {
2221        let source = decision_eligibility_config().replace(
2222            "decision_client = \"privacy\"\nlabels = [\"private\"]",
2223            "decision_client = \"privacy\"",
2224        );
2225        let source = format!(
2226            r#"{source}
2227[decision_clients.other]
2228format = "system_one"
2229endpoint = "http://127.0.0.1:1/decisions"
2230api_key_env = "PATH"
2231timeout_ms = 1
2232
2233[decision_targets.secondary]
2234id = "decision/secondary"
2235decision_client = "privacy"
2236
2237[decision_targets.approved_primary]
2238id = "decision/shared"
2239decision_client = "privacy"
2240labels = ["private"]
2241
2242[decision_targets.approved_secondary]
2243id = "decision/shared"
2244decision_client = "other"
2245labels = ["private"]
2246
2247[routes.ambiguous]
2248id = "switchyard/ambiguous"
2249type = "composite"
2250classifier = {{ target = "standard", classify_trigger = "user_turn", decision = {{ cutoff = 0.4 }} }}
2251stage = {{ capable_target = "strong", efficient_target = "weak", confidence_threshold = 0.5 }}
2252efficient = {{ classifier = {{ target = "secondary", decision = {{ cutoff = 0.4 }} }} }}
2253
2254[routes.ambiguous.eligibility.target_alternatives]
2255standard = ["approved_primary"]
2256secondary = ["approved_secondary"]
2257"#
2258        );
2259        let runner = Runner::from_toml(&source)?;
2260        let mut request = Request::default();
2261        require_target_labels(&mut request, ["private"])?;
2262        let factory_error = AlgorithmFactory::from_toml(&source)?
2263            .build_configured()
2264            .err()
2265            .expect("ambiguous factory decisions must fail during construction");
2266        let error = runner
2267            .route("switchyard/ambiguous")
2268            .expect("composite route")
2269            .decide(request)
2270            .await
2271            .err()
2272            .expect("ambiguous decision clients must fail before model I/O");
2273        for error in [error, factory_error] {
2274            assert!(matches!(error, RunnerError::Configuration { .. }));
2275            assert!(
2276                error
2277                    .to_string()
2278                    .contains("maps decision model decision/shared to different clients"),
2279                "{error}"
2280            );
2281        }
2282        let standard_alias = source.replace(
2283            "id = \"decision/secondary\"\ndecision_client = \"privacy\"",
2284            "id = \"decision/standard\"\ndecision_client = \"other\"",
2285        );
2286        let ungoverned = standard_alias
2287            .split_once("[routes.ambiguous.eligibility.target_alternatives]")
2288            .expect("alternatives fixture")
2289            .0;
2290        for source in [standard_alias.as_str(), ungoverned] {
2291            let error = AlgorithmFactory::from_toml(source)?
2292                .build_configured()
2293                .err()
2294                .expect("ambiguous standard decisions must fail during construction");
2295            assert!(
2296                error
2297                    .to_string()
2298                    .contains("maps decision model decision/standard to different clients"),
2299                "{error}"
2300            );
2301        }
2302        Ok(())
2303    }
2304
2305    #[test]
2306    fn eligibility_rejects_unknown_fields_and_invalid_scope() {
2307        let configured = eligible_pool_config();
2308        for (invalid, expected) in [
2309            (
2310                configured.replace("labels = ['private']", "label = ['private']"),
2311                "unknown field `label`",
2312            ),
2313            (
2314                configured.replace(
2315                    "[routes.passthrough.eligibility]",
2316                    "[routes.passthrough.eligible]",
2317                ),
2318                "unknown field `eligible`",
2319            ),
2320            (
2321                decision_eligibility_config().replace(
2322                    "[decision_targets.standard]",
2323                    "[decision_targets.standard]\nlabel = ['private']",
2324                ),
2325                "unknown field `label`",
2326            ),
2327            (
2328                format!("{configured}\nrequire_explicit_requirement = true\n"),
2329                "unknown field `require_explicit_requirement`",
2330            ),
2331            (
2332                format!("{configured}\nscope = 'tenant'\n"),
2333                "unknown variant `tenant`",
2334            ),
2335        ] {
2336            let message = error_message(&invalid);
2337            assert!(
2338                message.contains(expected),
2339                "expected {expected:?}, got {message}"
2340            );
2341        }
2342    }
2343
2344    #[test]
2345    fn eligibility_rejects_conflicting_approvals_and_forwarded_auth() {
2346        let configured = eligible_pool_config();
2347        for (invalid, expected) in [
2348            (
2349                format!(
2350                    "{configured}\n[targets.alias]\nid = \"strong/model\"\nllm_client = \"responses\"\n"
2351                ),
2352                "disagree on approval labels",
2353            ),
2354            (
2355                format!(
2356                    "{}\n[decision_targets.alias]\nid = \"decision/standard\"\ndecision_client = \"privacy\"\n",
2357                    decision_eligibility_config()
2358                ),
2359                "disagrees on approval labels",
2360            ),
2361            (
2362                configured.replace(
2363                    "[llm_clients.responses]\nformat = \"openai_responses\"",
2364                    "[llm_clients.responses]\nformat = \"openai_responses\"\nforward_auth = true",
2365                ),
2366                "cannot use eligibility with forwarded caller authentication",
2367            ),
2368            (
2369                alternative_config(
2370                    "type = 'prefill_router'\ntargets = ['weak']\ncheckpoint = 'unused'",
2371                ),
2372                "cannot use eligibility with prefill_router",
2373            ),
2374        ] {
2375            let message = error_message(&invalid);
2376            assert!(
2377                message.contains(expected),
2378                "expected {expected:?}, got {message}"
2379            );
2380        }
2381    }
2382
2383    #[test]
2384    fn public_runner_from_toml_builds_a_deployment() -> RunnerResult<()> {
2385        let config = format!(
2386            "{VALID_CONFIG}\n[routes.classifier.infra]\n\
2387             max_signal_age_ms = 1000\nmin_waiting_requests = 4\nmax_capable_inflight = 2"
2388        );
2389        let runner = Runner::from_toml(&config)?;
2390        assert!(
2391            Runner::from_toml(
2392                &config.replace("min_waiting_requests = 4", "min_waiting_requests = 0")
2393            )
2394            .is_err()
2395        );
2396
2397        let classifier = runner
2398            .route("switchyard/classifier")
2399            .expect("classifier route should exist");
2400        let models = classifier.models();
2401        assert_eq!(
2402            models.models_for(&Category::Judge),
2403            [ModelId::from("classifier")]
2404        );
2405        assert_eq!(
2406            models.models_for(&Category::Efficient),
2407            [ModelId::from("weak")]
2408        );
2409        assert_eq!(
2410            models.models_for(&Category::Capable),
2411            [ModelId::from("strong")]
2412        );
2413        assert_eq!(
2414            models.models_for(&Category::Any),
2415            [ModelId::from("weak"), ModelId::from("strong")]
2416        );
2417        let plan_execute = runner
2418            .route("switchyard/plan-execute")
2419            .expect("plan-execute route should exist");
2420        assert_eq!(
2421            plan_execute.models().models_for(&Category::Capable),
2422            [ModelId::from("strong")]
2423        );
2424        assert_eq!(
2425            plan_execute.models().models_for(&Category::Efficient),
2426            [ModelId::from("weak")]
2427        );
2428        assert!(runner.route("switchyard/passthrough").is_some());
2429        Ok(())
2430    }
2431
2432    /// Both the TOML and JSON parsers must reject the removed `plan_execute` type.
2433    #[test]
2434    fn removed_plan_execute_type_is_rejected() {
2435        let route = r#"
2436type = "plan_execute"
2437capable_target = "strong"
2438efficient_target = "weak"
2439"#;
2440        let config = format!("{VALID_CONFIG}\n[routes.obsolete]\nid = \"obsolete\"\n{route}");
2441        assert!(error_message(&config).contains("unknown variant `plan_execute`"));
2442
2443        let error = serde_json::from_str::<AlgorithmSpec>(
2444            r#"{"type":"plan_execute","capable_target":"strong","efficient_target":"weak"}"#,
2445        )
2446        .expect_err("the removed algorithm must be rejected");
2447        assert!(error.to_string().contains("unknown variant `plan_execute`"));
2448    }
2449
2450    /// TOML and JSON parsers must reject old `plan_execute` fields on `stage_router` routes.
2451    /// Changing only the route type must not load a route that ignores its handoff settings.
2452    #[test]
2453    fn stage_rejects_obsolete_plan_execute_settings() {
2454        let stage = json!({
2455            "type": "stage_router", "capable_target": "strong", "efficient_target": "weak",
2456            "picker": "capable_first", "confidence_threshold": 0.0,
2457            "efficient_hold_turns": -1, "capable_system_prompt": "Plan before editing.",
2458        });
2459        assert!(serde_json::from_str::<AlgorithmSpec>(&stage.to_string()).is_ok());
2460        for (field, value, toml_value) in [
2461            ("planning_prompt", json!("plan"), r#""plan""#),
2462            ("handoff_prompt", json!("execute"), r#""execute""#),
2463            ("planner_reasoning_as_text", json!(true), "true"),
2464            ("execution_trigger", json!("edit"), r#""edit""#),
2465            (
2466                "judge",
2467                json!({"target": "classifier"}),
2468                r#"{ target = "classifier" }"#,
2469            ),
2470        ] {
2471            let mut invalid = stage.clone();
2472            invalid[field] = value;
2473            let error = serde_json::from_str::<AlgorithmSpec>(&invalid.to_string())
2474                .expect_err("obsolete fields must be rejected");
2475            assert!(error.to_string().contains(field), "{error}");
2476            let error = error_message(&format!("{VALID_CONFIG}\n{field} = {toml_value}\n"));
2477            assert!(error.contains(field), "{error}");
2478        }
2479    }
2480
2481    #[test]
2482    fn duplicate_route_ids_are_rejected() {
2483        let config = format!(
2484            r#"{VALID_CONFIG}
2485
2486[routes.duplicate]
2487id = "switchyard/passthrough"
2488type = "passthrough"
2489target = "strong"
2490"#
2491        );
2492
2493        let error = error_message(&config);
2494
2495        assert!(
2496            error.contains(
2497                "routes duplicate and passthrough both use id switchyard/passthrough; route ids must be unique"
2498            ),
2499            "{error}"
2500        );
2501    }
2502
2503    fn error_message(toml: &str) -> String {
2504        match runner_from_toml(toml) {
2505            Ok(_) => "configuration unexpectedly succeeded".to_string(),
2506            Err(error) => error.to_string(),
2507        }
2508    }
2509
2510    fn vgr_config() -> String {
2511        format!(
2512            r#"{VALID_CONFIG}
2513
2514[routes.vgr]
2515id = "switchyard/vgr"
2516type = "vgr"
2517efficient_target = "weak"
2518capable_target = "strong"
2519judge_target = "classifier"
2520mode = "active"
2521active_approval = "prospective-validation-and-canary-approved"
2522task_typing = false
2523"#
2524        )
2525    }
2526
2527    #[test]
2528    fn vgr_compaction_is_opt_in_from_toml() -> RunnerResult<()> {
2529        for setting in ["", "compact_handoff = false", "compact_handoff = true"] {
2530            let source = format!("{}\nagentic_handoff = true\n{setting}\n", vgr_config());
2531            let parsed: DeploymentConfig = toml::from_str(&source).expect("valid VGR config");
2532            let AlgorithmSpec::Vgr { config } = &parsed.routes["vgr"].algorithm else {
2533                panic!("expected VGR route");
2534            };
2535            assert_eq!(config.compact_handoff, setting.ends_with("= true"));
2536            assert!(runner_from_toml(&source)?.route("switchyard/vgr").is_some());
2537        }
2538        Ok(())
2539    }
2540
2541    #[test]
2542    fn vgr_route_builds_and_rejects_unsafe_configuration() -> RunnerResult<()> {
2543        let runner = runner_from_toml(&vgr_config())?;
2544        assert!(runner.route("switchyard/vgr").is_some());
2545
2546        let compact = format!("{}\ncompact_handoff = true\n", vgr_config());
2547        assert!(error_message(&compact).contains("compact_handoff requires agentic_handoff"));
2548        let compact = format!("{compact}\nagentic_handoff = true\n");
2549        assert!(
2550            runner_from_toml(&compact)?
2551                .route("switchyard/vgr")
2552                .is_some()
2553        );
2554
2555        let identical_ids = vgr_config().replace(
2556            "efficient_target = \"weak\"",
2557            "efficient_target = \"strong\"",
2558        );
2559        assert!(error_message(&identical_ids).contains("distinct efficient and capable model IDs"));
2560
2561        let bad_approval =
2562            vgr_config().replace("prospective-validation-and-canary-approved", "approved");
2563        assert!(error_message(&bad_approval).contains("approval attestation"));
2564
2565        let missing_target = vgr_config().replace(
2566            "efficient_target = \"weak\"",
2567            "efficient_target = \"missing\"",
2568        );
2569        assert!(error_message(&missing_target).contains("unknown target missing"));
2570
2571        let zero_cooldown = format!("{}breaker_cooldown_seconds = 0\n", vgr_config());
2572        assert!(
2573            error_message(&zero_cooldown).contains("breaker_cooldown_seconds must be a positive")
2574        );
2575        Ok(())
2576    }
2577
2578    #[test]
2579    fn vgr_local_server_example_builds_and_rejects_unknown_discovery() -> RunnerResult<()> {
2580        let example = include_str!("../../../examples/vgr-local-servers.toml");
2581        let runner = runner_from_toml(example)?;
2582        assert!(runner.route("switchyard/vgr").is_some());
2583        assert!(runner.route("switchyard/only-efficient").is_some());
2584        let parsed: DeploymentConfig = toml::from_str(example).expect("valid VGR example");
2585        assert!(matches!(
2586            &parsed.routes["auxiliary"].algorithm,
2587            AlgorithmSpec::Passthrough { target, .. } if target == "efficient"
2588        ));
2589        let invalid = example.replace(
2590            "context_discovery = \"llama_cpp\"",
2591            "context_discovery = \"guess\"",
2592        );
2593        assert!(error_message(&invalid).contains("unknown variant `guess`"));
2594        Ok(())
2595    }
2596
2597    /// Reject an invalid image budget or a mode that never consumes it.
2598    #[test]
2599    fn rejects_invalid_judge_image_limits() {
2600        let negative = VALID_CONFIG.replace(
2601            "base_threshold = 0.5",
2602            "base_threshold = 0.5\njudge_max_images = -1",
2603        );
2604        assert!(Runner::from_toml(&negative).is_err());
2605        let escalation = VALID_CONFIG.replace(
2606            "base_threshold = 0.5",
2607            "mode = \"escalation\"\nescalation = { confirmations = 1 }\njudge_max_images = 1",
2608        );
2609        assert!(error_message(&escalation).contains("mode escalation cannot use judge_max_images"));
2610    }
2611
2612    fn with_subagent_llm_classifier(config: &str, route: &str, extra: &str) -> String {
2613        let mut configured = config.to_string();
2614        configured.push_str(&format!("\n[routes.{route}.subagents]\n"));
2615        configured.push_str(
2616            r#"type = "llm_classifier"
2617mode = "custom"
2618models = { judge = ["classifier"], capable = ["strong"], efficient = ["weak"], any = ["strong", "weak"] }
2619default_target = "efficient"
2620prompt = "Select a target for this delegated task."
2621response_schema = '{"type":"object","properties":{"target":{"type":"string","enum":["capable","efficient"]}},"required":["target"],"additionalProperties":false}'
2622policy = { type = "target_selector", selector = "/target" }
2623classify_trigger = "new_session""#,
2624        );
2625        configured.push_str(extra);
2626        configured
2627    }
2628
2629    #[test]
2630    fn subagent_models_stay_separate_from_the_parent_tiers() -> RunnerResult<()> {
2631        // The sub-agent target is also the parent's capable tier. Merged into one group it
2632        // would be indistinguishable from that tier, and delegated work would follow the
2633        // parent's ordering instead of its own configured target.
2634        let runner = runner_from_toml(&with_subagent_passthrough(&stage_config(), "stage"))?;
2635        let models = runner
2636            .route("switchyard/stage")
2637            .expect("stage route should exist")
2638            .models();
2639
2640        assert_eq!(
2641            models.subagent_models_for(&Category::Any),
2642            [ModelId::from("strong")]
2643        );
2644        assert_eq!(
2645            models.models_for(&Category::Any),
2646            [ModelId::from("strong"), ModelId::from("weak")]
2647        );
2648        Ok(())
2649    }
2650
2651    fn with_subagent_passthrough(config: &str, route: &str) -> String {
2652        format!("{config}\n[routes.{route}.subagents]\ntype = \"passthrough\"\ntarget = \"strong\"")
2653    }
2654
2655    fn stage_config() -> String {
2656        format!(
2657            r#"{VALID_CONFIG}
2658[targets.stage_judge]
2659id = "stage-judge/model"
2660llm_client = "primary"
2661
2662[routes.stage]
2663id = "switchyard/stage"
2664type = "stage_router"
2665capable_target = "strong"
2666efficient_target = "weak"
2667picker = "efficient_first"
2668confidence_threshold = 1.0
2669capable_hold_turns = 2
2670
2671[routes.stage.tool_semantics]
2672observe = ["lookup_customer"]
2673mutate = ["send_payment"]
2674plan = ["create_workflow"]
2675new = ["send_message"]
2676
2677[routes.stage.classifier]
2678target = "stage_judge"
2679base_threshold = 0.5
2680"#
2681        )
2682    }
2683
2684    fn composite_config() -> String {
2685        format!(
2686            r#"{VALID_CONFIG}
2687[targets.tier_judge]
2688id = "tier-judge/model"
2689llm_client = "primary"
2690
2691[routes.composed]
2692id = "switchyard/hier"
2693type = "composite"
2694
2695[routes.composed.classifier]
2696target = "tier_judge"
2697base_threshold = 0.5
2698classify_trigger = "user_turn"
2699
2700[routes.composed.stage]
2701capable_target = "strong"
2702efficient_target = "weak"
2703confidence_threshold = 0.5
2704capable_hold_turns = 2
2705
2706[routes.composed.stage.tool_semantics]
2707new = ["send_message"]
2708"#
2709        )
2710    }
2711
2712    #[test]
2713    fn stage_and_composite_validate_hold_turns() {
2714        let composite =
2715            composite_config().replace("capable_hold_turns = 2", "capable_hold_turns = 0");
2716        for source in [
2717            stage_config(),
2718            stage_config().replace("efficient_first", "capable_first"),
2719            composite_config(),
2720            format!("{composite}\n[routes.composed.efficient]\ncapable_hold_turns = 2"),
2721            format!("{composite}\n[routes.composed.capable]\ncapable_hold_turns = 2"),
2722        ] {
2723            for field in ["capable_hold_turns", "efficient_hold_turns"] {
2724                for (turns, valid) in [
2725                    (-2_i64, false),
2726                    (-1, true),
2727                    (0, true),
2728                    (3, true),
2729                    (i64::from(u32::MAX), true),
2730                    (i64::from(u32::MAX) + 1, false),
2731                ] {
2732                    let configured =
2733                        source.replace("capable_hold_turns = 2", &format!("{field} = {turns}"));
2734                    let result = AlgorithmFactory::from_toml(&configured)
2735                        .and_then(|factory| factory.build());
2736                    assert_eq!(result.is_ok(), valid, "{field} = {turns}");
2737                    if let Err(error) = result {
2738                        assert!(error.to_string().contains(field), "{error}");
2739                    }
2740                }
2741            }
2742        }
2743    }
2744
2745    #[test]
2746    fn composite_decision_judge_reuses_capability_validation() {
2747        let source = composite_config().replace(
2748            "[routes.composed.classifier]\ntarget = \"tier_judge\"\nbase_threshold = 0.5",
2749            "[routes.composed.classifier]\ntarget = \"tier_judge\"",
2750        ) + r#"
2751[routes.composed.classifier.decision]
2752cutoff = 0.4
2753instructions = "candidate comparison"
2754"#;
2755        for (source, valid) in [
2756            (source.clone(), true),
2757            (
2758                source.replace(
2759                    "target = \"tier_judge\"",
2760                    "target = \"tier_judge\"\nbase_threshold = 0.5",
2761                ),
2762                false,
2763            ),
2764            (source.replace("cutoff = 0.4", "cutoff = 1.1"), false),
2765        ] {
2766            let deployment: DeploymentConfig = toml::from_str(&source).unwrap();
2767            let spec = &deployment.routes["composed"].algorithm;
2768            assert_eq!(spec.classifier_targets().next().unwrap().0, "tier_judge");
2769            assert_eq!(
2770                spec.build_with_runtime_models("composed", &deployment.build_targets())
2771                    .is_ok(),
2772                valid
2773            );
2774        }
2775    }
2776
2777    #[test]
2778    fn decision_target_judges_use_default_decision_settings() -> RunnerResult<()> {
2779        let source = format!(
2780            r#"{VALID_CONFIG}
2781[decision_clients.decisions]
2782format = "openai_decisions"
2783endpoint = "https://example.test/v1/decisions"
2784api_key_env = "PATH"
2785timeout_ms = 5000
2786
2787[decision_targets.judge]
2788id = "decision/judge"
2789decision_client = "decisions"
2790
2791[routes.judged]
2792id = "switchyard/judged"
2793type = "llm_classifier"
2794classifier_target = "judge"
2795strong_target = "strong"
2796weak_target = "weak"
2797
2798[routes.staged]
2799id = "switchyard/staged"
2800type = "stage_router"
2801capable_target = "strong"
2802efficient_target = "weak"
2803picker = "efficient_first"
2804confidence_threshold = 1.0
2805
2806[routes.staged.classifier]
2807target = "judge"
2808
2809[routes.composed]
2810id = "switchyard/composed"
2811type = "composite"
2812
2813[routes.composed.classifier]
2814target = "judge"
2815classify_trigger = "user_turn"
2816
2817[routes.composed.stage]
2818capable_target = "strong"
2819efficient_target = "weak"
2820
2821[routes.composed.efficient.classifier]
2822target = "judge"
2823"#
2824        );
2825        let factory = AlgorithmFactory::from_toml(&source)?;
2826        let routes = &factory.config.routes;
2827        for route in ["judged", "staged", "composed"] {
2828            let judges: Vec<_> = routes[route].algorithm.classifier_targets().collect();
2829            assert!(!judges.is_empty(), "{route}");
2830            assert!(
2831                judges
2832                    .iter()
2833                    .all(|(target, decision)| *target == "judge" && decision.is_some()),
2834                "{route}"
2835            );
2836        }
2837        // LLM judges keep their capability settings.
2838        assert!(
2839            routes["classifier"]
2840                .algorithm
2841                .classifier_targets()
2842                .all(|(_, d)| d.is_none())
2843        );
2844        factory.build()?;
2845        runner_from_toml(&source)?;
2846        Ok(())
2847    }
2848
2849    #[test]
2850    fn composite_custom_judge_builds_and_rejects_capability_settings() -> RunnerResult<()> {
2851        let source = composite_config().replace(
2852            "base_threshold = 0.5\nclassify_trigger",
2853            r#"mode = "custom"
2854prompt = 'Select efficient or capable.'
2855response_schema = '{"type":"object","properties":{"decision":{"type":"object","properties":{"target":{"type":"string","enum":["efficient","capable"]}},"required":["target"],"additionalProperties":false}},"required":["decision"],"additionalProperties":false}'
2856policy = { type = "target_selector", selector = "/decision/target" }
2857classify_trigger"#,
2858        );
2859        runner_from_toml(&source)?;
2860        runner_from_toml(
2861            &source.replace("mode = \"custom\"", "mode = \"custom\"\nfail_open = true"),
2862        )?;
2863        for (setting, expected) in [
2864            (
2865                "base_threshold = 0.5",
2866                "composite custom classifier cannot use capability thresholds",
2867            ),
2868            (
2869                "fail_open = false",
2870                "composite custom classifiers always fail open",
2871            ),
2872        ] {
2873            let invalid = source.replace(
2874                "mode = \"custom\"",
2875                &format!("mode = \"custom\"\n{setting}"),
2876            );
2877            assert!(error_message(&invalid).contains(expected));
2878        }
2879        Ok(())
2880    }
2881
2882    #[test]
2883    fn composite_route_builds_and_claims_both_tiers_and_its_judge() -> RunnerResult<()> {
2884        let runner = runner_from_toml(&composite_config())?;
2885        assert!(
2886            runner
2887                .models()
2888                .any(|model| model.id.as_str() == "switchyard/hier")
2889        );
2890        Ok(())
2891    }
2892
2893    #[test]
2894    fn builds_all_supported_algorithm_types() -> RunnerResult<()> {
2895        let state = runner_from_toml(VALID_CONFIG)?;
2896        // The model id array is sorted alphabetically
2897        assert_eq!(
2898            state
2899                .models()
2900                .map(|model| model.id.as_str())
2901                .collect::<Vec<_>>(),
2902            [
2903                "switchyard/classifier",
2904                "switchyard/noop",
2905                "switchyard/passthrough",
2906                "switchyard/plan-execute",
2907                "switchyard/random",
2908            ]
2909        );
2910        Ok(())
2911    }
2912
2913    #[test]
2914    fn stage_rejects_ambiguous_or_non_additive_tool_semantics() {
2915        for (configured, expected) in [
2916            (
2917                stage_config().replace(
2918                    "mutate = [\"send_payment\"]",
2919                    "mutate = [\"LOOKUP_CUSTOMER\"]",
2920                ),
2921                "appears in both tool_semantics.observe and tool_semantics.mutate",
2922            ),
2923            (
2924                stage_config().replace("new = [\"send_message\"]", "new = [\"Read\"]"),
2925                "already has built-in semantics and cannot be reclassified",
2926            ),
2927            (
2928                stage_config().replace("observe = [\"lookup_customer\"]", "observe = [\" \"]"),
2929                "contains an empty tool name",
2930            ),
2931        ] {
2932            let message = error_message(&configured);
2933            assert!(
2934                message.contains(expected),
2935                "expected {expected:?} in error, got: {message}"
2936            );
2937        }
2938    }
2939
2940    #[test]
2941    fn passthrough_and_stage_accept_subagent_routing() -> RunnerResult<()> {
2942        let stage = stage_config();
2943        let stage_with_classifier = with_subagent_llm_classifier(&stage, "stage", "");
2944        let parsed: DeploymentConfig = toml::from_str(&stage_with_classifier).map_err(|error| {
2945            RunnerError::configuration(format!("failed to parse stage config: {error}"))
2946        })?;
2947        let Some(stage_route) = parsed.routes.get("stage") else {
2948            return Err(RunnerError::configuration("stage route is missing"));
2949        };
2950        let callable_targets = stage_route.callable_target_names();
2951        for expected in ["strong", "weak", "stage_judge", "classifier"] {
2952            assert!(callable_targets.contains(&expected));
2953        }
2954
2955        for configured in [
2956            with_subagent_llm_classifier(VALID_CONFIG, "passthrough", ""),
2957            with_subagent_passthrough(VALID_CONFIG, "passthrough"),
2958            stage_with_classifier,
2959            with_subagent_passthrough(&stage, "stage"),
2960        ] {
2961            runner_from_toml(&configured)?;
2962        }
2963        Ok(())
2964    }
2965
2966    // A routing-only judge cannot inherit the answer target's system prompt.
2967    #[test]
2968    fn rejects_prompted_answer_target_used_as_routing_only_target() {
2969        let configured = VALID_CONFIG
2970            .replace(
2971                "classifier_target = \"classifier\"",
2972                "classifier_target = \"weak\"",
2973            )
2974            .replace(
2975                "id = \"weak/model\"\nllm_client = \"anthropic\"",
2976                "id = \"weak/model\"\nllm_client = \"anthropic\"\nsystem_prompt = \"answer prompt\"",
2977            )
2978            .replace(
2979                "base_threshold = 0.5",
2980                "base_threshold = 0.5\nescalation = { confirmations = 1 }",
2981            );
2982
2983        assert_eq!(
2984            error_message(&configured),
2985            "route classifier cannot apply system_prompt to target weak: it is also the routing-only target"
2986        );
2987    }
2988
2989    #[test]
2990    fn rejects_invalid_unreferenced_llm_client() {
2991        for (settings, expected) in [
2992            (
2993                "base_url = \"not a url\"",
2994                "base_url must be an absolute HTTP(S) URL",
2995            ),
2996            (
2997                "base_url = \"https://example.test\"\ntimeout_ms = 0",
2998                "timeout_ms must be at least 1",
2999            ),
3000        ] {
3001            let invalid = format!(
3002                "{VALID_CONFIG}\n[llm_clients.unused]\nformat = \"openai_chat\"\n{settings}"
3003            );
3004            let message = error_message(&invalid);
3005            assert!(message.contains(expected), "unexpected error: {message}");
3006        }
3007    }
3008
3009    #[test]
3010    fn an_escalation_table_switches_the_classifier_route_to_escalation() -> RunnerResult<()> {
3011        // Present: the classifier target judges the weak tier's reply each turn instead of
3012        // picking a tier ahead of it. The route builds either way, so the assertion is that
3013        // the knob parses and its settings reach the algorithm's validation.
3014        let escalating = VALID_CONFIG.replace(
3015            "base_threshold = 0.5",
3016            "base_threshold = 0.5\nescalation = { confirmations = 2 }",
3017        );
3018        runner_from_toml(&escalating)?;
3019
3020        let reversible = VALID_CONFIG.replace(
3021            "base_threshold = 0.5",
3022            "base_threshold = 0.5\nescalation = { confirmations = 2, deescalation = { strong_min_calls = 3, confirmations = 2, strong_max_calls = 6, weak_cooldown_calls = 8 } }",
3023        );
3024        runner_from_toml(&reversible)?;
3025
3026        // A setting that would starve the judge is rejected here rather than on the first
3027        // request, the same as any other unusable route configuration.
3028        let starved = VALID_CONFIG.replace(
3029            "base_threshold = 0.5",
3030            "base_threshold = 0.5\nescalation = { confirmations = 0 }",
3031        );
3032        assert!(error_message(&starved).contains("confirmations must be at least 1"));
3033
3034        Ok(())
3035    }
3036
3037    #[test]
3038    fn unmatched_steps_is_a_capability_setting() -> RunnerResult<()> {
3039        // Accepted on a capability route; the value range is checked by the algorithm.
3040        runner_from_toml(&VALID_CONFIG.replace(
3041            "base_threshold = 0.5",
3042            "base_threshold = 0.5\nunmatched_steps = 2",
3043        ))?;
3044        assert!(
3045            error_message(&VALID_CONFIG.replace(
3046                "base_threshold = 0.5",
3047                "base_threshold = 0.5\nunmatched_steps = 3",
3048            ))
3049            .contains("unmatched_steps must be 0, 1, or 2")
3050        );
3051
3052        // Rejected on an escalation route, including the implicit form where the
3053        // `escalation` table alone selects the mode: the key is new, so no existing
3054        // configuration relies on it being ignored there.
3055        assert!(
3056            error_message(&VALID_CONFIG.replace(
3057                "base_threshold = 0.5",
3058                "base_threshold = 0.5\nunmatched_steps = 2\nescalation = { confirmations = 2 }",
3059            ))
3060            .contains("mode escalation cannot use capability routing settings")
3061        );
3062        Ok(())
3063    }
3064
3065    #[test]
3066    fn a_target_reasoning_effort_parses_on_every_client_format() -> RunnerResult<()> {
3067        let strong = "[targets.strong]\nid = \"strong/model\"\nllm_client = \"responses\"";
3068        let weak = "[targets.weak]\nid = \"weak/model\"\nllm_client = \"anthropic\"";
3069        assert!(VALID_CONFIG.contains(strong) && VALID_CONFIG.contains(weak));
3070
3071        let forced = VALID_CONFIG.replace(strong, &format!("{strong}\nreasoning_effort = \"max\""));
3072        runner_from_toml(&forced)?;
3073
3074        let blank = VALID_CONFIG.replace(strong, &format!("{strong}\nreasoning_effort = \" \""));
3075        assert!(error_message(&blank).contains("reasoning_effort must not be empty"));
3076
3077        let anthropic = VALID_CONFIG.replace(weak, &format!("{weak}\nreasoning_effort = \"high\""));
3078        runner_from_toml(&anthropic)?;
3079
3080        let minimal =
3081            VALID_CONFIG.replace(weak, &format!("{weak}\nreasoning_effort = \"minimal\""));
3082        assert!(
3083            error_message(&minimal).contains("is not an anthropic_messages effort"),
3084            "{}",
3085            error_message(&minimal)
3086        );
3087        Ok(())
3088    }
3089
3090    #[test]
3091    fn decision_target_ids_must_not_match_llm_target_names() {
3092        let configured = format!(
3093            "{VALID_CONFIG}\n[decision_clients.decisions]\nformat = \"system_one\"\nendpoint = \"https://example.test/decisions\"\napi_key_env = \"PATH\"\ntimeout_ms = 5000\n\n[decision_targets.judge]\nid = \"strong\"\ndecision_client = \"decisions\"\n"
3094        );
3095        let message = error_message(&configured);
3096        assert!(
3097            message.contains("decision target judge id strong is also an LLM target name"),
3098            "{message}"
3099        );
3100    }
3101
3102    #[test]
3103    fn classifier_judge_completion_caps_are_configurable() -> RunnerResult<()> {
3104        let capability = VALID_CONFIG.replace(
3105            "base_threshold = 0.5",
3106            "base_threshold = 0.5\nmax_output_tokens = 512",
3107        );
3108        runner_from_toml(&capability)?;
3109
3110        let escalation = VALID_CONFIG.replace(
3111            "base_threshold = 0.5",
3112            "base_threshold = 0.5\nmax_output_tokens = 256\nescalation = { confirmations = 2 }",
3113        );
3114        runner_from_toml(&escalation)?;
3115        Ok(())
3116    }
3117
3118    #[test]
3119    fn classifier_prompts_are_configurable_in_both_modes() -> RunnerResult<()> {
3120        let capability = VALID_CONFIG.replace(
3121            "base_threshold = 0.5",
3122            "base_threshold = 0.5\nprompt = \"custom capability rubric\"",
3123        );
3124        runner_from_toml(&capability)?;
3125
3126        let escalation = VALID_CONFIG.replace(
3127            "base_threshold = 0.5",
3128            "base_threshold = 0.5\nprompt = \"custom trajectory rubric\"\nescalation = { confirmations = 2 }",
3129        );
3130        runner_from_toml(&escalation)?;
3131
3132        let empty = VALID_CONFIG.replace(
3133            "base_threshold = 0.5",
3134            "base_threshold = 0.5\nprompt = \"   \"",
3135        );
3136        assert!(error_message(&empty).contains("classifier prompt must not be empty"));
3137
3138        let schema_placeholder = VALID_CONFIG.replace(
3139            "base_threshold = 0.5",
3140            "base_threshold = 0.5\nprompt = \"{{RESPONSE_SCHEMA}}\"",
3141        );
3142        assert!(
3143            error_message(&schema_placeholder)
3144                .contains("Switchyard supplies the schema automatically")
3145        );
3146        Ok(())
3147    }
3148
3149    #[test]
3150    fn mode_custom_rejects_capability_fields() {
3151        let mixed = VALID_CONFIG.replace(
3152            "base_threshold = 0.5",
3153            "mode = \"custom\"\nbase_threshold = 0.5",
3154        );
3155
3156        assert!(
3157            error_message(&mixed)
3158                .contains("mode custom cannot use capability or escalation fields")
3159        );
3160    }
3161
3162    #[test]
3163    fn stage_router_rejects_an_unknown_field() {
3164        let config = stage_config().replace(
3165            "picker = \"efficient_first\"",
3166            "picker = \"efficient_first\"\nmagic = true",
3167        );
3168        assert!(error_message(&config).contains("unknown field"));
3169    }
3170
3171    #[test]
3172    fn auto_route_builds_a_stage_router_with_no_extra_fields() -> RunnerResult<()> {
3173        let config = format!(
3174            r#"{VALID_CONFIG}
3175[routes.auto]
3176id = "switchyard/auto"
3177type = "auto"
3178capable_target = "strong"
3179efficient_target = "weak"
3180"#
3181        );
3182        let runner = runner_from_toml(&config)?;
3183        assert!(runner.route("switchyard/auto").is_some());
3184        Ok(())
3185    }
3186
3187    #[test]
3188    fn composite_stage_block_rejects_an_unknown_field() {
3189        let config = composite_config().replace(
3190            "confidence_threshold = 0.5",
3191            "confidence_threshold = 0.5\nmagic = true",
3192        );
3193        assert!(error_message(&config).contains("unknown field"));
3194    }
3195
3196    #[test]
3197    fn rejects_unknown_fields_and_algorithm_types() {
3198        let unknown_field =
3199            VALID_CONFIG.replace("schema_version = 1", "schema_version = 1\nmagic = true");
3200        assert!(error_message(&unknown_field).contains("unknown field"));
3201
3202        let nested_completion_cap = VALID_CONFIG.replace(
3203            "base_threshold = 0.5",
3204            "base_threshold = 0.5\nescalation = { max_output_tokens = 256 }",
3205        );
3206        assert!(error_message(&nested_completion_cap).contains("unknown field"));
3207
3208        let unknown_classifier_field = VALID_CONFIG.replace(
3209            "base_threshold = 0.5",
3210            "base_threshold = 0.5\nclassifier_magic = true",
3211        );
3212        assert!(error_message(&unknown_classifier_field).contains("unknown field"));
3213
3214        let target_capability = VALID_CONFIG.replace(
3215            "llm_client = \"responses\"",
3216            "llm_client = \"responses\"\ncontext_window = 1000000",
3217        );
3218        assert!(error_message(&target_capability).contains("unknown field `context_window`"));
3219
3220        let unknown_algorithm = VALID_CONFIG.replace("type = \"noop\"", "type = \"imaginary\"");
3221        assert!(error_message(&unknown_algorithm).contains("unknown variant"));
3222    }
3223
3224    #[test]
3225    fn rejects_unknown_stage_classifier_fields() {
3226        // Nested classifier typos must fail instead of silently using a default.
3227        let config = format!(
3228            r#"{VALID_CONFIG}
3229
3230[routes.stage]
3231id = "switchyard/stage"
3232type = "stage_router"
3233capable_target = "strong"
3234efficient_target = "weak"
3235picker = "efficient_first"
3236confidence_threshold = 1.0
3237
3238[routes.stage.classifier]
3239target = "classifier"
3240base_threshold = 0.5
3241classifier_magic = true
3242"#
3243        );
3244
3245        let error = error_message(&config);
3246        assert!(
3247            error.contains("unknown field `classifier_magic`"),
3248            "{error}"
3249        );
3250    }
3251
3252    #[test]
3253    fn rejects_invalid_references_and_parameters() {
3254        let cases = [
3255            (
3256                VALID_CONFIG.replace("llm_client = \"primary\"", "llm_client = \"missing\""),
3257                "unknown llm client missing",
3258            ),
3259            (
3260                VALID_CONFIG.replace(
3261                    "targets = [\"strong\", \"weak\"]",
3262                    "targets = [\"strong\", \"missing\"]",
3263                ),
3264                "unknown target missing",
3265            ),
3266            (
3267                VALID_CONFIG.replace(
3268                    "targets = [\"strong\", \"weak\"]",
3269                    "targets = [\"strong\", \"weak\"]\nweights = [0, 0]",
3270                ),
3271                "at least one weight must be positive",
3272            ),
3273            (
3274                VALID_CONFIG.replace(
3275                    "targets = [\"strong\", \"weak\"]",
3276                    "targets = [\"strong\", \"strong\"]",
3277                ),
3278                "targets must be unique, strong is repeated",
3279            ),
3280            (
3281                VALID_CONFIG.replace(
3282                    "targets = [\"strong\", \"weak\"]",
3283                    "targets = [\"strong\", \"weak\"]\nweights = [1]",
3284                ),
3285                "expected 2 weights, got 1",
3286            ),
3287            (
3288                VALID_CONFIG.replace("base_threshold = 0.5", "base_threshold = 1.5"),
3289                "base_threshold must be between 0 and 1",
3290            ),
3291            (
3292                VALID_CONFIG.replace("classifier_target = \"classifier\"\n", ""),
3293                "route references unknown target",
3294            ),
3295            (
3296                VALID_CONFIG.replace(
3297                    "classifier_target = \"classifier\"",
3298                    "classifier_target = \"\"",
3299                ),
3300                "route references unknown target",
3301            ),
3302            (
3303                VALID_CONFIG.replace(
3304                    "classifier_target = \"classifier\"",
3305                    "classifier_target = \"   \"",
3306                ),
3307                "route references unknown target",
3308            ),
3309            (
3310                VALID_CONFIG.replace(
3311                    "base_threshold = 0.5",
3312                    "base_threshold = 0.5\nthreshold_step = -0.1",
3313                ),
3314                "threshold_step must be finite and greater than or equal to 0",
3315            ),
3316            (
3317                VALID_CONFIG.replace(
3318                    "base_threshold = 0.5",
3319                    "base_threshold = 0.8\nthreshold_step = 0.11",
3320                ),
3321                "base_threshold + 2 * threshold_step must be at most 1",
3322            ),
3323            (
3324                VALID_CONFIG.replace(
3325                    "base_threshold = 0.5",
3326                    "base_threshold = 0.5\nmax_output_tokens = 0\nescalation = { confirmations = 2 }",
3327                ),
3328                "max_output_tokens must be at least 1",
3329            ),
3330            (
3331                VALID_CONFIG.replace(
3332                    "base_threshold = 0.5",
3333                    "base_threshold = 0.5\nmessage_hash_fallback = true",
3334                ),
3335                "message_hash_fallback requires classify_trigger = new_session",
3336            ),
3337            (
3338                with_subagent_llm_classifier(
3339                    VALID_CONFIG,
3340                    "passthrough",
3341                    "\nmessage_hash_fallback = true",
3342                ),
3343                "cannot use message_hash_fallback",
3344            ),
3345            (
3346                with_subagent_llm_classifier(VALID_CONFIG, "passthrough", "")
3347                    .replace("mode = \"custom\"", "mode = \"capability\""),
3348                "mode capability cannot use custom classifier fields",
3349            ),
3350            (
3351                VALID_CONFIG.replace(
3352                    "base_threshold = 0.5",
3353                    "escalation = { confirmations = 2 }\nclassify_trigger = \"user_turn\"",
3354                ),
3355                "mode escalation cannot use classify_trigger",
3356            ),
3357            (
3358                VALID_CONFIG.replace("schema_version = 1", "schema_version = 2"),
3359                "unsupported schema_version 2",
3360            ),
3361            (
3362                VALID_CONFIG.replace("[targets.strong]", "[targets.\" strong \"]"),
3363                "target name must be non-empty and have no surrounding whitespace",
3364            ),
3365            (
3366                VALID_CONFIG.replace(
3367                    "targets = [\"strong\", \"weak\"]",
3368                    "targets = [\"strong\", \"weak\"]\ncontext_window = 0",
3369                ),
3370                "route random context_window must be greater than zero",
3371            ),
3372        ];
3373
3374        for (toml, expected) in cases {
3375            let error = AlgorithmFactory::from_toml(&toml)
3376                .and_then(|factory| factory.build())
3377                .err()
3378                .expect("invalid configuration should fail")
3379                .to_string();
3380            assert!(
3381                error.contains(expected),
3382                "expected error containing {expected}, got {error}"
3383            );
3384        }
3385    }
3386
3387    #[test]
3388    fn accepts_duplicate_target_model_ids_on_one_client() -> RunnerResult<()> {
3389        // Two targets share one model id on one client. The client keeps one and drops the
3390        // other, so the build warns and still succeeds, and both routes resolve. Serving one
3391        // model under two route names this way is allowed; pointing both routes at one target
3392        // is the tidier form.
3393        const SAME_MODEL_TWO_ROUTES: &str = r#"
3394schema_version = 1
3395
3396[llm_clients.primary]
3397format = "openai_chat"
3398base_url = "https://example.test/v1"
3399
3400[targets.fast]
3401id = "gpt-4o"
3402llm_client = "primary"
3403
3404[targets.smart]
3405id = "gpt-4o"
3406llm_client = "primary"
3407
3408[routes.fast]
3409id = "switchyard/fast"
3410type = "passthrough"
3411target = "fast"
3412
3413[routes.smart]
3414id = "switchyard/smart"
3415type = "passthrough"
3416target = "smart"
3417"#;
3418        let state = runner_from_toml(SAME_MODEL_TWO_ROUTES)?;
3419        assert_eq!(
3420            state
3421                .models()
3422                .map(|model| model.id.as_str())
3423                .collect::<Vec<_>>(),
3424            ["switchyard/fast", "switchyard/smart"]
3425        );
3426        Ok(())
3427    }
3428
3429    #[test]
3430    fn accepts_same_model_id_on_different_llm_clients() -> RunnerResult<()> {
3431        // One model may be served through different clients in separate routes.
3432        const CROSS_PROVIDER: &str = r#"
3433schema_version = 1
3434
3435[llm_clients.openai]
3436format = "openai_chat"
3437base_url = "https://example.test/v1"
3438
3439[llm_clients.azure]
3440format = "openai_chat"
3441base_url = "https://azure.test/v1"
3442
3443[targets.openai]
3444id = "gpt-4o"
3445llm_client = "openai"
3446
3447[targets.azure]
3448id = "gpt-4o"
3449llm_client = "azure"
3450
3451[routes.openai]
3452id = "switchyard/openai-gpt4o"
3453type = "passthrough"
3454target = "openai"
3455
3456[routes.azure]
3457id = "switchyard/azure-gpt4o"
3458type = "passthrough"
3459target = "azure"
3460"#;
3461        runner_from_toml(CROSS_PROVIDER)?;
3462        Ok(())
3463    }
3464
3465    #[test]
3466    fn accepts_relative_weights_and_seed() -> RunnerResult<()> {
3467        let weighted = VALID_CONFIG.replace(
3468            "targets = [\"strong\", \"weak\"]",
3469            "targets = [\"strong\", \"weak\"]\nweights = [1, 3]\nseed = 42",
3470        );
3471        runner_from_toml(&weighted)?;
3472        Ok(())
3473    }
3474
3475    #[test]
3476    fn accepts_new_session_trigger_with_message_hash_fallback() -> RunnerResult<()> {
3477        let configured = VALID_CONFIG.replace(
3478            "base_threshold = 0.5",
3479            "base_threshold = 0.25\nthreshold_step = 0.1\nclassify_trigger = \"new_session\"\nmessage_hash_fallback = true",
3480        );
3481        runner_from_toml(&configured)?;
3482        Ok(())
3483    }
3484
3485    #[test]
3486    fn target_extra_body_is_parsed_and_applied_to_its_backend() -> RunnerResult<()> {
3487        let configured = VALID_CONFIG.replacen(
3488            "llm_client = \"primary\"",
3489            "llm_client = \"primary\"\n\
3490             extra_body = { service_tier = \"priority\", \
3491             chat_template_kwargs = { enable_thinking = false } }",
3492            1,
3493        );
3494        let config: DeploymentConfig = toml::from_str(&configured).map_err(|error| {
3495            RunnerError::configuration(format!("failed to parse config: {error}"))
3496        })?;
3497        let Some(target) = config.targets.get("classifier") else {
3498            return Err(RunnerError::configuration("classifier target is missing"));
3499        };
3500        let Some(client) = config.llm_clients.get("primary") else {
3501            return Err(RunnerError::configuration("primary llm client is missing"));
3502        };
3503        let backend = build_backend(
3504            "primary",
3505            client,
3506            &target.extra_body,
3507            &target.omit_body_fields,
3508            None,
3509        )?;
3510
3511        assert_eq!(
3512            backend.extra_body().get("service_tier"),
3513            Some(&json!("priority"))
3514        );
3515        assert_eq!(
3516            backend
3517                .extra_body()
3518                .get("chat_template_kwargs")
3519                .and_then(|value| value.get("enable_thinking")),
3520            Some(&json!(false))
3521        );
3522        Ok(())
3523    }
3524
3525    #[test]
3526    fn target_omit_body_fields_is_parsed_and_applied_to_its_backend() -> RunnerResult<()> {
3527        let configured = VALID_CONFIG.replacen(
3528            "llm_client = \"primary\"",
3529            "llm_client = \"primary\"\n\
3530             omit_body_fields = [\"max_output_tokens\"]",
3531            1,
3532        );
3533        let config: DeploymentConfig = toml::from_str(&configured).map_err(|error| {
3534            RunnerError::configuration(format!("failed to parse config: {error}"))
3535        })?;
3536        let Some(target) = config.targets.get("classifier") else {
3537            return Err(RunnerError::configuration("classifier target is missing"));
3538        };
3539        let Some(client) = config.llm_clients.get("primary") else {
3540            return Err(RunnerError::configuration("primary llm client is missing"));
3541        };
3542        let backend = build_backend(
3543            "primary",
3544            client,
3545            &target.extra_body,
3546            &target.omit_body_fields,
3547            None,
3548        )?;
3549
3550        assert!(backend.omit_body_fields().contains("max_output_tokens"));
3551        Ok(())
3552    }
3553
3554    #[test]
3555    fn client_deadline_defaults_and_rejects_zero() -> RunnerResult<()> {
3556        for (setting, expected) in [
3557            ("", None),
3558            ("timeout_ms = 1500", Some(1500)),
3559            ("timeout_ms = 0", Some(0)),
3560        ] {
3561            let source = format!(
3562                "format = \"openai_chat\"\nbase_url = \"https://example.test/v1\"\n{setting}"
3563            );
3564            let config: LlmClientConfig = toml::from_str(&source).expect("valid deadline config");
3565            let backend = build_backend("test", &config, &BTreeMap::new(), &BTreeSet::new(), None);
3566            if expected == Some(0) {
3567                assert!(backend.is_err());
3568            } else {
3569                assert_eq!(backend?.timeout(), expected.map(Duration::from_millis));
3570            }
3571        }
3572        Ok(())
3573    }
3574
3575    #[test]
3576    fn retry_budget_defaults_and_accepts_an_override() -> RunnerResult<()> {
3577        let default: DeploymentConfig = toml::from_str(VALID_CONFIG).map_err(|error| {
3578            RunnerError::configuration(format!("failed to parse default config: {error}"))
3579        })?;
3580        let Some(primary) = default.llm_clients.get("primary") else {
3581            return Err(RunnerError::configuration("primary llm client is missing"));
3582        };
3583        assert_eq!(primary.max_retries, DEFAULT_MAX_RETRIES);
3584
3585        let explicit = VALID_CONFIG.replacen(
3586            "base_url = \"https://example.test/v1\"",
3587            "base_url = \"https://example.test/v1\"\nmax_retries = 0",
3588            1,
3589        );
3590        let config: DeploymentConfig = toml::from_str(&explicit).map_err(|error| {
3591            RunnerError::configuration(format!("failed to parse explicit retry config: {error}"))
3592        })?;
3593        let Some(primary) = config.llm_clients.get("primary") else {
3594            return Err(RunnerError::configuration("primary llm client is missing"));
3595        };
3596        assert_eq!(primary.max_retries, 0);
3597
3598        let maximum = VALID_CONFIG.replacen(
3599            "base_url = \"https://example.test/v1\"",
3600            &format!(
3601                "base_url = \"https://example.test/v1\"\nmax_retries = {MAX_CONFIGURED_RETRIES}"
3602            ),
3603            1,
3604        );
3605        let config: DeploymentConfig = toml::from_str(&maximum).map_err(|error| {
3606            RunnerError::configuration(format!("failed to parse maximum retry config: {error}"))
3607        })?;
3608        let Some(primary) = config.llm_clients.get("primary") else {
3609            return Err(RunnerError::configuration("primary llm client is missing"));
3610        };
3611        assert_eq!(primary.max_retries, MAX_CONFIGURED_RETRIES);
3612        Ok(())
3613    }
3614
3615    #[test]
3616    fn responses_reasoning_defaults_and_accepts_drop() -> RunnerResult<()> {
3617        let default: DeploymentConfig = toml::from_str(VALID_CONFIG).map_err(|error| {
3618            RunnerError::configuration(format!("failed to parse config: {error}"))
3619        })?;
3620        let responses = default
3621            .llm_clients
3622            .get("responses")
3623            .ok_or_else(|| RunnerError::configuration("responses llm client is missing"))?;
3624        assert_eq!(responses.responses_reasoning, None);
3625
3626        let configured = VALID_CONFIG.replacen(
3627            "[llm_clients.responses]\nformat = \"openai_responses\"\nbase_url = \"https://example.test/v1\"",
3628            "[llm_clients.responses]\nformat = \"openai_responses\"\nbase_url = \"https://example.test/v1\"\nresponses_reasoning = \"drop\"",
3629            1,
3630        );
3631        let config: DeploymentConfig = toml::from_str(&configured).map_err(|error| {
3632            RunnerError::configuration(format!("failed to parse config: {error}"))
3633        })?;
3634        let responses = config
3635            .llm_clients
3636            .get("responses")
3637            .ok_or_else(|| RunnerError::configuration("responses llm client is missing"))?;
3638        assert_eq!(
3639            responses.responses_reasoning,
3640            Some(ResponsesReasoningPolicy::Drop)
3641        );
3642        runner_from_toml(&configured)?;
3643        Ok(())
3644    }
3645
3646    #[test]
3647    fn responses_reasoning_rejects_other_formats() {
3648        let invalid = VALID_CONFIG.replacen(
3649            "format = \"openai_chat\"",
3650            "format = \"openai_chat\"\nresponses_reasoning = \"drop\"",
3651            1,
3652        );
3653        assert!(
3654            error_message(&invalid)
3655                .contains("responses_reasoning is only valid for openai_responses")
3656        );
3657    }
3658
3659    #[test]
3660    fn responses_reasoning_rejects_unreferenced_other_format() {
3661        let invalid = format!(
3662            "{VALID_CONFIG}\n[llm_clients.unused]\nformat = \"openai_chat\"\nbase_url = \"https://example.test/v1\"\nresponses_reasoning = \"drop\"\n"
3663        );
3664        assert!(
3665            error_message(&invalid)
3666                .contains("responses_reasoning is only valid for openai_responses")
3667        );
3668    }
3669
3670    #[test]
3671    fn rejects_headers_that_switchyard_sets() {
3672        let cases = [
3673            (
3674                "base_url = \"https://example.test/v1\"",
3675                "base_url = \"https://example.test/v1\"\n\
3676                 extra_headers = { AUTHORIZATION = \"Bearer custom-key\" }",
3677                "AUTHORIZATION",
3678            ),
3679            (
3680                "base_url = \"https://example.test\"",
3681                "base_url = \"https://example.test\"\n\
3682                 extra_headers = { \"X-Api-Key\" = \"custom-key\" }",
3683                "X-Api-Key",
3684            ),
3685            (
3686                "base_url = \"https://example.test\"",
3687                "base_url = \"https://example.test\"\n\
3688                 extra_headers = { \"ANTHROPIC-VERSION\" = \"custom-version\" }",
3689                "ANTHROPIC-VERSION",
3690            ),
3691        ];
3692
3693        for (original, replacement, header) in cases {
3694            let configured = VALID_CONFIG.replacen(original, replacement, 1);
3695            let error = error_message(&configured);
3696            assert!(
3697                error.contains(&format!("extra_headers cannot set {header:?}")),
3698                "expected {header} to be rejected, got: {error}"
3699            );
3700        }
3701    }
3702
3703    #[test]
3704    fn accepts_additional_headers() -> RunnerResult<()> {
3705        let configured = VALID_CONFIG.replacen(
3706            "base_url = \"https://example.test/v1\"",
3707            "base_url = \"https://example.test/v1\"\n\
3708             extra_headers = { X-Inference-Priority = \"batch\" }",
3709            1,
3710        );
3711
3712        runner_from_toml(&configured)?;
3713        Ok(())
3714    }
3715
3716    #[test]
3717    fn retry_budget_rejects_negative_values() {
3718        let invalid = VALID_CONFIG.replacen(
3719            "base_url = \"https://example.test/v1\"",
3720            "base_url = \"https://example.test/v1\"\nmax_retries = -1",
3721            1,
3722        );
3723        assert!(error_message(&invalid).contains("max_retries"));
3724    }
3725
3726    #[test]
3727    fn retry_budget_rejects_excessive_values() {
3728        let invalid = VALID_CONFIG.replacen(
3729            "base_url = \"https://example.test/v1\"",
3730            "base_url = \"https://example.test/v1\"\nmax_retries = 11",
3731            1,
3732        );
3733        assert!(
3734            error_message(&invalid).contains("llm client primary max_retries must be at most 10")
3735        );
3736    }
3737
3738    #[test]
3739    fn api_key_environment_reference_is_validated() {
3740        let missing = VALID_CONFIG.replacen(
3741            "base_url = \"https://example.test/v1\"",
3742            "base_url = \"https://example.test/v1\"\napi_key_env = \"SWITCHYARD_CONFIG_TEST_KEY_THAT_IS_NOT_SET\"",
3743            1,
3744        );
3745        assert!(error_message(&missing).contains("SWITCHYARD_CONFIG_TEST_KEY_THAT_IS_NOT_SET"));
3746
3747        const EMPTY_KEY_ENV: &str = "SWITCHYARD_CONFIG_TEST_EMPTY_KEY";
3748        unsafe {
3749            // "unsafe" is for concurrent reads and writes, very rare
3750            std::env::set_var(EMPTY_KEY_ENV, "");
3751        }
3752        let empty = VALID_CONFIG.replacen(
3753            "base_url = \"https://example.test/v1\"",
3754            &format!("base_url = \"https://example.test/v1\"\napi_key_env = \"{EMPTY_KEY_ENV}\""),
3755            1,
3756        );
3757        let message = error_message(&empty);
3758        unsafe {
3759            std::env::remove_var(EMPTY_KEY_ENV);
3760        }
3761        assert!(message.contains("is empty"));
3762
3763        // macOS reads `FOO` for the name `FOO=x`, so the config would use another variable. A
3764        // name with `=` is often a pasted `NAME=key` line, so the error leaves it out.
3765        let with_equals = VALID_CONFIG.replacen(
3766            "base_url = \"https://example.test/v1\"",
3767            "base_url = \"https://example.test/v1\"\napi_key_env = \"NVIDIA_API_KEY=DUMMY_SECRET_DO_NOT_LOG\"",
3768            1,
3769        );
3770        let message = error_message(&with_equals);
3771        assert!(message.contains("llm client primary api_key_env must not contain '=' or NUL"));
3772        assert!(!message.contains("DUMMY_SECRET_DO_NOT_LOG"), "{message}");
3773    }
3774
3775    // `VarError::NotUnicode` holds the variable's value, so printing that error prints the key.
3776    #[cfg(any(unix, windows))]
3777    #[test]
3778    fn invalid_unicode_api_key_is_not_printed() {
3779        const RAW_KEY_ENV: &str = "SWITCHYARD_CONFIG_TEST_RAW_KEY";
3780        #[cfg(unix)]
3781        let raw = {
3782            use std::os::unix::ffi::OsStringExt;
3783            let mut bytes = b"DUMMY_SECRET_DO_NOT_LOG".to_vec();
3784            bytes.push(0xff);
3785            std::ffi::OsString::from_vec(bytes)
3786        };
3787        #[cfg(windows)]
3788        let raw = {
3789            use std::os::windows::ffi::OsStringExt;
3790            let mut words: Vec<_> = "DUMMY_SECRET_DO_NOT_LOG".encode_utf16().collect();
3791            words.push(0xd800);
3792            std::ffi::OsString::from_wide(&words)
3793        };
3794        unsafe {
3795            // "unsafe" is for concurrent reads and writes, very rare
3796            std::env::set_var(RAW_KEY_ENV, raw);
3797        }
3798        let result = read_api_key("llm client fixture", RAW_KEY_ENV);
3799        unsafe {
3800            std::env::remove_var(RAW_KEY_ENV);
3801        }
3802        let error = result.expect_err("invalid Unicode credential").to_string();
3803        assert!(error.contains("not valid Unicode"), "{error}");
3804        assert!(!error.contains("DUMMY_SECRET_DO_NOT_LOG"), "{error}");
3805    }
3806
3807    #[test]
3808    fn forward_auth_rejects_conflicting_credentials() {
3809        let competing_auth = VALID_CONFIG.replacen(
3810            "base_url = \"https://example.test/v1\"",
3811            "base_url = \"https://example.test/v1\"\n\
3812                 forward_auth = true\n\
3813                 api_key_env = \"UNUSED_TEST_KEY\"",
3814            1,
3815        );
3816        assert!(
3817            error_message(&competing_auth).contains("cannot set both forward_auth and api_key_env")
3818        );
3819
3820        let static_auth = VALID_CONFIG.replacen(
3821            "base_url = \"https://example.test\"",
3822            "base_url = \"https://example.test\"\n\
3823                 forward_auth = true\n\
3824                 extra_headers = { Authorization = \"static-value\" }",
3825            1,
3826        );
3827        assert!(error_message(&static_auth).contains("extra_headers cannot set \"Authorization\""));
3828
3829        let static_beta = static_auth.replace("Authorization", "anthropic-beta");
3830        assert!(
3831            error_message(&static_beta).contains("extra_headers cannot set \"anthropic-beta\"")
3832        );
3833
3834        for header in ["chatgpt-account-id", "x-openai-fedramp"] {
3835            let static_context = VALID_CONFIG.replacen(
3836                "base_url = \"https://example.test/v1\"",
3837                &format!(
3838                    "base_url = \"https://example.test/v1\"\n\
3839                     forward_auth = true\n\
3840                     extra_headers = {{ \"{header}\" = \"static-value\" }}"
3841                ),
3842                1,
3843            );
3844            assert!(
3845                error_message(&static_context)
3846                    .contains(&format!("extra_headers cannot set \"{header}\""))
3847            );
3848        }
3849    }
3850
3851    /// Returns a config whose `mixed` route has a GPT target on a Responses client and a Claude
3852    /// target on a Messages client at `messages_url`. Its `claude` route uses Claude only.
3853    fn mixed_forwarding_config(messages_url: &str) -> String {
3854        format!(
3855            r#"
3856schema_version = 1
3857
3858[llm_clients.responses]
3859format = "openai_responses"
3860base_url = "https://gateway.example.test/v1"
3861forward_auth = true
3862
3863[llm_clients.messages]
3864format = "anthropic_messages"
3865base_url = "{messages_url}"
3866forward_auth = true
3867
3868[targets]
3869gpt = {{ id = "gpt/model", llm_client = "responses" }}
3870claude = {{ id = "claude/model", llm_client = "messages" }}
3871
3872[routes.mixed]
3873id = "switchyard/mixed"
3874type = "random"
3875targets = ["gpt", "claude"]
3876
3877[routes.claude]
3878id = "switchyard/claude"
3879type = "passthrough"
3880target = "claude"
3881"#
3882        )
3883    }
3884
3885    /// A forwarding route can mix OpenAI and Anthropic clients only when they all use the same
3886    /// scheme, host, and port.
3887    #[test]
3888    fn forwarding_route_mixes_formats_only_on_one_host() -> RunnerResult<()> {
3889        // Same host, different paths: the mixed route serves OpenAI callers, and the route that
3890        // uses only the Messages client keeps serving Messages callers.
3891        let runner = runner_from_toml(&mixed_forwarding_config("https://gateway.example.test"))?;
3892        let caller_auth = |id| runner.route(id).and_then(Route::caller_auth);
3893        assert_eq!(
3894            caller_auth("switchyard/mixed"),
3895            Some(CallerAuthKind::OpenAi)
3896        );
3897        assert_eq!(
3898            caller_auth("switchyard/claude"),
3899            Some(CallerAuthKind::Anthropic)
3900        );
3901
3902        // A different host, port, or scheme fails, and the error names it.
3903        for other in [
3904            "https://api.anthropic.test",
3905            "https://gateway.example.test:8443",
3906            "http://gateway.example.test",
3907        ] {
3908            let error = error_message(&mixed_forwarding_config(other));
3909            assert!(
3910                error.contains("different origins") && error.contains(other),
3911                "{error}"
3912            );
3913        }
3914        Ok(())
3915    }
3916
3917    const ADVISOR_CONFIG: &str = r#"
3918schema_version = 1
3919
3920[llm_clients.anthropic]
3921format = "anthropic_messages"
3922base_url = "https://example.test"
3923
3924[targets.executor]
3925id = "executor/model"
3926llm_client = "anthropic"
3927
3928[targets.advisor]
3929id = "advisor/model"
3930llm_client = "anthropic"
3931
3932[routes.gated]
3933id = "switchyard/advisor"
3934type = "advisor"
3935executor_target = "executor"
3936advisor_target = "advisor"
3937"#;
3938
3939    #[test]
3940    fn advisor_route_parses_with_defaults_and_builds() -> RunnerResult<()> {
3941        let state = runner_from_toml(ADVISOR_CONFIG)?;
3942        let route = state
3943            .route("switchyard/advisor")
3944            .expect("advisor route should exist");
3945        let models = route.models();
3946        // The gate calls the executor through `efficient`; `any` keeps it in the
3947        // route's last-resort pool.
3948        assert_eq!(
3949            models.models_for(&Category::Efficient),
3950            [ModelId::from("executor")]
3951        );
3952        assert_eq!(
3953            models.models_for(&Category::Any),
3954            [ModelId::from("executor")]
3955        );
3956        assert_eq!(
3957            models.models_for(&Category::Judge),
3958            [ModelId::from("advisor")]
3959        );
3960        assert_eq!(
3961            state
3962                .models()
3963                .map(|model| model.id.as_str())
3964                .collect::<Vec<_>>(),
3965            ["switchyard/advisor"]
3966        );
3967        Ok(())
3968    }
3969
3970    #[test]
3971    fn advisor_route_accepts_every_gate_knob() -> RunnerResult<()> {
3972        let tuned = ADVISOR_CONFIG.replace(
3973            "advisor_target = \"advisor\"",
3974            concat!(
3975                "advisor_target = \"advisor\"\n",
3976                "reviewer_system_prompt = \"review it\"\n",
3977                "redo_feedback_prefix = \"REVIEWER SAYS: \"\n",
3978                "gate_trigger = \"pattern\"\n",
3979                "gate_trigger_pattern = 'task_complete[\"\\s>:]*true'\n",
3980                "max_reviews = 2\n",
3981                "gate_stall_turns = 40\n",
3982                "gate_min_tool_results = 1\n",
3983                "advisor_max_tokens = 1024\n",
3984                "advisor_temperature = 0.0\n",
3985                "transcript_max_chars = 100000\n",
3986                "fail_open = false\n",
3987                "context_window = 200000\n",
3988                "tool_calling = true\n",
3989                "reasoning = true",
3990            ),
3991        );
3992        runner_from_toml(&tuned)?;
3993        Ok(())
3994    }
3995
3996    #[test]
3997    fn advisor_route_rejects_unknown_keys() {
3998        let invalid = ADVISOR_CONFIG.replace(
3999            "advisor_target = \"advisor\"",
4000            "advisor_target = \"advisor\"\nbogus_field = 1",
4001        );
4002        assert!(error_message(&invalid).contains("bogus_field"));
4003    }
4004
4005    #[test]
4006    fn advisor_route_requires_both_targets() {
4007        let missing = ADVISOR_CONFIG.replace("advisor_target = \"advisor\"\n", "");
4008        assert!(error_message(&missing).contains("advisor_target"));
4009    }
4010
4011    #[test]
4012    fn advisor_route_rejects_unknown_target() {
4013        let invalid = ADVISOR_CONFIG.replace(
4014            "advisor_target = \"advisor\"",
4015            "advisor_target = \"missing\"",
4016        );
4017        assert!(error_message(&invalid).contains("missing"));
4018    }
4019
4020    #[test]
4021    fn advisor_route_rejects_invalid_pattern() {
4022        let invalid = ADVISOR_CONFIG.replace(
4023            "advisor_target = \"advisor\"",
4024            "advisor_target = \"advisor\"\ngate_trigger = \"pattern\"\ngate_trigger_pattern = \"(unclosed\"",
4025        );
4026        assert!(error_message(&invalid).contains("not a valid regex"));
4027    }
4028
4029    #[test]
4030    fn advisor_route_rejects_pattern_without_pattern_trigger() {
4031        let invalid = ADVISOR_CONFIG.replace(
4032            "advisor_target = \"advisor\"",
4033            "advisor_target = \"advisor\"\ngate_trigger_pattern = \"done\"",
4034        );
4035        assert!(
4036            error_message(&invalid)
4037                .contains("gate_trigger_pattern requires gate_trigger = \"pattern\"")
4038        );
4039    }
4040
4041    #[test]
4042    fn advisor_route_pattern_trigger_requires_pattern() {
4043        let invalid = ADVISOR_CONFIG.replace(
4044            "advisor_target = \"advisor\"",
4045            "advisor_target = \"advisor\"\ngate_trigger = \"pattern\"",
4046        );
4047        assert!(error_message(&invalid).contains("non-empty gate_trigger_pattern"));
4048    }
4049
4050    #[test]
4051    fn advisor_route_rejects_zero_max_reviews() {
4052        let invalid = ADVISOR_CONFIG.replace(
4053            "advisor_target = \"advisor\"",
4054            "advisor_target = \"advisor\"\nmax_reviews = 0",
4055        );
4056        assert!(error_message(&invalid).contains("max_reviews must be at least 1"));
4057    }
4058}