Skip to main content

switchyard_libsy/core/
pool.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A fixed score line shared by classifiers and the final target resolver.
5
6use crate::{LibsyError, Result};
7use switchyard_protocol::ModelId;
8
9/// Ordered target anchors and the boundaries halfway between them.
10#[derive(Clone, Debug)]
11pub struct TargetPool {
12    targets: Vec<ModelId>,
13    positions: Vec<f64>,
14}
15
16impl TargetPool {
17    /// Targets in increasing score order. An empty line uses evenly spaced anchors.
18    pub fn new(targets: Vec<ModelId>, positions: Vec<f64>) -> Result<Self> {
19        if targets.is_empty() {
20            return Err(LibsyError::NoTargets);
21        }
22        if targets
23            .iter()
24            .enumerate()
25            .any(|(i, target)| targets[..i].contains(target))
26        {
27            return Err(invalid("pool targets must be distinct"));
28        }
29        let positions = if positions.is_empty() {
30            (0..targets.len())
31                .map(|i| i as f64 / targets.len().saturating_sub(1).max(1) as f64)
32                .collect()
33        } else {
34            positions
35        };
36        if positions.len() != targets.len()
37            || positions
38                .iter()
39                .any(|p| !p.is_finite() || !(0.0..=1.0).contains(p))
40            || positions.windows(2).any(|pair| {
41                let midpoint = (pair[0] + pair[1]) / 2.0;
42                pair[0] >= midpoint || midpoint >= pair[1]
43            })
44            || positions[0] != 0.0
45            || (positions.len() > 1 && positions.last() != Some(&1.0))
46        {
47            return Err(invalid(
48                "pool positions must match targets, increase with distinct midpoints, and span 0 to 1",
49            ));
50        }
51        Ok(Self { targets, positions })
52    }
53
54    /// Number of targets on the score line.
55    pub fn target_count(&self) -> usize {
56        self.targets.len()
57    }
58
59    pub(crate) fn validate_targets(&self, targets: &[ModelId]) -> Result<()> {
60        for target in &self.targets {
61            super::algorithm::ensure_model_is_target(targets, target)?;
62        }
63        Ok(())
64    }
65
66    pub(crate) fn position(&self, target: &ModelId) -> Result<f64> {
67        self.targets
68            .iter()
69            .position(|candidate| candidate == target)
70            .map(|index| self.positions[index])
71            .ok_or_else(|| {
72                invalid(format!(
73                    "classifier selected target {target} outside the score pool"
74                ))
75            })
76    }
77
78    /// Distance from the nearest midpoint, normalized within its adjacent interval.
79    /// Zero is ambiguous; one is an anchor. This reduces to abs(2*p - 1) for two targets.
80    pub fn confidence(&self, value: f64) -> Result<f64> {
81        validate_value(value)?;
82        Ok(self
83            .positions
84            .windows(2)
85            .find(|pair| value >= pair[0] && value <= pair[1])
86            .map_or(1.0, |pair| {
87                (2.0 * (value - (pair[0] + pair[1]) / 2.0).abs() / (pair[1] - pair[0])).min(1.0)
88            }))
89    }
90
91    /// Continuous scores on a closed ambiguity band fall through to the next classifier.
92    pub fn is_clear(&self, value: f64, threshold: f64) -> Result<bool> {
93        validate_value(value)?;
94        validate_value(threshold)?;
95        // At one the bands cover the line; midpoint rounding must not open gaps.
96        if threshold == 1.0 {
97            return Ok(false);
98        }
99        Ok(!self.positions.windows(2).any(|pair| {
100            let midpoint = (pair[0] + pair[1]) / 2.0;
101            let width = threshold * (pair[1] - pair[0]) / 2.0;
102            value >= midpoint - width && value <= midpoint + width
103        }))
104    }
105
106    /// Resolve once, after the cascade accepts a clear score. Midpoint ties go left.
107    pub fn resolve(&self, value: f64) -> Result<&ModelId> {
108        validate_value(value)?;
109        let index = self
110            .positions
111            .windows(2)
112            .take_while(|pair| value > (pair[0] + pair[1]) / 2.0)
113            .count();
114        Ok(&self.targets[index])
115    }
116}
117
118pub(crate) fn validate_value(value: f64) -> Result<()> {
119    if !value.is_finite() || !(0.0..=1.0).contains(&value) {
120        return Err(invalid(format!(
121            "classifier score must be finite and between 0 and 1, got {value}"
122        )));
123    }
124    Ok(())
125}
126
127fn invalid(message: impl Into<String>) -> LibsyError {
128    LibsyError::AlgorithmError {
129        message: message.into(),
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    #[test]
137    fn line_and_relative_bands() -> Result<()> {
138        let pool = TargetPool::new(
139            vec!["small".into(), "middle".into(), "large".into()],
140            vec![0.0, 0.4, 1.0],
141        )?;
142        for (score, target, confidence) in [
143            (0.0, "small", 1.0),
144            (0.2, "small", 0.0),
145            (0.4, "middle", 1.0),
146            (0.7, "middle", 0.0),
147            (1.0, "large", 1.0),
148        ] {
149            assert_eq!(pool.resolve(score)?.as_str(), target);
150            assert!((pool.confidence(score)? - confidence).abs() < 1e-12);
151            assert!((0.0..=1.0).contains(&pool.confidence(score)?));
152        }
153        Ok(())
154    }
155    #[test]
156    fn rejects_invalid_lines_and_scores() {
157        for line in [
158            vec![0.0],
159            vec![0.1, 1.0],
160            vec![0.0, 0.8],
161            vec![0.0, f64::NAN],
162        ] {
163            assert!(TargetPool::new(vec!["a".into(), "b".into()], line).is_err());
164        }
165        assert!(TargetPool::new(vec!["a".into(), "a".into()], vec![]).is_err());
166        let pool = TargetPool::new(vec!["a".into()], vec![]).unwrap();
167        for score in [f64::NAN, f64::INFINITY, -0.1, 1.1] {
168            assert!(pool.resolve(score).is_err());
169        }
170    }
171    #[test]
172    fn binary_bands_and_multi_target_boundaries_are_closed() -> Result<()> {
173        let binary = TargetPool::new(vec!["a".into(), "b".into()], vec![])?;
174        for threshold in [0.0, 0.2, 0.5, 1.0] {
175            for i in 0..=1000 {
176                let p = i as f64 / 1000.0;
177                assert_eq!(
178                    binary.is_clear(p, threshold)?,
179                    p < 0.5 - threshold / 2.0 || p > 0.5 + threshold / 2.0
180                );
181            }
182        }
183        let pool = TargetPool::new(vec!["a".into(), "b".into(), "c".into()], vec![])?;
184        for p in [0.25, 0.75] {
185            assert!(!pool.is_clear(p, 0.0)?);
186        }
187        for p in [0.0, 0.5, 1.0] {
188            assert!(pool.is_clear(p, 0.5)?);
189        }
190        for p in [0.125, 0.375, 0.625, 0.875] {
191            assert!(!pool.is_clear(p, 0.5)?);
192        }
193        let uneven = TargetPool::new(
194            vec!["a".into(), "b".into(), "c".into(), "d".into(), "e".into()],
195            vec![
196                0.0,
197                0.34284326542215604,
198                0.471240086114993,
199                0.5346217948794222,
200                1.0,
201            ],
202        )?;
203        for value in &uneven.positions {
204            assert!(
205                !uneven.is_clear(*value, 1.0)?,
206                "anchor {value} escaped the closed band"
207            );
208        }
209        Ok(())
210    }
211    #[test]
212    fn runtime_pool_rejects_targets_outside_the_completion_group() -> Result<()> {
213        use switchyard_protocol::Category;
214        let models = crate::RuntimeModels::new(
215            [
216                (Category::Any, vec!["small".into()]),
217                (Category::Judge, vec!["judge".into()]),
218            ]
219            .into(),
220        );
221        for target in ["missing", "judge"] {
222            let error = models
223                .clone()
224                .with_pool(TargetPool::new(
225                    vec!["small".into(), target.into()],
226                    vec![],
227                )?)
228                .expect_err("pool targets must be completion targets");
229            assert!(matches!(error, LibsyError::TargetNotFound { target: name } if name == target));
230        }
231        Ok(())
232    }
233
234    #[test]
235    fn parent_line_does_not_leak_into_subagent_scope() -> Result<()> {
236        use switchyard_protocol::Category;
237        let models = crate::RuntimeModels::new(
238            [(
239                Category::Any,
240                vec!["small".into(), "middle".into(), "large".into()],
241            )]
242            .into(),
243        )
244        .with_pool(TargetPool::new(
245            vec!["small".into(), "middle".into(), "large".into()],
246            vec![0.0, 0.4, 1.0],
247        )?)?
248        .with_subagent(
249            [
250                (Category::Efficient, vec!["worker-small".into()]),
251                (Category::Capable, vec!["worker-large".into()]),
252            ]
253            .into(),
254        );
255        let (driver, _) = crate::Driver::new("test", std::sync::Arc::new(models));
256        assert_eq!(driver.pool().unwrap().resolve(0.4)?.as_str(), "middle");
257        let worker = driver.for_subagent()?;
258        assert!(worker.pool().is_none());
259        Ok(())
260    }
261}