diff --git a/crates/libsy-llm-client/tests/observability.rs b/crates/libsy-llm-client/tests/observability.rs index 64c8c1c96c..fd6118b6ae 100644 --- a/crates/libsy-llm-client/tests/observability.rs +++ b/crates/libsy-llm-client/tests/observability.rs @@ -1311,6 +1311,20 @@ async fn stage_router_records_algorithm_owned_metrics() -> switchyard_libsy::Res usage: Usage::default(), }) as Arc; + const STAGE_HISTOGRAMS: [&str; 6] = [ + "switchyard.stage_router.probability", + "switchyard.stage_router.confidence", + "switchyard.stage_router.severity", + "switchyard.stage_router.spinning", + "switchyard.stage_router.exploring", + "switchyard.stage_router.production_intensity", + ]; + let before = flushed_metrics(exporter, provider); + let before_counts: Vec = STAGE_HISTOGRAMS + .iter() + .map(|name| f64_histogram_count(&before, name, &[]).unwrap_or(0)) + .collect(); + let (selected_model, _) = switchyard_llm_client::run( algorithm, ClientRouter::single(client), @@ -1340,15 +1354,12 @@ async fn stage_router_records_algorithm_owned_metrics() -> switchyard_libsy::Res ), Some(1) ); - for name in [ - "switchyard.stage_router.probability", - "switchyard.stage_router.confidence", - "switchyard.stage_router.severity", - "switchyard.stage_router.spinning", - "switchyard.stage_router.exploring", - "switchyard.stage_router.production_intensity", - ] { - assert_eq!(f64_histogram_count(&snapshots, name, &[]), Some(1)); + for (name, before_count) in STAGE_HISTOGRAMS.iter().zip(before_counts) { + assert_eq!( + f64_histogram_count(&snapshots, name, &[]), + Some(before_count + 1), + "histogram {name}" + ); } Ok(()) } @@ -2633,3 +2644,139 @@ async fn target_aliases_preserve_provider_model_metric_labels() -> switchyard_li } Ok(()) } + +#[tokio::test] +async fn pool_logs_setup_and_score_without_request_text() -> switchyard_libsy::Result<()> { + let _guard = serialize_test().lock().await; + let (store, _, _, _, _) = telemetry(); + let start_idx = store.events().len(); + + const SMALL: &str = "obs-pool-small"; + const MIDDLE: &str = "obs-pool-middle"; + const LARGE: &str = "obs-pool-large"; + const SECRET_MSG: &str = "PRIVATE_POOL_USER_MARKER_98765"; + const SECRET_TOOL: &str = "PRIVATE_POOL_TOOL_MARKER_54321"; + + let pool = switchyard_libsy::TargetPool::new( + vec![ + ModelId::from(SMALL), + ModelId::from(MIDDLE), + ModelId::from(LARGE), + ], + vec![], + )?; + let models = Arc::new(RuntimeModels::new( + [ + (Category::Efficient, vec![ModelId::from(SMALL)]), + (Category::Capable, vec![ModelId::from(LARGE)]), + ( + Category::Any, + vec![ + ModelId::from(SMALL), + ModelId::from(MIDDLE), + ModelId::from(LARGE), + ], + ), + ] + .into(), + )); + let client = Arc::new(UsageClient { + usage: Usage::default(), + }) as Arc; + + let make_request = |session: &str| Request { + llm_request: LlmRequest { + model: Some("agent".to_string()), + messages: vec![ + Message::text(Role::User, SECRET_MSG), + Message::new( + Role::Assistant, + vec![ContentBlock::ToolCall(ToolCall { + id: "call_1".to_string(), + name: "Read".to_string(), + arguments: json!({"path": "README.md"}), + })], + ), + Message::new( + Role::Tool, + vec![ContentBlock::ToolResult(ToolResult { + tool_call_id: "call_1".to_string(), + content: vec![ContentBlock::Text { + text: SECRET_TOOL.to_string(), + }], + is_error: Some(false), + })], + ), + ], + ..LlmRequest::default() + }, + raw_request: None, + metadata: Some(Metadata { + wire_format: Some(WireFormat::OpenAiChat), + session_id: Some(session.to_string()), + ..Metadata::default() + }), + }; + + // Clear score at threshold 0.5 -> middle target, ambiguous = false. + let mut clear_cfg = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + clear_cfg.pool = Some(pool.clone()); + let clear_algo = Arc::new(StageRouter::new(clear_cfg)?) as Arc; + let (clear_selected, _) = switchyard_llm_client::run( + clear_algo, + ClientRouter::single(Arc::clone(&client)), + make_request("obs-pool-clear"), + Arc::clone(&models), + None, + ) + .await?; + assert_eq!(clear_selected, MIDDLE); + + // Ambiguous score at threshold 1.0 -> falls open to small, ambiguous = true. + let mut ambig_cfg = StageRouterConfig::new(PickerMode::EfficientFirst, 1.0); + ambig_cfg.pool = Some(pool); + let ambig_algo = Arc::new(StageRouter::new(ambig_cfg)?) as Arc; + let (ambig_selected, _) = switchyard_llm_client::run( + ambig_algo, + ClientRouter::single(client), + make_request("obs-pool-ambig"), + models, + None, + ) + .await?; + assert_eq!(ambig_selected, SMALL); + + let events = &store.events()[start_idx..]; + assert!( + events + .iter() + .any(|e| e.fields.get("message").map(String::as_str) + == Some("Stage target pool configured")), + "expected pool configuration log event" + ); + let score_events: Vec<_> = events + .iter() + .filter(|e| { + e.fields.get("message").map(String::as_str) == Some("Stage pool score classified") + }) + .collect(); + assert_eq!(score_events.len(), 2); + assert_eq!( + score_events[0].fields.get("ambiguous").map(String::as_str), + Some("false") + ); + assert_eq!( + score_events[1].fields.get("ambiguous").map(String::as_str), + Some("true") + ); + + for event in events { + for value in event.fields.values() { + assert!( + !value.contains(SECRET_MSG) && !value.contains(SECRET_TOOL), + "log leaked private request text: {event:?}" + ); + } + } + Ok(()) +} diff --git a/crates/libsy/src/algorithms/composite.rs b/crates/libsy/src/algorithms/composite.rs index b795cd4d84..ac10d65353 100644 --- a/crates/libsy/src/algorithms/composite.rs +++ b/crates/libsy/src/algorithms/composite.rs @@ -855,4 +855,90 @@ mod tests { } Ok(()) } + + #[tokio::test] + async fn composite_with_three_target_pool_routes_neutral_signals_to_middle() -> Result<()> { + let pool = crate::TargetPool::new( + vec![ + ModelId::from("weak"), + ModelId::from("middle"), + ModelId::from("strong"), + ], + vec![], + )?; + let mut ef = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + ef.pool = Some(pool.clone()); + let mut cf = StageRouterConfig::new(PickerMode::CapableFirst, 0.5); + cf.pool = Some(pool); + let router = Arc::new(CompositeRouter::new( + CompositeJudgeConfig::Capability(TaskClassifierConfig { + classify_trigger: ClassifyTrigger::UserTurn, + judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig::default()), + ..TaskClassifierConfig::default() + }), + ef, + cf, + )?); + let mut models = runtime_models(); + models.insert( + Category::Any, + vec![ + ModelId::from("weak"), + ModelId::from("middle"), + ModelId::from("strong"), + ], + ); + let recorder = Arc::new(Recorder::default()); + *recorder.judge_p_solve.lock() = 0.9; + + // First request is a user turn -> outer judge picks EF profile, resets signals -> fall open to weak. + let (first, _) = test_drive_with_models( + router.clone(), + user_turn_request(), + models.clone(), + recorder.serve(), + ) + .await?; + assert_eq!(first.as_str(), "weak"); + + // Second request is a neutral tool step -> pool resolves 0.5 to middle. + let (second, _) = + test_drive_with_models(router, turn_request(false), models, recorder.serve()).await?; + assert_eq!(second.as_str(), "middle"); + assert_eq!(recorder.judge_calls(), 1); + Ok(()) + } + + #[test] + fn composite_rejects_three_target_pool_with_binary_profile_fallback_at_construction() { + let pool = crate::TargetPool::new( + vec![ + ModelId::from("weak"), + ModelId::from("middle"), + ModelId::from("strong"), + ], + vec![], + ) + .unwrap(); + let mut ef = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + ef.pool = Some(pool.clone()); + let mut cf = StageRouterConfig::new(PickerMode::CapableFirst, 0.5); + cf.pool = Some(pool); + cf.llm_fallback = Some(crate::LlmFallback { + target: None, + config: TaskClassifierConfig::default(), + }); + assert!( + CompositeRouter::new( + CompositeJudgeConfig::Capability(TaskClassifierConfig { + classify_trigger: ClassifyTrigger::UserTurn, + judge: CapabilityJudgeConfig::Llm(LlmCapabilityConfig::default()), + ..TaskClassifierConfig::default() + }), + ef, + cf, + ) + .is_err() + ); + } } diff --git a/crates/libsy/src/algorithms/stage.rs b/crates/libsy/src/algorithms/stage.rs index 7b3040ec0f..21f769a11a 100644 --- a/crates/libsy/src/algorithms/stage.rs +++ b/crates/libsy/src/algorithms/stage.rs @@ -18,13 +18,16 @@ use std::sync::Arc; use async_trait::async_trait; use super::fall_through::FallThrough; -use super::llm_class::{LlmClassifierConfig, LlmTaskClassifier, TaskClassifierConfig}; +use super::llm_class::{ + CustomClassifierConfig, LlmClassifierConfig, LlmTaskClassifier, TaskClassifierConfig, +}; use super::util::affinity::{ClassifyTrigger, has_new_user_turn}; use super::util::cache_aware::CacheAware; use super::util::stage::{ DecisionSource, HandoffNoteConfig, PickerMode, StageClassifier, Tier, fall_open_tier, record_routing_decision, }; +use super::util::target_pool::TargetPool; use super::util::tool_signals::{DEFAULT_RECENT_WINDOW, ToolSemantics, ToolSignalProcessor}; use crate::core::algorithm::{Algorithm, Driver}; use crate::core::classifier::{Classification, Classifier, Score}; @@ -78,6 +81,7 @@ struct SourceStamp { source: DecisionSource, judge: Option, skip_user_turn: bool, + pool: Option, } #[async_trait] @@ -96,13 +100,27 @@ impl Classifier for SourceStamp { .as_ref() .map(|judge| driver.for_judge(judge.clone())); let driver = scoped.as_ref().unwrap_or(driver); - let (classification, served) = self.inner.score(state, request, driver).await?; + let (mut classification, served) = self.inner.score(state, request, driver).await?; // An abstaining classifier passes the turn on, so it is not its to claim. - if let Some(winner) = classification.argmax(false)? { + if let Some(mut winner) = classification.argmax(false)? { + if let Some(pool) = &self.pool { + if !pool.contains(&winner.target) { + return Err(LibsyError::AlgorithmError { + message: format!( + "classifier selected target {} outside the target pool", + winner.target + ), + }); + } + winner.category = pool.category_for(&winner.target); + } record_routing_decision(self.source, driver.provider_model(&winner.target)); driver.set_evidence_if_empty(serde_json::json!({ "source": self.source.as_str(), })); + if self.pool.is_some() { + classification = Classification::Scores(vec![winner]); + } } Ok((classification, served)) } @@ -151,10 +169,27 @@ pub struct LlmFallback { pub config: TaskClassifierConfig, } +/// Categorical JSON Schema judge for pools with more than two targets. +/// +/// The judge's target-selector policy looks up the chosen label as a named +/// category in [`crate::RuntimeModels`]. When using labels `target_0` through +/// `target_{n-1}`, runtime models must map `Category::Named("target_{i}")` to +/// `pool.targets()[i]`. +pub struct CategoricalFallback { + /// Overrides the runtime judge for this stage configuration. + pub target: Option, + /// Custom schema and target-selector contract. + pub config: CustomClassifierConfig, + /// Whether judge call errors fall open to the picker default. + pub fail_open: bool, +} + /// How a stage router scores turns, and what it hands the model it picks. pub struct StageRouterConfig { /// Optional capable and efficient targets for this stage profile. pub tier_targets: Option<[switchyard_protocol::ModelId; 2]>, + /// Optional ordered target pool for multi-target score resolution. + pub pool: Option, /// Tier a turn falls open to when the scorer is not confident. pub mode: PickerMode, /// How much corroboration a decisive pick needs, in `[0.0, 1.0]`. @@ -189,6 +224,8 @@ pub struct StageRouterConfig { /// Capability judge consulted on turns the signals leave undecided. It uses /// the runtime judge model and the standalone capability route's settings. pub llm_fallback: Option, + /// Categorical JSON Schema judge consulted on undecided turns for N-target pools. + pub categorical_fallback: Option, } impl StageRouterConfig { @@ -198,6 +235,7 @@ impl StageRouterConfig { Self { mode, tier_targets: None, + pool: None, confidence_threshold, cache_aware: false, max_switch_cost_overhead: 0.10, @@ -211,6 +249,7 @@ impl StageRouterConfig { capable_system_prompt: None, efficient_system_prompt: None, llm_fallback: None, + categorical_fallback: None, } } } @@ -261,23 +300,71 @@ impl Algorithm for StageRouter { } } +fn reject_fallback_retention( + classify_trigger: ClassifyTrigger, + message_hash_fallback: bool, +) -> Result<()> { + if classify_trigger != ClassifyTrigger::EveryRequest || message_hash_fallback { + return Err(LibsyError::AlgorithmError { + message: "classify_trigger and message_hash_fallback have no effect on the \ + stage fallback judge, which runs on every ambiguous turn. Remove \ + them, or use a composite route to judge once per user turn" + .to_string(), + }); + } + Ok(()) +} + /// Wires the cascade the wrapper drives. Exposed so a composition above can /// stack a prelude onto it. pub(crate) fn build_stage_route( config: StageRouterConfig, reset_on_user_turn: bool, ) -> Result { - if let Some(fallback) = &config.llm_fallback - && (fallback.config.classify_trigger != ClassifyTrigger::EveryRequest - || fallback.config.message_hash_fallback) + if config.pool.is_some() && config.tier_targets.is_some() { + return Err(LibsyError::AlgorithmError { + message: "tier target overrides cannot be combined with a target pool".to_string(), + }); + } + if config.llm_fallback.is_some() && config.categorical_fallback.is_some() { + return Err(LibsyError::AlgorithmError { + message: "configure only one stage fallback judge".to_string(), + }); + } + if config.categorical_fallback.is_some() + && !config + .pool + .as_ref() + .is_some_and(|pool| pool.target_count() > 2) { return Err(LibsyError::AlgorithmError { - message: "classify_trigger and message_hash_fallback have no effect on the \ - stage fallback judge, which runs on every ambiguous turn. Remove \ - them, or use a composite route to judge once per user turn" + message: "categorical stage fallback requires a target pool with more than 2 targets" .to_string(), }); } + if let Some(pool) = &config.pool + && pool.target_count() > 2 + && config.llm_fallback.is_some() + { + return Err(LibsyError::AlgorithmError { + message: format!( + "binary stage fallback supports at most 2 pool targets, but {} are configured; use a categorical fallback", + pool.target_count() + ), + }); + } + if let Some(fallback) = &config.llm_fallback { + reject_fallback_retention( + fallback.config.classify_trigger, + fallback.config.message_hash_fallback, + )?; + } + if let Some(fallback) = &config.categorical_fallback { + reject_fallback_retention( + fallback.config.classify_trigger, + fallback.config.message_hash_fallback, + )?; + } for (name, threshold) in [ ("confidence_threshold", config.confidence_threshold), ("max_switch_cost_overhead", config.max_switch_cost_overhead), @@ -316,6 +403,10 @@ pub(crate) fn build_stage_route( classifier.cache_aware = Some(CacheAware::new(config.max_switch_cost_overhead)?); } classifier.tier_targets = config.tier_targets; + if let Some(pool) = config.pool.clone() { + tracing::debug!(pool = ?pool, "Stage target pool configured"); + classifier = classifier.with_pool(pool); + } if let Some(turns) = config.efficient_hold_turns { classifier = classifier.with_efficient_hold_turns(turns); } @@ -339,6 +430,15 @@ pub(crate) fn build_stage_route( source: DecisionSource::LlmClassifier, judge: fallback.target, skip_user_turn: reset_on_user_turn, + pool: config.pool, + })); + } else if let Some(fallback) = config.categorical_fallback { + router = router.with_classifier(Arc::new(SourceStamp { + inner: LlmTaskClassifier::custom_classifier(&fallback.config, fallback.fail_open)?, + source: DecisionSource::LlmClassifier, + judge: fallback.target, + skip_user_turn: reset_on_user_turn, + pool: config.pool, })); } // Nothing behind this, so no turn is left unrouted. @@ -347,6 +447,7 @@ pub(crate) fn build_stage_route( source: DecisionSource::FallOpen, judge: None, skip_user_turn: false, + pool: None, })); if config.capable_system_prompt.is_some() || config.efficient_system_prompt.is_some() { router = router.with_processor(Arc::new(TierPromptProcessor { @@ -416,6 +517,7 @@ mod tests { source: DecisionSource::LlmClassifier, judge: None, skip_user_turn: false, + pool: None, }; let (driver, mut rx) = Driver::new("test", Arc::new(crate::RuntimeModels::default())); stamp @@ -1190,4 +1292,330 @@ mod tests { ); Ok(()) } + + fn pool_models() -> HashMap> { + [ + (Category::Judge, vec![ModelId::from(JUDGE)]), + (Category::Efficient, vec![ModelId::from("weak")]), + (Category::Capable, vec![ModelId::from("strong")]), + ( + Category::Any, + vec![ + ModelId::from("weak"), + ModelId::from("middle"), + ModelId::from("strong"), + ], + ), + ( + Category::Named("target_0".into()), + vec![ModelId::from("weak")], + ), + ( + Category::Named("target_1".into()), + vec![ModelId::from("middle")], + ), + ( + Category::Named("target_2".into()), + vec![ModelId::from("strong")], + ), + ] + .into() + } + + fn three_target_pool() -> TargetPool { + TargetPool::new( + vec![ + ModelId::from("weak"), + ModelId::from("middle"), + ModelId::from("strong"), + ], + vec![], + ) + .expect("valid 3-target pool") + } + + fn categorical_fallback_config() -> CustomClassifierConfig { + CustomClassifierConfig::new( + "Choose target_0, target_1, or target_2.", + serde_json::json!({ + "type": "object", + "additionalProperties": false, + "properties": { + "target": { + "type": "string", + "enum": ["target_0", "target_1", "target_2"] + }, + "reason": { "type": "string" } + }, + "required": ["target", "reason"] + }), + crate::CustomClassifierPolicy::target_selector("/target"), + ) + } + + fn first_instruction(outcome: &crate::RoutingOutcome) -> Option<&str> { + outcome + .request + .llm_request + .instructions + .first() + .and_then(|block| block.content.first()) + .and_then(|block| match block { + switchyard_protocol::ContentBlock::Text { text } => Some(text.as_str()), + _ => None, + }) + } + + #[tokio::test] + async fn three_target_pool_routes_intermediate_overrides_holds_and_prompts() -> Result<()> { + let recorder = Arc::new(Recorder::default()); + let mut config = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + config.pool = Some(three_target_pool()); + config.capable_hold_turns = 2; + config.capable_system_prompt = Some("CAPABLE PROMPT".to_string()); + config.efficient_system_prompt = Some("EFFICIENT PROMPT".to_string()); + let router = Arc::new(StageRouter::new(config)?); + + // Turn 1: neutral signal -> middle (intermediate, no endpoint prompt). + // Turn 2: hard failure -> strong (override, capable prompt, arms 2-turn hold). + // Turns 3-4: held on strong. + // Turn 5: hold expired, neutral signal -> middle again. + let turns = [ + (false, "middle", None), + (true, "strong", Some("CAPABLE PROMPT")), + (false, "strong", Some("CAPABLE PROMPT")), + (false, "strong", Some("CAPABLE PROMPT")), + (false, "middle", None), + ]; + for (failed, expected_target, expected_prompt) in turns { + let outcome = crate::core::testing::test_drive_with_state( + router.clone(), + turn_request(failed), + pool_models(), + State::default(), + recorder.serve(), + ) + .await?; + let selected = outcome.selected_model_id()?.clone(); + assert_eq!(selected.as_str(), expected_target); + assert_eq!( + first_instruction(&outcome), + expected_prompt, + "target={expected_target}" + ); + } + Ok(()) + } + + #[tokio::test] + async fn categorical_fallback_normalizes_endpoints_and_keeps_intermediate_category_none() + -> Result<()> { + for (choice, expected_target, expected_prompt) in [ + ("target_0", "weak", Some("EFFICIENT PROMPT")), + ("target_1", "middle", None), + ("target_2", "strong", Some("CAPABLE PROMPT")), + ] { + let mut config = StageRouterConfig::new(PickerMode::EfficientFirst, 1.0); + config.pool = Some(three_target_pool()); + config.capable_hold_turns = 0; + config.capable_system_prompt = Some("CAPABLE PROMPT".to_string()); + config.efficient_system_prompt = Some("EFFICIENT PROMPT".to_string()); + config.categorical_fallback = Some(CategoricalFallback { + target: Some(ModelId::from(JUDGE)), + config: categorical_fallback_config(), + fail_open: false, + }); + let router = Arc::new(StageRouter::new(config)?); + let serve = move |target: ModelId, _request: Request| async move { + if target == JUDGE { + return Ok(crate::core::testing::reply( + serde_json::json!({ + "target": choice, + "reason": "picked" + }) + .to_string(), + )); + } + Ok(crate::core::testing::reply(target.to_string())) + }; + + let outcome = crate::core::testing::test_drive_with_state( + router, + turn_request(false), + pool_models(), + State::default(), + serve, + ) + .await?; + let selected = outcome.selected_model_id()?.clone(); + assert_eq!(selected.as_str(), expected_target); + assert_eq!( + first_instruction(&outcome), + expected_prompt, + "choice={choice}" + ); + } + Ok(()) + } + + #[tokio::test] + async fn source_stamp_rejects_target_outside_pool() { + let stamp = SourceStamp { + inner: Arc::new(Fixed("outsider")), + source: DecisionSource::LlmClassifier, + judge: None, + skip_user_turn: false, + pool: Some(three_target_pool()), + }; + let (driver, _rx) = Driver::new("test", Arc::new(crate::RuntimeModels::default())); + let Err(err) = stamp + .score(&mut State::default(), &mut Request::default(), &driver) + .await + else { + panic!("out-of-pool target must return an error"); + }; + let msg = err.to_string(); + assert!( + msg.contains("outsider") && msg.contains("outside the target pool"), + "unexpected error: {msg}" + ); + } + + #[tokio::test] + async fn pool_endpoints_must_match_runtime_tier_targets() -> Result<()> { + let mut cfg = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + cfg.pool = Some(three_target_pool()); + let router = Arc::new(StageRouter::new(cfg)?); + let mut models = pool_models(); + // Swap Capable and Efficient so they disagree with pool endpoints. + models.insert(Category::Efficient, vec![ModelId::from("strong")]); + models.insert(Category::Capable, vec![ModelId::from("weak")]); + let recorder = Arc::new(Recorder::default()); + let Err(err) = + test_drive_with_models(router, turn_request(false), models, recorder.serve()).await + else { + panic!("mismatched pool endpoints must fail"); + }; + assert!(err.to_string().contains("pool endpoints must match")); + Ok(()) + } + + #[test] + fn rejects_invalid_pool_and_fallback_combinations() { + let expect_err = |cfg: StageRouterConfig, expected: &str| { + let Err(err) = StageRouter::new(cfg) else { + panic!("expected error containing {expected:?}"); + }; + assert!( + err.to_string().contains(expected), + "expected {expected:?} in {err}" + ); + }; + + // pool + tier_targets + let mut cfg = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + cfg.pool = Some(three_target_pool()); + cfg.tier_targets = Some([ModelId::from("strong"), ModelId::from("weak")]); + expect_err( + cfg, + "tier target overrides cannot be combined with a target pool", + ); + + // both fallbacks set + let mut cfg = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + cfg.llm_fallback = Some(LlmFallback { + target: None, + config: TaskClassifierConfig::default(), + }); + cfg.categorical_fallback = Some(CategoricalFallback { + target: None, + config: categorical_fallback_config(), + fail_open: true, + }); + expect_err(cfg, "configure only one stage fallback judge"); + + // categorical_fallback requires a pool with more than 2 targets + let mut cfg = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + cfg.categorical_fallback = Some(CategoricalFallback { + target: None, + config: categorical_fallback_config(), + fail_open: true, + }); + expect_err( + cfg, + "categorical stage fallback requires a target pool with more than 2 targets", + ); + + let mut cfg = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + cfg.pool = Some( + TargetPool::new(vec![ModelId::from("weak"), ModelId::from("strong")], vec![]).unwrap(), + ); + cfg.categorical_fallback = Some(CategoricalFallback { + target: None, + config: categorical_fallback_config(), + fail_open: true, + }); + expect_err( + cfg, + "categorical stage fallback requires a target pool with more than 2 targets", + ); + + // N > 2 pool + binary llm_fallback + let mut cfg = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + cfg.pool = Some(three_target_pool()); + cfg.llm_fallback = Some(LlmFallback { + target: None, + config: TaskClassifierConfig::default(), + }); + expect_err(cfg, "binary stage fallback supports at most 2 pool targets"); + + // categorical_fallback retention settings rejected + let mut cfg = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + cfg.pool = Some(three_target_pool()); + let mut custom = categorical_fallback_config(); + custom.classify_trigger = ClassifyTrigger::UserTurn; + cfg.categorical_fallback = Some(CategoricalFallback { + target: None, + config: custom, + fail_open: true, + }); + expect_err(cfg, "have no effect on the stage fallback judge"); + + // invalid custom contracts (blank prompt, invalid schema, bad selector) + for (bad_config, expected) in [ + ( + CustomClassifierConfig::new( + " ", + serde_json::json!({"type": "object"}), + crate::CustomClassifierPolicy::target_selector("/target"), + ), + "classifier prompt must not be empty", + ), + ( + CustomClassifierConfig::new( + "pick", + serde_json::json!({"json_schema": {}}), + crate::CustomClassifierPolicy::target_selector("/target"), + ), + "response_schema must be the inner JSON Schema", + ), + ( + CustomClassifierConfig::new( + "pick", + serde_json::json!({"type": "object"}), + crate::CustomClassifierPolicy::target_selector("no-leading-slash"), + ), + "valid JSON Pointer", + ), + ] { + let mut cfg = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5); + cfg.pool = Some(three_target_pool()); + cfg.categorical_fallback = Some(CategoricalFallback { + target: None, + config: bad_config, + fail_open: true, + }); + expect_err(cfg, expected); + } + } } diff --git a/crates/libsy/src/algorithms/util.rs b/crates/libsy/src/algorithms/util.rs index 17dcbf6b6d..750f106cc9 100644 --- a/crates/libsy/src/algorithms/util.rs +++ b/crates/libsy/src/algorithms/util.rs @@ -11,6 +11,7 @@ pub(crate) mod prompts; pub(crate) mod robustness; pub(crate) mod stage; pub mod subagent; +pub(crate) mod target_pool; pub(crate) mod target_selector; #[cfg(test)] pub(crate) mod tier_fixtures; diff --git a/crates/libsy/src/algorithms/util/stage.rs b/crates/libsy/src/algorithms/util/stage.rs index 9c0c0d97d0..fce066a19a 100644 --- a/crates/libsy/src/algorithms/util/stage.rs +++ b/crates/libsy/src/algorithms/util/stage.rs @@ -24,13 +24,14 @@ use serde::Deserialize; use super::affinity::has_new_user_turn; use super::cache_aware::CacheAware; use super::prompts::append_note; +use super::target_pool::TargetPool; use super::tool_signals::{ToolSignalProcessor, ToolSignals}; -use crate::Result; use crate::core::algorithm::Driver; use crate::core::classifier::{Classification, Classifier, Score}; use crate::core::processor::{Event, Processor}; use crate::core::state::{State, StateValue}; use crate::observability::meter; +use crate::{LibsyError, Result}; use switchyard_protocol::{Category, Request}; /// Turn depth below which stall signals stay quiet — early no-write turns are @@ -58,6 +59,7 @@ const SEVERITY_CRITICAL: f32 = 1.0; const CAPABLE_HOLD_KEY: &str = "capable_hold_turns"; const EFFICIENT_HOLD_KEY: &str = "efficient_hold_turns"; const PREVIOUS_TIER_KEY: &str = "stage_previous_tier"; +const INTERMEDIATE_TIER_LABEL: &str = "intermediate"; /// Counts final stage-router choices by decision source and semantic target. const ROUTING_DECISIONS_METRIC: &str = "switchyard.stage_router.routing_decisions"; @@ -285,23 +287,7 @@ pub(crate) fn record_routing_decision(source: DecisionSource, target_name: &str) } /// Records the scorer's bounded inputs and output as six explicit histograms. -fn record_score_metrics(signal: &ToolSignals, outcome: &PickOutcome) { - let (probability, confidence) = match outcome { - PickOutcome::Resolved { - probability, - confidence, - .. - } => ( - *probability, - // Distance from 0.5, doubled onto [0, 1] — probability's `score.abs()`. - confidence.unwrap_or_else(|| 2.0 * (probability - 0.5).abs()), - ), - PickOutcome::ConsultClassifier { - probability, - confidence, - .. - } => (*probability, *confidence), - }; +fn record_score_metrics(signal: &ToolSignals, probability: f64, confidence: f64) { let dimensions = dimensions_from_signal(signal); let meter = meter(); for (name, value, boundaries) in [ @@ -536,6 +522,7 @@ pub struct StageClassifier { pub(crate) reset_on_user_turn: bool, pub(crate) cache_aware: Option, pub(crate) tier_targets: Option<[switchyard_protocol::ModelId; 2]>, + pool: Option, signals: ToolSignalProcessor, handoff_notes: Option, } @@ -554,11 +541,18 @@ impl StageClassifier { reset_on_user_turn: false, cache_aware: None, tier_targets: None, + pool: None, signals: ToolSignalProcessor::default(), handoff_notes: None, } } + /// Resolves clear non-override scores across an ordered target pool. + pub fn with_pool(mut self, pool: TargetPool) -> Self { + self.pool = Some(pool); + self + } + /// Threshold used when an outer classifier selects capable-first. pub fn with_capable_first_threshold(mut self, threshold: f64) -> Self { self.capable_first_threshold = threshold; @@ -610,6 +604,25 @@ impl StageClassifier { self.handoff_notes.as_ref()?.note_for(tier, source) } + fn record_handoff_note( + &self, + state: &mut State, + request: &mut Request, + target: &switchyard_protocol::ModelId, + tier: Tier, + source: DecisionSource, + ) { + let Some(note) = self.handoff_note(tier, source) else { + return; + }; + if self.cache_aware.is_some() { + // Price the original prompt before adding the final target's note. + state.pick_note = Some((target.clone(), note.to_owned())); + } else { + append_note(&mut request.llm_request, note); + } + } + fn agent_key(request: &Request, key: &str) -> String { request .metadata @@ -672,6 +685,20 @@ impl Processor for StageClassifier { if let Some(pair) = &self.tier_targets { driver.select_tier_targets(pair)?; } + if let Some(pool) = &self.pool { + pool.validate_targets(driver.models_for(&Category::Any))?; + let efficient = driver.first_model_for(&Category::Efficient)?; + let capable = driver.first_model_for(&Category::Capable)?; + if pool.targets().first() != Some(efficient) + || pool.targets().last() != Some(capable) + { + return Err(LibsyError::AlgorithmError { + message: format!( + "pool endpoints must match runtime efficient ({efficient}) and capable ({capable}) targets" + ), + }); + } + } if self.reset_on_user_turn && has_new_user_turn(&request.llm_request.messages) { for key in [CAPABLE_HOLD_KEY, EFFICIENT_HOLD_KEY, PREVIOUS_TIER_KEY] { state.extra.remove(&Self::agent_key(request, key)); @@ -722,7 +749,18 @@ impl Processor for StageClassifier { } }), ), - _ => return Ok(()), + _ => { + if self.pool.is_some() { + state.extra.insert( + Self::agent_key(request, PREVIOUS_TIER_KEY), + StateValue::String(INTERMEDIATE_TIER_LABEL.to_string()), + ); + for key in [CAPABLE_HOLD_KEY, EFFICIENT_HOLD_KEY] { + state.extra.remove(&Self::agent_key(request, key)); + } + } + return Ok(()); + } }; // A cost veto can cancel the capable hold set during scoring even // when the final tier matches the previous turn. @@ -787,8 +825,80 @@ impl Classifier for StageClassifier { Some(Tier::Efficient) => (PickerMode::EfficientFirst, self.confidence_threshold), None => (self.mode, self.confidence_threshold), }; + if let Some(pool) = &self.pool + && override_reason(&signal).is_none() + { + let value = score_signal(&signal).probability(); + let confidence = pool.confidence(value)?; + let clear = pool.is_clear(value, threshold)?; + tracing::debug!( + score = value, + confidence, + threshold, + ambiguous = !clear, + "Stage pool score classified" + ); + record_score_metrics(&signal, value, confidence); + if !clear { + return Ok((Self::abstain(), None)); + } + let target = pool.resolve(value)?.clone(); + let category = pool.category_for(&target); + record_routing_decision(DecisionSource::Dimensions, driver.provider_model(&target)); + driver.set_evidence(serde_json::json!({ + "source": DecisionSource::Dimensions.as_str(), + "score": value, + "confidence": confidence, + "threshold": threshold, + })); + if category == Some(Category::Capable) { + if self.capable_hold_turns > 0 { + Self::set_hold(state, &capable_hold_key, self.capable_hold_turns); + } + self.record_handoff_note( + state, + request, + &target, + Tier::Capable, + DecisionSource::Dimensions, + ); + } else if category == Some(Category::Efficient) { + self.record_handoff_note( + state, + request, + &target, + Tier::Efficient, + DecisionSource::Dimensions, + ); + } + return Ok(( + Classification::Scores(vec![Score { + target, + confidence, + category, + target_locked: false, + }]), + None, + )); + } let outcome = pick_tier(&signal, mode, threshold); - record_score_metrics(&signal, &outcome); + let (probability, confidence) = match &outcome { + PickOutcome::Resolved { + probability, + confidence, + .. + } => ( + *probability, + // Distance from 0.5, doubled onto [0, 1] — probability's `score.abs()`. + confidence.unwrap_or_else(|| 2.0 * (probability - 0.5).abs()), + ), + PickOutcome::ConsultClassifier { + probability, + confidence, + .. + } => (*probability, *confidence), + }; + record_score_metrics(&signal, probability, confidence); match outcome { PickOutcome::Resolved { tier, @@ -824,14 +934,7 @@ impl Classifier for StageClassifier { // Only a resolved turn routes on this classifier's target, so it // is the only branch whose tier the signals actually chose — an // ambiguous turn is decided further down the cascade. - if let Some(note) = self.handoff_note(tier, source) { - if self.cache_aware.is_some() { - // Price the original prompt before adding the final target's note. - state.pick_note = Some((target.clone(), note.to_owned())); - } else { - append_note(&mut request.llm_request, note); - } - } + self.record_handoff_note(state, request, target, tier, source); let evidence = match (source, confidence) { (DecisionSource::Dimensions, Some(confidence)) => serde_json::json!({ "source": source.as_str(), diff --git a/crates/libsy/src/algorithms/util/target_pool.rs b/crates/libsy/src/algorithms/util/target_pool.rs new file mode 100644 index 0000000000..949f25548b --- /dev/null +++ b/crates/libsy/src/algorithms/util/target_pool.rs @@ -0,0 +1,417 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Ordered score pool mapping `[0.0, 1.0]` signals onto `N >= 2` targets. + +use std::collections::HashSet; + +use switchyard_protocol::{Category, ModelId}; + +use crate::{LibsyError, Result}; + +/// Ordered completion targets partitioning `[0.0, 1.0]`, from efficient (`0.0`) +/// to capable (`1.0`). +#[derive(Clone, Debug, PartialEq)] +pub struct TargetPool { + targets: Vec, + anchors: Vec, + boundaries: Vec, +} + +impl TargetPool { + /// Creates a target pool ordered from efficient (`0.0`) to capable (`1.0`). + /// + /// Pass an empty `positions` vector to split `[0.0, 1.0]` into equal `1 / N` + /// bands so every target has the same clear width at any threshold. + pub fn new(targets: Vec, positions: Vec) -> Result { + if targets.is_empty() { + return Err(LibsyError::NoTargets); + } + if targets.len() < 2 { + return Err(LibsyError::AlgorithmError { + message: "pool needs at least two targets".to_string(), + }); + } + let mut seen = HashSet::with_capacity(targets.len()); + if !targets.iter().all(|target| seen.insert(target)) { + return Err(LibsyError::AlgorithmError { + message: "pool targets must be distinct".to_string(), + }); + } + let (anchors, boundaries) = if positions.is_empty() { + let count = targets.len(); + let count_f = count as f64; + let boundaries = (0..=count) + .map(|i| if i == count { 1.0 } else { i as f64 / count_f }) + .collect(); + let anchors = (0..count) + .map(|i| { + if i == 0 { + 0.0 + } else if i == count - 1 { + 1.0 + } else { + (i as f64 + 0.5) / count_f + } + }) + .collect(); + (anchors, boundaries) + } else { + validate_positions(&positions, targets.len())?; + let mut boundaries = Vec::with_capacity(positions.len() + 1); + boundaries.push(0.0); + for pair in positions.windows(2) { + boundaries.push((pair[0] + pair[1]) / 2.0); + } + boundaries.push(1.0); + (positions, boundaries) + }; + Ok(Self { + targets, + anchors, + boundaries, + }) + } + + /// Returns the number of targets in the pool. + pub fn target_count(&self) -> usize { + self.targets.len() + } + + /// Returns the ordered pool targets, from efficient to capable. + pub fn targets(&self) -> &[ModelId] { + &self.targets + } + + /// Returns how far `value` sits from its nearest cell boundary toward its + /// target anchor, normalized to `[0.0, 1.0]`. + pub fn confidence(&self, value: f64) -> Result { + validate_unit_value("score", value)?; + let index = self.cell_index(value); + let anchor = self.anchors[index]; + if value == anchor { + return Ok(1.0); + } + let score = if value < anchor { + let lo = self.boundaries[index]; + (value - lo) / (anchor - lo) + } else { + let hi = self.boundaries[index + 1]; + (hi - value) / (hi - anchor) + }; + Ok(score.clamp(0.0, 1.0)) + } + + /// Returns `true` when `value` falls outside every boundary's ambiguity band + /// for `threshold`. + pub fn is_clear(&self, value: f64, threshold: f64) -> Result { + validate_unit_value("score", value)?; + validate_unit_value("threshold", threshold)?; + if threshold == 1.0 { + return Ok(false); + } + if self.anchors.contains(&value) { + return Ok(true); + } + let ambiguous = (0..self.targets.len() - 1).any(|index| { + let boundary = self.boundaries[index + 1]; + let left_half = threshold * (boundary - self.anchors[index]); + let right_half = threshold * (self.anchors[index + 1] - boundary); + value >= boundary - left_half && value <= boundary + right_half + }); + Ok(!ambiguous) + } + + /// Resolves `value` to the target whose cell contains it. Boundary ties go + /// to the lower target. + pub fn resolve(&self, value: f64) -> Result<&ModelId> { + validate_unit_value("score", value)?; + Ok(&self.targets[self.cell_index(value)]) + } + + fn cell_index(&self, value: f64) -> usize { + self.boundaries[1..self.targets.len()] + .iter() + .take_while(|&&boundary| value > boundary) + .count() + } + + pub(crate) fn contains(&self, target: &ModelId) -> bool { + self.targets.contains(target) + } + + pub(crate) fn category_for(&self, target: &ModelId) -> Option { + if self.targets.first() == Some(target) { + Some(Category::Efficient) + } else if self.targets.last() == Some(target) { + Some(Category::Capable) + } else { + None + } + } + + pub(crate) fn validate_targets(&self, available: &[ModelId]) -> Result<()> { + let available: HashSet<&ModelId> = available.iter().collect(); + for target in &self.targets { + if !available.contains(target) { + return Err(LibsyError::TargetNotFound { + target: target.clone(), + }); + } + } + Ok(()) + } +} + +fn validate_positions(positions: &[f64], expected_len: usize) -> Result<()> { + let invalid = || LibsyError::AlgorithmError { + message: + "pool positions must match targets, increase with distinct midpoints, and span 0 to 1" + .to_string(), + }; + if positions.len() != expected_len { + return Err(invalid()); + } + if positions + .iter() + .any(|p| !p.is_finite() || !(0.0..=1.0).contains(p)) + { + return Err(invalid()); + } + if positions[0] != 0.0 || positions[expected_len - 1] != 1.0 { + return Err(invalid()); + } + if !positions.windows(2).all(|pair| { + let midpoint = (pair[0] + pair[1]) / 2.0; + pair[0] < midpoint && midpoint < pair[1] + }) { + return Err(invalid()); + } + Ok(()) +} + +fn validate_unit_value(name: &str, value: f64) -> Result<()> { + if !value.is_finite() || !(0.0..=1.0).contains(&value) { + return Err(LibsyError::AlgorithmError { + message: format!("{name} must be finite and between 0 and 1, got {value}"), + }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ids(names: &[&str]) -> Vec { + names.iter().map(|name| ModelId::from(*name)).collect() + } + + #[test] + fn resolves_three_target_anchors_and_confidence() { + let pool = TargetPool::new(ids(&["small", "medium", "large"]), vec![0.0, 0.4, 1.0]) + .expect("valid pool"); + assert_eq!(pool.target_count(), 3); + assert_eq!( + pool.category_for(&ModelId::from("small")), + Some(Category::Efficient) + ); + assert_eq!(pool.category_for(&ModelId::from("medium")), None); + assert_eq!( + pool.category_for(&ModelId::from("large")), + Some(Category::Capable) + ); + + let cases = [ + (0.0, "small", 1.0), + (0.2, "small", 0.0), + (0.4, "medium", 1.0), + (0.7, "medium", 0.0), + (1.0, "large", 1.0), + ]; + for (value, expected_target, expected_conf) in cases { + assert_eq!( + pool.resolve(value).expect("valid score"), + &ModelId::from(expected_target), + "score={value}" + ); + let conf = pool.confidence(value).expect("valid confidence"); + assert!( + (conf - expected_conf).abs() < 1e-12, + "score={value}: expected {expected_conf}, got {conf}" + ); + } + assert_eq!( + pool.resolve(0.200_001).expect("just above midpoint"), + &ModelId::from("medium") + ); + assert_eq!( + pool.resolve(0.700_001).expect("just above midpoint"), + &ModelId::from("large") + ); + } + + #[test] + fn omits_positions_for_equal_bands() { + let pool = TargetPool::new(ids(&["a", "b", "c", "d"]), vec![]).expect("even pool"); + // Boundaries at 0.25, 0.50, 0.75; ties resolve to the lower target. + for (value, expected) in [ + (0.0, "a"), + (0.25, "a"), + (0.250_001, "b"), + (0.375, "b"), + (0.5, "b"), + (0.500_001, "c"), + (0.625, "c"), + (0.75, "c"), + (0.750_001, "d"), + (1.0, "d"), + ] { + assert_eq!( + pool.resolve(value).unwrap(), + &ModelId::from(expected), + "score={value}" + ); + } + + // At threshold = 0.5, every target has clear width (1 - 0.5) / 4 = 0.125: + // a: [0.0, 0.125), b: (0.3125, 0.4375), c: (0.5625, 0.6875), d: (0.875, 1.0]. + for (value, expected_clear) in [ + (0.0, true), + (0.124, true), + (0.125, false), + (0.3125, false), + (0.313, true), + (0.375, true), + (0.437, true), + (0.4375, false), + (0.5625, false), + (0.563, true), + (0.625, true), + (0.687, true), + (0.6875, false), + (0.875, false), + (0.876, true), + (0.8808, true), + (1.0, true), + ] { + assert_eq!( + pool.is_clear(value, 0.5).unwrap(), + expected_clear, + "score={value}" + ); + } + + // Confidence is 1.0 at anchors (0.0, 0.375, 0.625, 1.0) and 0.0 at boundaries. + for (value, expected_conf) in [ + (0.0, 1.0), + (0.125, 0.5), + (0.25, 0.0), + (0.3125, 0.5), + (0.375, 1.0), + (0.4375, 0.5), + (0.5, 0.0), + (0.625, 1.0), + (0.75, 0.0), + (0.875, 0.5), + (1.0, 1.0), + ] { + let conf = pool.confidence(value).unwrap(); + assert!( + (conf - expected_conf).abs() < 1e-12, + "score={value}: expected {expected_conf}, got {conf}" + ); + } + } + + #[test] + fn equal_clear_band_widths_for_default_pools() { + for n in 2..=5 { + let names: Vec = (0..n).map(|i| format!("t{i}")).collect(); + let models: Vec = names.iter().map(|s| ModelId::from(s.as_str())).collect(); + let pool = TargetPool::new(models.clone(), vec![]).expect("valid default pool"); + let samples = 40_000usize; + for threshold in [0.0, 0.2, 0.5, 0.8] { + let mut counts = vec![0usize; n]; + for step in 0..samples { + // Sample bin centers across [0, 1] to measure each clear region's width. + let value = (step as f64 + 0.5) / samples as f64; + if pool.is_clear(value, threshold).unwrap() { + let target = pool.resolve(value).unwrap(); + let idx = models.iter().position(|m| m == target).unwrap(); + counts[idx] += 1; + } + } + let expected = (1.0 - threshold) / n as f64; + for (idx, count) in counts.iter().enumerate() { + let measured = *count as f64 / samples as f64; + assert!( + (measured - expected).abs() < 1e-3, + "n={n}, threshold={threshold}, target={idx}: expected width {expected}, measured {measured}" + ); + } + } + } + } + + #[test] + fn rejects_invalid_inputs() { + assert!(matches!( + TargetPool::new(vec![], vec![]), + Err(LibsyError::NoTargets) + )); + assert!(TargetPool::new(ids(&["only"]), vec![]).is_err()); + assert!(TargetPool::new(ids(&["dup", "dup"]), vec![]).is_err()); + assert!(TargetPool::new(ids(&["a", "b"]), vec![0.0, 0.5, 1.0]).is_err()); + assert!(TargetPool::new(ids(&["a", "b"]), vec![0.1, 1.0]).is_err()); + assert!(TargetPool::new(ids(&["a", "b"]), vec![0.0, 0.9]).is_err()); + assert!(TargetPool::new(ids(&["a", "b", "c"]), vec![0.0, f64::NAN, 1.0]).is_err()); + assert!(TargetPool::new(ids(&["a", "b", "c"]), vec![0.0, 1.5, 1.0]).is_err()); + assert!(TargetPool::new(ids(&["a", "b", "c"]), vec![0.0, 0.5, 0.5]).is_err()); + assert!(TargetPool::new(ids(&["a", "b", "c"]), vec![0.0, 0.0, 1.0]).is_err()); + // Adjacent floats with no distinct midpoint between them. + let tiny = 1.0_f64 - f64::EPSILON / 2.0; + assert!(TargetPool::new(ids(&["a", "b", "c"]), vec![0.0, tiny, 1.0]).is_err()); + + let pool = TargetPool::new(ids(&["small", "large"]), vec![]).unwrap(); + for bad in [-0.01, 1.01, f64::NAN, f64::INFINITY] { + assert!(pool.resolve(bad).is_err()); + assert!(pool.confidence(bad).is_err()); + assert!(pool.is_clear(bad, 0.5).is_err()); + assert!(pool.is_clear(0.5, bad).is_err()); + } + } + + #[test] + fn two_target_pool_matches_stage_ambiguity_band() { + let pool = TargetPool::new(ids(&["small", "large"]), vec![]).expect("2-target pool"); + for threshold in [0.0, 0.2, 0.5, 1.0] { + for step in 0..=1000 { + let p = step as f64 / 1000.0; + let expected = if threshold == 1.0 { + false + } else { + p < 0.5 - threshold / 2.0 || p > 0.5 + threshold / 2.0 + }; + assert_eq!( + pool.is_clear(p, threshold).expect("valid"), + expected, + "p={p}, threshold={threshold}" + ); + } + } + let three = TargetPool::new(ids(&["s", "m", "l"]), vec![0.0, 0.4, 1.0]).unwrap(); + for anchor in [0.0, 0.4, 1.0] { + assert!(!three.is_clear(anchor, 1.0).unwrap()); + } + } + + #[test] + fn exact_anchors_stay_clear_below_threshold_one() { + let pool = TargetPool::new(ids(&["s", "m", "l"]), vec![0.0, 0.5, 1.0]).unwrap(); + let almost_one = 0.9999999999999999_f64; + assert!(almost_one < 1.0); + assert!(pool.is_clear(0.5, almost_one).unwrap()); + assert!(!pool.is_clear(0.5, 1.0).unwrap()); + } +} diff --git a/crates/libsy/src/lib.rs b/crates/libsy/src/lib.rs index 01a5e2ea4a..74de34d12c 100644 --- a/crates/libsy/src/lib.rs +++ b/crates/libsy/src/lib.rs @@ -29,7 +29,7 @@ pub use algorithms::llm_class::{ pub use algorithms::noop::Noop; pub use algorithms::passthrough::Passthrough; pub use algorithms::rand::{Random, RandomClassifier}; -pub use algorithms::stage::{LlmFallback, StageRouter, StageRouterConfig}; +pub use algorithms::stage::{CategoricalFallback, LlmFallback, StageRouter, StageRouterConfig}; pub use algorithms::subagent::{SubagentRouter, SubagentRouterConfig}; pub use algorithms::util::affinity::{AffinityRouter, ClassifyTrigger}; pub use algorithms::util::classifier_contract::{ @@ -38,6 +38,7 @@ pub use algorithms::util::classifier_contract::{ pub use algorithms::util::escalation::{DeescalationConfig, EscalationJudgeConfig}; pub use algorithms::util::prompts::prepend_system_prompt; pub use algorithms::util::subagent::{SubagentGate, SubagentOverride}; +pub use algorithms::util::target_pool::TargetPool; pub use algorithms::util::tool_signals::{DEFAULT_RECENT_WINDOW, ToolSemantics, ToolSignals}; pub use algorithms::vgr::{ ACTIVE_APPROVAL, BreakerConfig, KillSwitch, ServingMode, Targets as VgrTargets, Vgr, VgrConfig, diff --git a/crates/switchyard-runner/src/algorithm.rs b/crates/switchyard-runner/src/algorithm.rs index 8015bb1ea0..1757ae8a62 100644 --- a/crates/switchyard-runner/src/algorithm.rs +++ b/crates/switchyard-runner/src/algorithm.rs @@ -11,13 +11,13 @@ use std::sync::Arc; use libsy::{ AdvisorGate, AdvisorGateConfig, Algorithm, BreakerConfig, CapabilityJudgeConfig, - ClassifierContractConfig, ClassifierResponseFormat, ClassifyTrigger, CompositeJudgeConfig, - CompositeRouter, CustomClassifierConfig, CustomClassifierPolicy, DEFAULT_UNMATCHED_STEPS, - DecisionChoice, DecisionJudgeConfig, DirectClassifierConfig, EscalationJudgeConfig, - GateTrigger, HandoffNoteConfig, LlmCapabilityConfig, LlmClassifierConfig, LlmFallback, - LlmTaskClassifier, Noop, Passthrough, PickerMode, Random, RuntimeModels, StageRouter, - StageRouterConfig, SubagentRouter, SubagentRouterConfig, TaskClassifierConfig, ToolSemantics, - Vgr, VgrConfig, + CategoricalFallback, ClassifierContractConfig, ClassifierResponseFormat, ClassifyTrigger, + CompositeJudgeConfig, CompositeRouter, CustomClassifierConfig, CustomClassifierPolicy, + DEFAULT_UNMATCHED_STEPS, DecisionChoice, DecisionJudgeConfig, DirectClassifierConfig, + EscalationJudgeConfig, GateTrigger, HandoffNoteConfig, LlmCapabilityConfig, + LlmClassifierConfig, LlmFallback, LlmTaskClassifier, Noop, Passthrough, PickerMode, Random, + RuntimeModels, StageRouter, StageRouterConfig, SubagentRouter, SubagentRouterConfig, + TargetPool, TaskClassifierConfig, ToolSemantics, Vgr, VgrConfig, }; use serde::Deserialize; use strum_macros::IntoStaticStr; @@ -434,6 +434,9 @@ pub enum AlgorithmSpec { settings: StageSettingsConfig, /// Tier to use when the signals are not confident. picker: PickerMode, + /// Ordered score pool for routing across two or more targets. + #[serde(default)] + pool: Option, /// Judge consulted for turns the tool signals cannot decide. #[serde(default)] classifier: Option, @@ -655,6 +658,15 @@ pub struct StageClassifierConfig { const COMPOSITE_PLANNING_PROMPT: &str = "You are in the planning phase. Inspect the task and the relevant code, then form a concrete implementation plan before modifying any files. Use read-only tools as needed. Do not make an edit until the plan is complete. After completing the plan, immediately make the first edit in the same task to hand execution off. Do not finish or return a final response with only the plan."; +/// A fixed score line. Omitted positions split `[0.0, 1.0]` into equal bands. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TargetPoolConfig { + pub targets: Vec, + #[serde(default)] + pub positions: Vec, +} + /// The shared model pair and defaults for composite stage profiles. #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] @@ -663,6 +675,8 @@ pub struct StageTierConfig { pub efficient_target: String, #[serde(default)] pub capable_first_threshold: f64, + #[serde(default)] + pub pool: Option, #[serde(flatten)] pub settings: StageSettingsConfig, } @@ -839,6 +853,25 @@ impl StageClassifierConfig { } } + fn attach_stage_fallback( + &self, + config: &mut StageRouterConfig, + route_name: &str, + pool: Option<&TargetPoolConfig>, + capable: &str, + efficient: &str, + targets: &BTreeMap, + ) -> AlgorithmResult<()> { + if let Some(pool_cfg) = pool.filter(|p| p.targets.len() > 2) { + config.categorical_fallback = + Some(self.pool_classifier_config(route_name, pool_cfg, targets)?); + } else { + config.llm_fallback = + Some(self.stage_fallback(route_name, capable, efficient, targets)?); + } + Ok(()) + } + fn stage_fallback( &self, route_name: &str, @@ -852,6 +885,81 @@ impl StageClassifierConfig { }) } + fn pool_classifier_config( + &self, + route_name: &str, + pool: &TargetPoolConfig, + targets: &BTreeMap, + ) -> AlgorithmResult { + if self.decision.is_some() + || self.base_threshold.is_some() + || self.threshold_step.is_some() + || self.response_schema.is_some() + || self.policy.is_some() + || self.mode.is_some() + || self.response_format_type != ClassifierResponseFormat::JsonSchema + { + return Err(AlgorithmConfigError::new( + "N-target stage uses a categorical JSON Schema judge; binary decision settings and custom schemas are unsupported", + )); + } + let intro = match &self.prompt { + Some(prompt) => { + let trimmed = prompt.trim(); + if trimmed.is_empty() { + return Err(AlgorithmConfigError::new( + "classifier prompt must not be empty", + )); + } + trimmed + } + None => "Route the agent's next turn using its task and current progress.", + }; + let choices: Vec = (0..pool.targets.len()) + .map(|i| format!("target_{i}")) + .collect(); + let options = pool + .targets + .iter() + .enumerate() + .map(|(i, name)| format!("target_{i}: {name}")) + .collect::>() + .join("\n"); + let prompt = format!( + "{intro}\nChoose one target for the next agent turn. Targets are ordered from efficient to capable. Choose the least costly target that can reliably do the remaining work. Return JSON with target and reason.\n{options}" + ); + let schema = serde_json::json!({ + "type": "object", + "additionalProperties": false, + "properties": { + "target": { + "type": "string", + "enum": choices, + }, + "reason": { + "type": "string", + }, + }, + "required": ["target", "reason"], + }); + let mut config = CustomClassifierConfig::new( + prompt, + schema, + CustomClassifierPolicy::target_selector("/target"), + ); + config.classify_trigger = self.classify_trigger; + config.message_hash_fallback = self.message_hash_fallback; + config.recent_turn_window = self.recent_turn_window; + config.judge_max_images = self.judge_max_images; + config.max_output_tokens = self.max_output_tokens; + config.judge_deadline_ms = self.judge_deadline_ms; + Ok(CategoricalFallback { + target: Some(resolve_target_model_id(route_name, &self.target, targets)?), + config, + fail_open: self.fail_open.unwrap_or(true), + }) + } + fn custom_classifier_config( &self, route_name: &str, @@ -1101,10 +1209,14 @@ impl AlgorithmSpec { Self::StageRouter { capable_target, efficient_target, + pool, subagents, .. } => { - let mut names = vec![capable_target.as_str(), efficient_target.as_str()]; + let mut names = match pool { + Some(pool) => pool.targets.iter().map(String::as_str).collect(), + None => vec![capable_target.as_str(), efficient_target.as_str()], + }; if let Some(subagents) = subagents { names.extend(subagents.routing_target_names()); } @@ -1117,10 +1229,13 @@ impl AlgorithmSpec { Self::Composite { stage, subagents, .. } => { - let mut names = vec![ - stage.capable_target.as_str(), - stage.efficient_target.as_str(), - ]; + let mut names = match &stage.pool { + Some(pool) => pool.targets.iter().map(String::as_str).collect(), + None => vec![ + stage.capable_target.as_str(), + stage.efficient_target.as_str(), + ], + }; names.extend(self.profile_targets().map(String::as_str)); if let Some(subagents) = subagents { names.extend(subagents.routing_target_names()); @@ -1222,17 +1337,20 @@ impl AlgorithmSpec { Self::StageRouter { capable_target, efficient_target, + pool, classifier, .. } => { + let any_targets = match pool { + Some(pool) => pool.targets.clone(), + None => vec![capable_target.clone(), efficient_target.clone()], + }; let mut models = category_models([ (Category::Capable, vec![capable_target.clone()]), (Category::Efficient, vec![efficient_target.clone()]), - ( - Category::Any, - vec![capable_target.clone(), efficient_target.clone()], - ), + (Category::Any, any_targets), ]); + insert_pool_categories(&mut models, pool.as_ref()); if let Some(classifier) = classifier { models.insert(Category::Judge, vec![classifier.target.clone()]); } @@ -1249,24 +1367,29 @@ impl AlgorithmSpec { vec![capable_target.clone(), efficient_target.clone()], ), ]), - Self::Composite { stage, .. } => category_models([ - ( - Category::Judge, - self.judge_target_names() - .into_iter() - .map(str::to_string) - .collect(), - ), - (Category::Capable, vec![stage.capable_target.clone()]), - (Category::Efficient, vec![stage.efficient_target.clone()]), - ( - Category::Any, - [stage.capable_target.clone(), stage.efficient_target.clone()] - .into_iter() - .chain(self.profile_targets().cloned()) - .collect(), - ), - ]), + Self::Composite { stage, .. } => { + let any_targets: Vec = match &stage.pool { + Some(pool) => pool.targets.clone(), + None => vec![stage.capable_target.clone(), stage.efficient_target.clone()], + } + .into_iter() + .chain(self.profile_targets().cloned()) + .collect(); + let mut models = category_models([ + ( + Category::Judge, + self.judge_target_names() + .into_iter() + .map(str::to_string) + .collect(), + ), + (Category::Capable, vec![stage.capable_target.clone()]), + (Category::Efficient, vec![stage.efficient_target.clone()]), + (Category::Any, any_targets), + ]); + insert_pool_categories(&mut models, stage.pool.as_ref()); + models + } Self::Advisor { executor_target, advisor_target, @@ -1977,9 +2100,9 @@ fn build_algorithm( max_switch_cost_overhead, settings, picker, + pool, classifier, subagents, - .. } => { if matches!(picker, PickerMode::CapableFirst) { tracing::warn!( @@ -1992,20 +2115,33 @@ fn build_algorithm( "stage_router route {route_name}: confidence_threshold is required" )) })?; + let resolved_pool = resolve_pool( + "stage_router", + route_name, + pool.as_ref(), + capable_target, + efficient_target, + targets, + )?; let mut config = settings.stage_config(settings, *picker, threshold); config.cache_aware = *cache_aware; if let Some(limit) = max_switch_cost_overhead { config.max_switch_cost_overhead = *limit; } config.capable_first_threshold = *capable_first_threshold; + config.pool = resolved_pool; // The judge is called through its own target, so it is not a routing // destination and stays out of the tier pair. - config.llm_fallback = classifier - .as_ref() - .map(|classifier| { - classifier.stage_fallback(route_name, capable_target, efficient_target, targets) - }) - .transpose()?; + if let Some(classifier) = classifier { + classifier.attach_stage_fallback( + &mut config, + route_name, + pool.as_ref(), + capable_target, + efficient_target, + targets, + )?; + } let algorithm = StageRouter::new(config).map_err(|error| { AlgorithmConfigError::with_source( format!("stage_router route {route_name}: {error}"), @@ -2043,6 +2179,19 @@ fn build_algorithm( &stage.efficient_target, )?; let has_overrides = config.profile_targets().next().is_some(); + if stage.pool.is_some() && has_overrides { + return Err(AlgorithmConfigError::new(format!( + "composite route {route_name}: stage.pool cannot be combined with profile capable_target or efficient_target" + ))); + } + let resolved_pool = resolve_pool( + "composite", + route_name, + stage.pool.as_ref(), + &stage.capable_target, + &stage.efficient_target, + targets, + )?; let defaults = StageProfileConfig::default(); let profiles = [ (efficient, PickerMode::EfficientFirst), @@ -2051,6 +2200,7 @@ fn build_algorithm( .map(|(profile, picker)| -> AlgorithmResult<_> { let profile = profile.as_deref().unwrap_or(&defaults); let mut config = stage.profile_config(profile, picker); + config.pool = resolved_pool.clone(); let [capable, efficient] = [ (&profile.capable_target, &stage.capable_target), (&profile.efficient_target, &stage.efficient_target), @@ -2062,13 +2212,16 @@ fn build_algorithm( resolve_target_model_id(route_name, efficient, targets)?, ]); } - config.llm_fallback = profile - .classifier - .as_ref() - .map(|classifier| { - classifier.stage_fallback(route_name, capable, efficient, targets) - }) - .transpose()?; + if let Some(classifier) = &profile.classifier { + classifier.attach_stage_fallback( + &mut config, + route_name, + stage.pool.as_ref(), + capable, + efficient, + targets, + )?; + } Ok(config) }); let [profile_0, profile_1] = profiles; @@ -2314,6 +2467,56 @@ fn resolve_target_model_id( }) } +fn insert_pool_categories( + models: &mut HashMap>, + pool: Option<&TargetPoolConfig>, +) { + if let Some(pool) = pool + && pool.targets.len() > 2 + { + for (i, target) in pool.targets.iter().enumerate() { + models.insert( + Category::Named(format!("target_{i}").into()), + vec![target.clone()], + ); + } + } +} + +fn resolve_pool( + route_kind: &str, + route_name: &str, + pool: Option<&TargetPoolConfig>, + capable: &str, + efficient: &str, + targets: &BTreeMap, +) -> AlgorithmResult> { + let Some(pool) = pool else { + return Ok(None); + }; + if pool.targets.len() < 2 + || pool.targets.first().map(String::as_str) != Some(efficient) + || pool.targets.last().map(String::as_str) != Some(capable) + { + return Err(AlgorithmConfigError::new(format!( + "{route_kind} route {route_name}: pool needs at least two targets, ordered from efficient_target to capable_target" + ))); + } + let ids = pool + .targets + .iter() + .map(|name| resolve_target_model_id(route_name, name, targets)) + .collect::>>()?; + TargetPool::new(ids, pool.positions.clone()) + .map(Some) + .map_err(|error| { + AlgorithmConfigError::with_source( + format!("{route_kind} route {route_name}: {error}"), + error, + ) + }) +} + fn resolve_runtime_models( route_name: &str, names: HashMap>, diff --git a/crates/switchyard-runner/src/config.rs b/crates/switchyard-runner/src/config.rs index d4a412467f..8b26c3ba2e 100644 --- a/crates/switchyard-runner/src/config.rs +++ b/crates/switchyard-runner/src/config.rs @@ -220,23 +220,35 @@ fn callable_targets(algorithm: &AlgorithmSpec) -> BTreeSet<&str> { algorithm.callable_target_names().into_iter().collect() } -fn check_random_targets( +fn check_distinct_pool_targets( algorithm: &AlgorithmSpec, targets: &LaneTargets<'_>, has_overrides: bool, ) -> RunnerResult<()> { - if matches!(algorithm, AlgorithmSpec::Random { .. }) && has_overrides { - let mut models = BTreeSet::new(); - for name in algorithm.routing_target_names() { - let target = targets[name].name; - if !models.insert(target) { - return Err(LlmClientError::InvalidRequest { - message: format!( - "random route alternatives map multiple pool entries to target {target}; use distinct targets" - ), - } - .into()); + if !has_overrides { + return Ok(()); + } + let (kind, pool_names): (&str, &[String]) = match algorithm { + AlgorithmSpec::Random { targets, .. } => ("random", targets), + AlgorithmSpec::StageRouter { + pool: Some(pool), .. + } => ("stage_router", &pool.targets), + AlgorithmSpec::Composite { stage, .. } => match &stage.pool { + Some(pool) => ("composite", &pool.targets), + None => return Ok(()), + }, + _ => return Ok(()), + }; + let mut models = BTreeSet::new(); + for name in pool_names { + let target = targets[name.as_str()].name; + if !models.insert(target) { + return Err(LlmClientError::InvalidRequest { + message: format!( + "{kind} route alternatives map multiple pool entries to target {target}; use distinct targets" + ), } + .into()); } } Ok(()) @@ -305,7 +317,7 @@ impl EligibleLanes { let targets = self .deployment .resolve_lane_targets(&algorithm, &overrides)?; - check_random_targets( + check_distinct_pool_targets( &algorithm, &targets, key.iter().any(|(name, target)| name != target), @@ -570,7 +582,7 @@ impl DeploymentConfig { .map(|(name, target)| (name.as_str(), target.as_str())) .collect(); let targets = self.resolve_lane_targets(&algorithm, &overrides)?; - check_random_targets( + check_distinct_pool_targets( &algorithm, &targets, bindings.iter().any(|(name, target)| name != target), diff --git a/crates/switchyard-runner/tests/stage_knobs.rs b/crates/switchyard-runner/tests/stage_knobs.rs index d660eab1c7..60fd01b975 100644 --- a/crates/switchyard-runner/tests/stage_knobs.rs +++ b/crates/switchyard-runner/tests/stage_knobs.rs @@ -58,3 +58,142 @@ fn rejects_classifier_knobs_that_have_no_effect() { ); } } + +const FOUR_TARGET_BASE: &str = r#" +schema_version = 1 +[llm_clients.local] +format = "openai_chat" +base_url = "http://127.0.0.1:1/v1" +[targets.small] +id = "small-model" +llm_client = "local" +[targets.medium_a] +id = "medium-a-model" +llm_client = "local" +[targets.medium_b] +id = "medium-b-model" +llm_client = "local" +[targets.large] +id = "large-model" +llm_client = "local" +[targets.judge] +id = "judge-model" +llm_client = "local" +[routes.stage] +id = "stage" +type = "stage_router" +capable_target = "large" +efficient_target = "small" +picker = "efficient_first" +confidence_threshold = 0.5 +"#; + +#[test] +fn accepts_valid_two_and_four_target_pools() { + let two = format!("{CONFIG}[routes.stage.pool]\ntargets = [\"fast\", \"strong\"]\n"); + assert!(Runner::from_toml(&two).is_ok()); + + let four_even = format!( + "{FOUR_TARGET_BASE}[routes.stage.pool]\ntargets = [\"small\", \"medium_a\", \"medium_b\", \"large\"]\n" + ); + assert!(Runner::from_toml(&four_even).is_ok()); + + let four_explicit = format!( + "{FOUR_TARGET_BASE}[routes.stage.pool]\ntargets = [\"small\", \"medium_a\", \"medium_b\", \"large\"]\npositions = [0.0, 0.2, 0.8, 1.0]\n" + ); + assert!(Runner::from_toml(&four_explicit).is_ok()); + + let four_with_judge = format!("{four_explicit}[routes.stage.classifier]\ntarget = \"judge\"\n"); + assert!(Runner::from_toml(&four_with_judge).is_ok()); +} + +#[test] +fn rejects_invalid_stage_pools() { + let cases = [ + // count mismatch + "targets = [\"small\", \"medium_a\", \"large\"]\npositions = [0.0, 1.0]\n", + // wrong endpoints + "targets = [\"medium_a\", \"medium_b\", \"large\"]\n", + "targets = [\"small\", \"medium_a\", \"medium_b\"]\n", + // missing target + "targets = [\"small\", \"missing\", \"large\"]\n", + // fewer than two targets (empty) + "targets = []\n", + ]; + for pool in cases { + let config = format!("{FOUR_TARGET_BASE}[routes.stage.pool]\n{pool}"); + assert!( + Runner::from_toml(&config).is_err(), + "expected error for pool:\n{pool}" + ); + } +} + +#[test] +fn rejects_invalid_n_target_stage_classifier_settings() { + let base = format!( + "{FOUR_TARGET_BASE}[routes.stage.pool]\ntargets = [\"small\", \"medium_a\", \"medium_b\", \"large\"]\n[routes.stage.classifier]\ntarget = \"judge\"\n" + ); + for setting in [ + "base_threshold = 0.5", + "prompt = \" \"", + "response_format_type = \"json_object\"", + ] { + let config = format!("{base}{setting}\n"); + assert!( + Runner::from_toml(&config).is_err(), + "expected error for classifier setting: {setting}" + ); + } + + let missing_judge = format!( + "{FOUR_TARGET_BASE}[routes.stage.pool]\ntargets = [\"small\", \"medium_a\", \"medium_b\", \"large\"]\n[routes.stage.classifier]\ntarget = \"missing_judge\"\n" + ); + assert!(Runner::from_toml(&missing_judge).is_err()); +} + +#[test] +fn composite_stage_pool_loads_and_rejects_profile_target_overrides() { + let base = r#" +schema_version = 1 +[llm_clients.local] +format = "openai_chat" +base_url = "http://127.0.0.1:1/v1" +[targets.small] +id = "small-model" +llm_client = "local" +[targets.medium] +id = "medium-model" +llm_client = "local" +[targets.large] +id = "large-model" +llm_client = "local" +[targets.judge] +id = "judge-model" +llm_client = "local" +[routes.comp] +id = "comp" +type = "composite" +[routes.comp.classifier] +target = "judge" +base_threshold = 0.5 +classify_trigger = "user_turn" +[routes.comp.stage] +capable_target = "large" +efficient_target = "small" +[routes.comp.stage.pool] +targets = ["small", "medium", "large"] +"#; + assert!(Runner::from_toml(base).is_ok()); + + for override_block in [ + "[routes.comp.capable]\ncapable_target = \"large\"\n", + "[routes.comp.efficient]\nefficient_target = \"small\"\n", + ] { + let error = load_error(&format!("{base}{override_block}")); + assert!( + error.contains("stage.pool cannot be combined with profile"), + "{override_block}: {error}" + ); + } +} diff --git a/crates/switchyard-runner/tests/stage_pool.rs b/crates/switchyard-runner/tests/stage_pool.rs new file mode 100644 index 0000000000..3c3431fafa --- /dev/null +++ b/crates/switchyard-runner/tests/stage_pool.rs @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! End-to-end tests for N-target Stage pools with the generated categorical judge. + +use serde_json::{Value, json}; +use switchyard_protocol::{Request, text_request}; +use switchyard_runner::Runner; +use wiremock::matchers::{body_partial_json, method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +fn chat_completion(model: &str, content: &str) -> Value { + json!({ + "id": "response", + "object": "chat.completion", + "model": model, + "choices": [{ + "index": 0, + "message": { "role": "assistant", "content": content }, + "finish_reason": "stop" + }] + }) +} + +fn config_for(base_url: &str) -> String { + format!( + r#" +schema_version = 1 + +[llm_clients.local] +format = "openai_chat" +base_url = "{base_url}/v1" +max_retries = 0 + +[targets.small] +id = "small" +llm_client = "local" + +[targets.medium_a] +id = "medium_a" +llm_client = "local" + +[targets.medium_b] +id = "medium_b" +llm_client = "local" + +[targets.large] +id = "large" +llm_client = "local" + +[targets.judge] +id = "judge" +llm_client = "local" + +[routes.agent] +id = "agent" +type = "stage_router" +efficient_target = "small" +capable_target = "large" +picker = "efficient_first" +confidence_threshold = 1.0 +capable_hold_turns = 0 + +[routes.agent.pool] +targets = ["small", "medium_a", "medium_b", "large"] +positions = [0.0, 0.2, 0.8, 1.0] + +[routes.agent.classifier] +target = "judge" +"# + ) +} + +#[tokio::test] +async fn four_target_stage_pool_routes_valid_verdicts_and_falls_open_on_invalid_verdicts() +-> Result<(), Box> { + let cases = [ + (r#"{"target":"target_0","reason":"trivial"}"#, "small"), + (r#"{"target":"target_1","reason":"simple"}"#, "medium_a"), + (r#"{"target":"target_2","reason":"moderate"}"#, "medium_b"), + (r#"{"target":"target_3","reason":"hard"}"#, "large"), + // Invalid verdicts fall open to the efficient_first picker default (`small`). + (r#"{"target":"unknown","reason":"bad enum"}"#, "small"), + ("not json at all", "small"), + ]; + + for (verdict, expected_target) in cases { + let server = MockServer::start().await; + let runner = Runner::from_toml(&config_for(&server.uri()))?; + + Mock::given(method("POST")) + .and(path("/v1/chat/completions")) + .and(body_partial_json(json!({ "model": "judge" }))) + .and(|request: &wiremock::Request| { + let body: Value = request.body_json().expect("valid JSON judge request"); + body["response_format"]["json_schema"]["schema"]["properties"]["target"]["enum"] + == json!(["target_0", "target_1", "target_2", "target_3"]) + }) + .respond_with( + ResponseTemplate::new(200).set_body_json(chat_completion("judge", verdict)), + ) + .expect(1) + .mount(&server) + .await; + + Mock::given(method("POST")) + .and(path("/v1/chat/completions")) + .and(body_partial_json(json!({ "model": expected_target }))) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(chat_completion(expected_target, expected_target)), + ) + .expect(1) + .mount(&server) + .await; + + let route = runner.route("agent").expect("configured route"); + let outcome = route + .execute( + Request { + llm_request: text_request(None, "Help with the build"), + ..Default::default() + }, + None, + ) + .await?; + + assert_eq!( + outcome.selected_model.as_str(), + expected_target, + "verdict={verdict}" + ); + server.verify().await; + } + + Ok(()) +} diff --git a/crates/switchyard-runner/tests/target_eligibility.rs b/crates/switchyard-runner/tests/target_eligibility.rs index 566a4d03e3..aea0f45632 100644 --- a/crates/switchyard-runner/tests/target_eligibility.rs +++ b/crates/switchyard-runner/tests/target_eligibility.rs @@ -686,3 +686,79 @@ labels = ["private", "customer_data"] primary.verify().await; approved.verify().await; } + +#[tokio::test] +async fn stage_pool_eligibility_collision_is_an_invalid_request() { + let server = MockServer::start().await; + + // Duplicate entries in the original pool remain a configuration error at load. + let dup_algorithm = r#" +type = "stage_router" +efficient_target = "fast" +capable_target = "capable" +picker = "efficient_first" +confidence_threshold = 0.5 +[routes.chat.pool] +targets = ["fast", "fast", "capable"] +"#; + let dup_err = match Runner::from_toml(&config(&server.uri(), dup_algorithm, "")) { + Ok(_) => panic!("duplicate pool entries must fail at load"), + Err(err) => err, + }; + assert!( + matches!(dup_err, RunnerError::Configuration { .. }), + "expected configuration error, got {dup_err:?}" + ); + + // A valid pool whose eligibility alternatives collapse two entries onto one target + // works for standard requests and rejects the colliding request as InvalidRequest. + let algorithm = r#" +type = "stage_router" +efficient_target = "fast" +capable_target = "capable" +picker = "efficient_first" +confidence_threshold = 0.5 +[routes.chat.pool] +targets = ["fast", "private_fast", "capable"] +"#; + let policy = r#" +target_alternatives = { fast = ["both_fast"], private_fast = ["both_fast"], capable = ["both_capable"] } +"#; + let runner = + Runner::from_toml(&config(&server.uri(), algorithm, policy)).expect("valid stage pool"); + respond( + &server, + "private/fast", + completion("private/fast", "standard answer"), + 1, + ) + .await; + + let route = runner.route("chat").expect("route"); + let standard = route + .execute(request("standard", None), None) + .await + .expect("standard request uses original pool"); + assert_eq!(standard.selected_model, "private_fast"); + + let err = match route + .execute( + request("collision", Some(&["private", "customer_data"])), + None, + ) + .await + { + Ok(_) => panic!("colliding alternatives must fail"), + Err(err) => err, + }; + assert!( + matches!( + err, + RunnerError::Client(LlmClientError::InvalidRequest { ref message }) + if message.contains("multiple pool entries") && message.contains("both_fast") + ), + "expected InvalidRequest for pool collision, got {err:?}" + ); + assert_eq!(models_called(&server).await, ["private/fast"]); + server.verify().await; +} diff --git a/dev-server/config.toml b/dev-server/config.toml index a2eb4a5400..73a8c6a622 100644 --- a/dev-server/config.toml +++ b/dev-server/config.toml @@ -35,6 +35,14 @@ llm_client = "openrouter" id = "openai/gpt-6-luna" llm_client = "openrouter" +[targets.terra] +id = "openai/gpt-6.1-terra" +llm_client = "openrouter" + +[targets.sol] +id = "openai/gpt-6.2-sol" +llm_client = "openrouter" + [targets.astra] id = "openai/gpt-6.2-astra" llm_client = "openrouter" @@ -81,6 +89,26 @@ target = "classifier" classify_trigger = "user_turn" fail_open = true +[routes.auto-openai-pool] +id = "switchyard/auto-openai-pool" +type = "composite" +vision = true + +[routes.auto-openai-pool.stage] +capable_target = "astra" +efficient_target = "luna" +# Shrink the ambiguous band between pool models to a single point +efficient_first_threshold = 0.0 +capable_first_threshold = 0.2 + +[routes.auto-openai-pool.stage.pool] +targets = ["luna", "terra", "sol", "astra"] + +[routes.auto-openai-pool.classifier] +target = "classifier" +classify_trigger = "user_turn" +fail_open = false + # The algos [routes.random] diff --git a/docs/reference/toml_schema.md b/docs/reference/toml_schema.md index 273d37f8f2..e3db524579 100644 --- a/docs/reference/toml_schema.md +++ b/docs/reference/toml_schema.md @@ -476,6 +476,7 @@ the signals work and for tuning. | `capable_target` | Yes | — | Capable tier. | | `efficient_target` | Yes | — | Efficient tier. | | `picker` | Yes | — | `efficient_first`, or `capable_first` (experimental, unbenchmarked). Tier used when the signals are not confident. | +| `pool` | No | unset | Optional ordered score pool for routing across two or more completion targets. Keys below. | | `confidence_threshold` | Yes | — | Corroboration a decisive pick needs. In `[0, 1]`. `efficient_first_threshold` is accepted as an alias. | | `capable_first_threshold` | No | `0.0` | Threshold used after an outer classifier selects the capable tier. Only a [composite](#composite) route sets that tier, so this key has no effect on a standalone `stage_router` route. | | `capable_system_prompt` | No | unset | System prompt prepended for capable requests. | @@ -494,6 +495,13 @@ the signals work and for tuning. | `classifier` | No | unset | Table for the optional capability judge consulted on ambiguous turns. Keys below. | | `subagents` | No | unset | Nested `passthrough` or custom `llm_classifier` policy used only for delegated sub-agent work. See [Sub-Agent-Aware Routing](../routing_algorithms/subagent_routing.md). | +#### `pool` keys + +| Key | Required | Default | Meaning | +|---|:---:|---|---| +| `pool.targets` | Yes, when the table is present | — | Ordered list of at least two unique completion target names, starting with `efficient_target` and ending with `capable_target`. | +| `pool.positions` | No | evenly spaced | Optional anchor positions in `[0, 1]`, matching `pool.targets`, starting at `0.0`, ending at `1.0`, and strictly increasing with distinct midpoints. | + #### `handoff_notes` keys | Key | Required | Default | Meaning | @@ -511,7 +519,7 @@ so it is consulted on every ambiguous turn and never retains a verdict. | Key | Required | Default | Meaning | |---|:---:|---|---| | `classifier.target` | Yes, when the table is present | — | Target the judge is called through. Not a routing destination. | -| `classifier.base_threshold` | For LLM judges | — | Lowest `p_solve` that still routes to the efficient tier. In `[0, 1]`. Omit with `classifier.decision`. | +| `classifier.base_threshold` | For two-target LLM judges | — | Lowest `p_solve` that still routes to the efficient tier. In `[0, 1]`. Omit with `classifier.decision` or when `pool.targets` has more than two targets. | | `classifier.threshold_step` | No | `0.0` | Finite, non-negative amount added once for uncertain or unmatched verdicts and twice for unsupported verdicts. `base_threshold + 2 * threshold_step` must be at most `1`. | | `classifier.fail_open` | No | `true` | When `true`, judge client failures and deadlines let the turn fall open to the picker default and record fail-open evidence. When `false`, they stop the request. | | `classifier.decision` | No | defaults for a decision target | Decision model settings. A classifier target in `decision_targets` uses the defaults when this table is absent. It cannot be combined with `base_threshold`, `threshold_step`, `prompt`, `response_format_type`, or `max_output_tokens`; the load error is `decision cannot use LLM judge settings`. See [Decision model classifier](../routing_algorithms/composite_routing.md#decision-model-classifier). | @@ -598,6 +606,7 @@ confidence threshold. Tool signals still drive escalation and recovery. See | `classifier.judge_deadline_ms` | No | unset | Bounds the whole judge consultation in milliseconds, the model call and the response drain included. On expiry, error handling follows `classifier.fail_open`. Must be at least `1`. Unset leaves the consultation unbounded. | | `stage.capable_target` | Yes | — | Capable tier. | | `stage.efficient_target` | Yes | — | Efficient tier. | +| `stage.pool` | No | unset | Optional ordered target pool (`targets` and optional `positions`) shared by both profiles. Cannot be combined with profile `capable_target` or `efficient_target` overrides. | | `stage.efficient_first_threshold` | No | `0.4` | Signal confidence required after an Efficient classification. In `[0, 1]`. Also accepts `confidence_threshold`. | | `stage.capable_first_threshold` | No | `0.0` | Signal confidence required after a Capable classification. In `[0, 1]`. | | `stage.recent_turn_window` | No | `3` | Trailing tool results the signals are computed over. | diff --git a/docs/routing_algorithms/composite_routing.md b/docs/routing_algorithms/composite_routing.md index 1273c5a91b..6bacb67f32 100644 --- a/docs/routing_algorithms/composite_routing.md +++ b/docs/routing_algorithms/composite_routing.md @@ -70,7 +70,10 @@ signals and known summary wrappers, then sets `is_compaction` in the IR. Stage r nor a second `classifier`. The outer classifier supplies the default tier. `confidence_threshold` remains an alias for `efficient_first_threshold`. Custom `tool_semantics` remain stage-local and have the same additive behavior as -on a standalone stage route. +on a standalone stage route. You can also add an optional +`[routes.switchyard.stage.pool]` table (`targets` and optional `positions`) so +both stage profiles score across more than two targets. `stage.pool` cannot be +combined with per-profile `capable_target` or `efficient_target` overrides. ### Independent stage profiles diff --git a/docs/routing_algorithms/stage_router_routing.md b/docs/routing_algorithms/stage_router_routing.md index f5f2d9fb2c..f2296b637a 100644 --- a/docs/routing_algorithms/stage_router_routing.md +++ b/docs/routing_algorithms/stage_router_routing.md @@ -5,9 +5,10 @@ and agent progress. Configure it with `type = "stage_router"`. Stage-router routing sends each request to either a **capable** model or a typically cheaper **efficient** one, depending on where the agent is in its run. -The goal is to spend the capable model on turns that need exploration or error -recovery and let the efficient model carry routine, mechanical work. Choose a -required `picker` for ambiguous turns, tune the split with +You can also add optional intermediate targets with a `[routes..pool]` +table. The goal is to spend the capable model on turns that need exploration or +error recovery and let the efficient model carry routine, mechanical work. +Choose a required `picker` for ambiguous turns, tune the split with `confidence_threshold`, and optionally add an LLM classifier. Model-call fallback happens after the routing decision. Eligible context-window @@ -341,6 +342,9 @@ required columns. | `capable_target` | required | Capable tier. | | `efficient_target` | required | Efficient tier. | | `picker` | required | `efficient_first` or `capable_first` (experimental). Tier used when the signals are not confident. | +| `pool` | unset | Optional score pool table for routing across two or more ordered targets. Keys below. | +| `pool.targets` | required in the table | Completion target names ordered from `efficient_target` (`0.0`) to `capable_target` (`1.0`). At least two unique targets. | +| `pool.positions` | even spacing | Optional anchor positions in `[0.0, 1.0]`, starting at `0.0`, ending at `1.0`, and strictly increasing with distinct midpoints. | | `confidence_threshold` | required | Corroboration a decisive pick needs, `0` to `1`. Alias `efficient_first_threshold`. | | `cache_aware` | `false` | Checks proposed switches against the estimated cost of the agent's next call. Holds and hard overrides take precedence. See [Cache-aware switches](#cache-aware-switches). | | `max_switch_cost_overhead` | `0.10` | Maximum extra cost as a fraction of the destination's estimated bill. Applies when `cache_aware` is enabled. | @@ -359,7 +363,7 @@ required columns. | `handoff_notes.deescalation_note` | unset | Note handed to the efficient tier whenever the signals select it, with or without a capable turn before. | | `handoff_notes.only_on_wrong_signal_escalation` | `true` | When `true`, restricts escalation notes to signal-driven capable decisions. Held turns receive no notes with either setting. | | `classifier.target` | required in the table | Judge target. Not a routing destination. | -| `classifier.base_threshold` | required for LLM judges | Lowest `p_solve` that still routes efficient. | +| `classifier.base_threshold` | required for two-target LLM judges | Lowest `p_solve` that still routes efficient. Rejected when `pool.targets` has more than two targets. | | `classifier.threshold_step` | `0.0` | Added once for uncertain or unmatched verdicts, twice for unsupported. | | `classifier.fail_open` | `true` | On judge failure, fall open to the picker default instead of failing the request. | | `classifier.decision` | unset | Use a decision model instead of an LLM judge. Excludes the LLM judge keys below. | @@ -456,6 +460,64 @@ When migrating from the removed `plan_execute` type, use this recipe and replace for the old judged handoff or reasoning-to-text conversion; keep the plan in ordinary conversation text so the executor receives it. +### Optional: more than two targets + +Add a `[routes..pool]` table to route across two or more ordered targets +using the same tool-signal score: + +```toml +[routes.stage] +id = "switchyard/stage" +type = "stage_router" +efficient_target = "small" +capable_target = "large" +picker = "efficient_first" +confidence_threshold = 0.5 + +[routes.stage.pool] +targets = ["small", "medium", "large"] +positions = [0.0, 0.4, 1.0] # optional; omit for even spacing +``` + +`pool.targets` must list at least two distinct targets, starting with +`efficient_target` and ending with `capable_target`. When `positions` is +omitted, `[0.0, 1.0]` is split into `N` equal cells of width `1 / N` so every +target has the same clear band width `(1 - confidence_threshold) / N`. +When `positions` is set, Stage places boundaries at the midpoints between +adjacent anchors. Boundary ties resolve to the lower target. + +Around each interior boundary `m` between adjacent target anchors `a` and `b`, +the closed ambiguity band is `[m - confidence_threshold * (m - a), m + confidence_threshold * (b - m)]`. +Scores inside any band abstain and go to the optional classifier, then to the +`picker` default. At `confidence_threshold = 1.0`, every score is ambiguous. + +Worked example for `positions = [0.0, 0.4, 1.0]` and `confidence_threshold = 0.5`: + +| Interval | Midpoint | Ambiguity band | Clear scores route to | +|---|---|---|---| +| `small` (`0.0`) to `medium` (`0.4`) | `0.2` | `[0.1, 0.3]` | `< 0.1` -> `small`; `(0.3, 0.55)` -> `medium` | +| `medium` (`0.4`) to `large` (`1.0`) | `0.7` | `[0.55, 0.85]` | `(0.3, 0.55)` -> `medium`; `> 0.85` -> `large` | + +A neutral tool signal scores `0.5`. In an evenly spaced three-target pool, `0.5` +lands on the middle anchor, so neutral turns resolve straight to the middle +target. Reaching the efficient target requires a clearly low score, and the +fallback classifier and `picker` default see fewer turns. Shift `positions` if +you want `0.5` to land inside an ambiguity band instead. + +Holds, hard overrides, handoff notes, endpoint system prompts, and the fall-open +picker keep working on the two endpoints. Intermediate targets receive no hold +and no endpoint prompt. Moving to an intermediate target clears active holds; +switching from an intermediate target to an endpoint arms that endpoint's hold. + +When `pool.targets` has more than two targets and a `[routes..classifier]` +table is present, Stage generates an N-choice JSON Schema judge over the pool +targets. Set `classifier.target` and optionally `classifier.prompt`, +`classifier.recent_turn_window`, `classifier.judge_max_images`, +`classifier.max_output_tokens`, `classifier.judge_deadline_ms`, and +`classifier.fail_open`. Binary settings (`base_threshold`, `threshold_step`, +`decision`), `response_format_type = "json_object"`, and custom schema fields +are rejected at load time. + ### Optional: custom tool semantics Extend the built-in coding vocabulary when an agent uses domain-specific tool diff --git a/tests/test_stage_router_knob_docs.py b/tests/test_stage_router_knob_docs.py index d544e5516e..77489c1265 100644 --- a/tests/test_stage_router_knob_docs.py +++ b/tests/test_stage_router_knob_docs.py @@ -81,7 +81,15 @@ def expected_keys() -> set[str]: signals = LIBSY_TOOL_SIGNALS.read_text() keys: set[str] = set() for key in toml_keys(block(runner, "StageRouter {")): - keys.update(key.split("|")) + field = key.split("|")[0] + if field == "pool": + keys.add("pool") + keys.update( + f"pool.{name}" + for name in toml_keys(block(runner, "pub struct TargetPoolConfig {")) + ) + else: + keys.update(key.split("|")) for key in toml_keys(block(runner, "pub struct StageSettingsConfig {")): field = key.split("|")[0] if field == "tool_semantics": @@ -138,6 +146,8 @@ def test_derived_keys_include_the_known_shape() -> None: keys = expected_keys() assert { "picker", + "pool.targets", + "pool.positions", "confidence_threshold", "efficient_first_threshold", "tool_semantics.observe",