Skip to main content

switchyard_libsy/algorithms/vgr/
config.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::time::Duration;
5
6use switchyard_protocol::ModelId;
7
8use super::safety::{BreakerConfig, KillSwitch};
9use crate::{LibsyError, Result};
10
11/// Required attestation for live local commits.
12pub const ACTIVE_APPROVAL: &str = "prospective-validation-and-canary-approved";
13
14/// Authority granted to VGR decisions.
15#[derive(Clone, Debug, Default, Eq, PartialEq)]
16pub enum ServingMode {
17    /// Always serves cloud without producing an attempt.
18    #[default]
19    Off,
20    /// Serves decisions, for isolated measurement.
21    Evaluate,
22    /// Decides but always serves cloud.
23    Shadow,
24    /// Serves decisions after operator approval.
25    Active {
26        /// Operator approval attestation.
27        approval: String,
28    },
29}
30
31/// Targets used by a VGR route.
32#[derive(Clone, Debug)]
33pub struct Targets {
34    /// Tier that produces the candidate attempt.
35    pub local: ModelId,
36    /// Tier used when the candidate is not licensed.
37    pub cloud: ModelId,
38    /// Local verifier, defaulting to `local`.
39    pub judge: Option<ModelId>,
40    /// Capable-tier verifier; unset removes the cloud confirmation rungs.
41    pub cloud_judge: Option<ModelId>,
42}
43
44/// VGR runtime configuration.
45#[derive(Clone, Debug)]
46pub struct VgrConfig {
47    /// Completion and verifier targets.
48    pub targets: Targets,
49    /// Authority granted to routing decisions.
50    pub mode: ServingMode,
51    /// Budget for one turn's attempt and verification.
52    pub deadline: Duration,
53    /// Optional live stop controlled by the operator.
54    pub kill_switch: Option<KillSwitch>,
55    /// Local endpoint breaker tuning.
56    pub breaker: BreakerConfig,
57    /// Whether a cheap typing call selects a verification regime.
58    pub task_typing: bool,
59    /// Whether the local tier accepts image content.
60    pub local_supports_images: bool,
61    /// Lets a long agentic run with earlier tool errors commit on a capable-tier
62    /// confirmation once it ends in this many consecutive clean tool results.
63    pub confirmed_recovery_min_clean_tail: Option<u32>,
64    /// Tells the capable tier, once per user turn, that it inherits unverified
65    /// tool-using work.
66    pub agentic_handoff: bool,
67    /// Condenses local history at handoff. Requires `agentic_handoff`.
68    pub compact_handoff: bool,
69    /// Wall-clock budget for the local tier within one user turn, including the
70    /// client's tool execution.
71    pub local_turn_budget: Option<Duration>,
72    /// Holds an escalated session on the capable tier past later user turns.
73    /// Shadow mode retains only the current turn's hold.
74    pub latch_escalation: bool,
75}
76
77impl VgrConfig {
78    /// Creates an off-by-default route between local and capable tiers.
79    pub fn new(local: ModelId, cloud: ModelId) -> Self {
80        Self {
81            targets: Targets {
82                local,
83                cloud,
84                judge: None,
85                cloud_judge: None,
86            },
87            mode: ServingMode::Off,
88            deadline: Duration::from_secs(30),
89            kill_switch: None,
90            breaker: BreakerConfig::default(),
91            task_typing: true,
92            local_supports_images: false,
93            confirmed_recovery_min_clean_tail: None,
94            agentic_handoff: false,
95            compact_handoff: false,
96            local_turn_budget: None,
97            latch_escalation: false,
98        }
99    }
100
101    pub(super) fn validate(&self) -> Result<()> {
102        if self.compact_handoff && !self.agentic_handoff {
103            return Err(LibsyError::AlgorithmError {
104                message: "compact_handoff requires agentic_handoff".into(),
105            });
106        }
107        if self.targets.local == self.targets.cloud {
108            return Err(LibsyError::AlgorithmError {
109                message: "vgr requires distinct local and cloud model IDs".into(),
110            });
111        }
112        if self.deadline.is_zero() || self.breaker.threshold == 0 {
113            return Err(LibsyError::AlgorithmError {
114                message: "vgr deadline and breaker threshold must be non-zero".into(),
115            });
116        }
117        if let ServingMode::Active { approval } = &self.mode
118            && approval != ACTIVE_APPROVAL
119        {
120            return Err(LibsyError::AlgorithmError {
121                message: format!(
122                    "vgr active mode requires approval attestation {ACTIVE_APPROVAL:?}"
123                ),
124            });
125        }
126        Ok(())
127    }
128
129    pub(super) fn judge(&self) -> &ModelId {
130        self.targets.judge.as_ref().unwrap_or(&self.targets.local)
131    }
132
133    pub(super) fn confirmed_min_clean_tail(&self) -> Option<i32> {
134        self.confirmed_recovery_min_clean_tail
135            .map(|tail| i32::try_from(tail.max(1)).unwrap_or(i32::MAX))
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn compaction_requires_handoff_for_direct_callers() {
145        let mut config = VgrConfig::new("local".into(), "cloud".into());
146        assert!(!config.compact_handoff);
147        config.compact_handoff = true;
148        assert!(super::super::Vgr::new(config.clone()).is_err());
149        config.agentic_handoff = true;
150        assert!(super::super::Vgr::new(config).is_ok());
151    }
152
153    #[test]
154    fn direct_callers_must_use_distinct_local_and_cloud_ids() {
155        assert!(super::super::Vgr::new(VgrConfig::new("same".into(), "same".into())).is_err());
156        assert!(super::super::Vgr::new(VgrConfig::new("local".into(), "cloud".into())).is_ok());
157    }
158}