Skip to main content

switchyard_libsy/algorithms/
vgr.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Verification-gated routing: fail-closed capability derivation.
5//!
6//! Capabilities are never client-declared. They come from the router's own
7//! typing of the request, the attempt it produced on the efficient tier, and its own reading
8//! of the tool results in the conversation. No client-reachable input selects
9//! a weaker regime than the default one; unsupported content and missing
10//! evidence select [`Branch::Unknown`], which never commits.
11
12use std::sync::Arc;
13
14use switchyard_protocol::Request;
15
16use self::text::ToolRecord;
17use crate::Result;
18use crate::algorithms::fall_through::FallThrough;
19use crate::algorithms::util::affinity::AffinityRouter;
20use crate::core::algorithm::{Algorithm, AnswerSummary, Driver, RoutingOutcome};
21
22mod compaction;
23mod config;
24mod decide;
25mod readout;
26mod render;
27mod rungs;
28mod runtime;
29mod safety;
30mod text;
31
32pub use config::{ACTIVE_APPROVAL, ServingMode, Targets, VgrConfig};
33pub use safety::{BreakerConfig, KillSwitch};
34
35#[cfg(test)]
36mod tests;
37
38/// A verification-gated route between an efficient and a capable tier.
39pub struct Vgr {
40    route: FallThrough,
41    classifier: Arc<runtime::VgrClassifier>,
42}
43
44impl Vgr {
45    /// Validates and constructs a verification-gated route.
46    pub fn new(config: VgrConfig) -> Result<Self> {
47        config.validate()?;
48        let mut affinity = AffinityRouter::new().with_latch_only([config.targets.capable.clone()]);
49        let reason = if config.latch_escalation && config.mode != ServingMode::Shadow {
50            "session_latched"
51        } else {
52            affinity = affinity.with_release_on_user_turn();
53            "turn_verification_latched"
54        };
55        let affinity = Arc::new(affinity);
56        let mut route = FallThrough::new_with_state().with_name("vgr");
57        if config.compact_handoff {
58            route = route.with_classifier(Arc::new(compaction::Compactor));
59        }
60        let classifier = Arc::new(runtime::VgrClassifier {
61            breaker: safety::CircuitBreaker::new(config.breaker),
62            config,
63        });
64        // Shadow always serves the capable tier; only a VGR escalation should hold it there.
65        if classifier.config.mode != ServingMode::Shadow {
66            route = route
67                .with_processor(affinity.clone())
68                .with_classifier(Arc::new(runtime::Held(affinity, reason)));
69        }
70        let route = route.with_classifier(classifier.clone());
71        Ok(Self { route, classifier })
72    }
73}
74
75#[async_trait::async_trait]
76impl Algorithm for Vgr {
77    fn name(&self) -> &str {
78        "vgr"
79    }
80
81    async fn route(self: Arc<Self>, driver: Driver, request: Request) -> Result<RoutingOutcome> {
82        // The handoff note is written for the capable tier, so an efficient stand-in gets the request
83        // as it arrived.
84        let arrived = self
85            .classifier
86            .efficient_may_stand_in(&request)
87            .then(|| request.clone());
88        let mut outcome = self.route.execute(driver.clone(), request).await?;
89        // Efficient answers are already buffered and have no fallback.
90        outcome.selected_model_ids.truncate(1);
91        let config = &self.classifier.config;
92        if let Some(arrived) = arrived
93            && outcome.response.is_none()
94            && outcome.selected_model_ids.first() == Some(&config.targets.capable)
95            // A failed generation must not be retried after the capable tier also rejects it.
96            && !driver.model_failed(&config.targets.efficient)
97            && self.classifier.efficient_may_stand_in(&arrived)
98        {
99            outcome
100                .selected_model_ids
101                .push(config.targets.efficient.clone());
102            outcome.fallback_request = Some(arrived);
103        }
104        Ok(outcome)
105    }
106
107    fn tracks_answers(&self) -> bool {
108        self.route.tracks_answers()
109    }
110
111    async fn observe_answer(&self, session_id: &str, answer: AnswerSummary) {
112        self.route.observe_answer(session_id, answer).await;
113    }
114}
115
116/// The verification regime a request's capabilities license.
117#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
118enum Branch {
119    /// Code or test activity, with no sandboxed checker to appeal to.
120    Coding,
121    /// A single-turn request typed as answer-seeking.
122    Answer,
123    /// Conversational traffic.
124    Chat,
125    /// A tool-using session verified from its trajectory.
126    Agentic,
127    /// Anything else with an attempt to verify.
128    DefaultVerified,
129    /// Nothing to verify.
130    #[default]
131    Unknown,
132}
133
134/// A task type produced by the router's own typing call; `None` abstains.
135#[derive(Clone, Copy, Debug, Eq, PartialEq)]
136enum TaskType {
137    Coding,
138    Agentic,
139    Answer,
140    Chat,
141}
142
143/// The complete input the decision core sees.
144#[derive(Default)]
145struct Capabilities {
146    branch: Branch,
147    /// The judged view of the request and attempt.
148    transcript: Option<String>,
149    /// The router's own tool-result record; unused by the answer regime.
150    tools: Option<ToolRecord>,
151}
152
153/// Derives capabilities from the router's own evidence, failing closed.
154///
155/// Media blocks fail closed unless `attachments_supported` sends them to the judge.
156fn derive_capabilities(
157    request: &Request,
158    attempt: &str,
159    task_type: Option<TaskType>,
160    attachments_supported: bool,
161) -> Capabilities {
162    let (turns, unsupported) = text::turns(request);
163    if (unsupported && !attachments_supported)
164        || text::user_task_text(&turns).trim().is_empty()
165        || attempt.trim().is_empty()
166    {
167        return Capabilities::default();
168    }
169    let caps = |branch, transcript| Capabilities {
170        branch,
171        transcript,
172        tools: Some(ToolRecord::from_request(request)),
173    };
174
175    // Typing abstains on a request that leans on earlier context, so a typed answer stands
176    // on its own; only tool use in the current user turn takes it off this branch.
177    if task_type == Some(TaskType::Answer) && !text::turn_has_tool_trajectory(request) {
178        return Capabilities {
179            tools: None,
180            ..caps(
181                Branch::Answer,
182                Some(render::render_session(&turns, attempt)),
183            )
184        };
185    }
186    // A tool trajectory is judged as agentic work unless typed conversational.
187    if task_type == Some(TaskType::Agentic)
188        || (text::has_tool_trajectory(request)
189            && !matches!(task_type, Some(TaskType::Answer | TaskType::Chat)))
190    {
191        return caps(
192            Branch::Agentic,
193            Some(render::render_agentic_view(request, &turns, attempt)),
194        );
195    }
196    let transcript = Some(render::render_session(&turns, attempt));
197    if text::observed_hardening(attempt) || task_type == Some(TaskType::Coding) {
198        return caps(Branch::Coding, transcript);
199    }
200    if text::observed_tool_activity(attempt) {
201        caps(Branch::Agentic, transcript)
202    } else if matches!(task_type, Some(TaskType::Chat | TaskType::Answer)) {
203        caps(Branch::Chat, transcript)
204    } else {
205        caps(Branch::DefaultVerified, transcript)
206    }
207}