Skip to content

Switchyard lets LLM applications route traffic across models and providers while preserving native OpenAI and Anthropic API compatibility - enabling flexible model selection, benchmarking, and cost/performance optimization.

Rust

refactor(libsy): fold turn pinning into AffinityRouter as a release rule (#494)

ryan-lempkac93d450b1387
diff --git a/crates/libsy/src/algorithms/llm_class.rs b/crates/libsy/src/algorithms/llm_class.rs
index 86c22bb54..d2a12582b 100644
--- a/crates/libsy/src/algorithms/llm_class.rs
+++ b/crates/libsy/src/algorithms/llm_class.rs
@@ -12,7 +12,7 @@ use serde_json::Value;
use switchyard_protocol::{ContentBlock, Message, ModelId, Role};
use super::fall_through::{DefaultTarget, FallThrough};
-use super::util::affinity::AffinityRouter;
+use super::util::affinity::{AffinityRouter, ClassifyTrigger};
use super::util::classifier_contract::{
ClassifierContract, ClassifierContractConfig, ClassifierResponseFormat,
};
@@ -22,7 +22,6 @@ use super::util::llm_judge::{
SerdeDecoder, StructuredJudge,
};
use super::util::target_selector::TargetSelectorPolicy;
-use super::util::turn_pin::{ClassifyTrigger, TurnPin};
use super::util::{DEFAULT_JUDGE_MAX_OUTPUT_TOKENS, decisive};
use crate::core::algorithm::{self, Algorithm, Driver};
use crate::core::classifier::{Classification, Classifier, Score};
@@ -579,6 +578,24 @@ impl Classifier<State> for EscalationClassifier {
}
}
+/// Builds the affinity router a trigger calls for, if any.
+fn affinity_router(
+ trigger: ClassifyTrigger,
+ message_hash_fallback: bool,
+) -> Option<Arc<AffinityRouter>> {
+ let router = match trigger {
+ ClassifyTrigger::EveryRequest => return None,
+ ClassifyTrigger::NewSession => AffinityRouter::new(),
+ ClassifyTrigger::UserTurn => AffinityRouter::new().with_release_on_user_turn(),
+ };
+ let router = if message_hash_fallback {
+ router.with_message_hash_fallback()
+ } else {
+ router
+ };
+ Some(Arc::new(router))
+}
+
/// Routes requests through a capability, escalation, or custom classifier mode.
pub struct LlmTaskClassifier {
route: FallThrough<State>,
@@ -855,28 +872,15 @@ impl LlmTaskClassifier {
.to_string(),
});
}
- // Wraps the classifier rather than the route, so the pin also holds when this is
- // embedded in another cascade and only `score` is called.
- let inner = if config.classify_trigger == ClassifyTrigger::UserTurn {
- Arc::new(TurnPin::new(inner)) as Arc<dyn Classifier<State>>
- } else {
- inner
- };
// Affinity comes first so a retained assignment short-circuits the judge call.
- // Note: when this classifier is embedded inside another cascade (e.g. StageRouter)
- // the affinity processor never fires — only the inner score() is called.
let mut route = FallThrough::<State>::new_with_state(targets).with_name(ALGORITHM_NAME);
- if config.classify_trigger == ClassifyTrigger::NewSession {
- let affinity = if config.message_hash_fallback {
- AffinityRouter::new().with_message_hash_fallback()
- } else {
- AffinityRouter::new()
- };
+ if let Some(affinity) =
+ affinity_router(config.classify_trigger, config.message_hash_fallback).as_ref()
+ {
// Both roles must share one `Arc` so the classifier reads what the processor wrote.
- let affinity = Arc::new(affinity);
route = route
.with_processor(affinity.clone())
- .with_classifier(affinity);
+ .with_classifier(affinity.clone());
}
let fallback = DefaultTarget::new(config.default_target);
Ok(Self {
diff --git a/crates/libsy/src/algorithms/util.rs b/crates/libsy/src/algorithms/util.rs
index 0f115ae55..d2e85c4c2 100644
--- a/crates/libsy/src/algorithms/util.rs
+++ b/crates/libsy/src/algorithms/util.rs
@@ -10,7 +10,6 @@ pub(crate) mod stage;
pub mod subagent;
pub(crate) mod target_selector;
pub(crate) mod tool_signals;
-pub mod turn_pin;
use switchyard_protocol::ModelId;
diff --git a/crates/libsy/src/algorithms/util/affinity.rs b/crates/libsy/src/algorithms/util/affinity.rs
index 4f13e96f9..6710ce3f2 100644
--- a/crates/libsy/src/algorithms/util/affinity.rs
+++ b/crates/libsy/src/algorithms/util/affinity.rs
@@ -23,7 +23,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
use async_trait::async_trait;
use parking_lot::Mutex;
-use switchyard_protocol::{ModelId, Request, Role};
+use serde::Deserialize;
+use switchyard_protocol::{ContentBlock, Message, ModelId, Request, Role};
use crate::core::algorithm::{Driver, RoutingIdentity};
use crate::core::classifier::{Classification, Classifier, Score};
@@ -33,6 +34,33 @@ use crate::core::processor::{Event, Processor};
/// without limit; the oldest entry is evicted once the bound is reached.
const MAX_ASSIGNMENTS: usize = 4096;
+/// How often the classifier re-decides a session's target.
+#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ClassifyTrigger {
+ /// Judge every request, tool continuations included.
+ #[default]
+ EveryRequest,
+ /// Judge each new user message, holding that target across the tool calls between.
+ UserTurn,
+ /// Judge once and reuse that target for the session.
+ NewSession,
+}
+
+/// Anthropic carries tool results as a `Role::User` message, so role alone cannot tell a
+/// human turn from a tool continuation.
+fn is_user_turn(message: &Message) -> bool {
+ message.role == Role::User
+ && !message
+ .content
+ .iter()
+ .all(|block| matches!(block, ContentBlock::ToolResult(_)))
+}
+
+fn has_new_user_turn(messages: &[Message]) -> bool {
+ messages.last().is_some_and(is_user_turn)
+}
+
/// Retains a model per request identity and forces it on later matching requests.
///
/// Register the same instance as both a processor and a classifier; the two roles share
@@ -51,6 +79,8 @@ pub struct AffinityRouter {
subagents_only: bool,
/// In absence of headers, use the message hash based fallback key to do task based routing
message_hash_fallback: bool,
+ /// Whether a new user message drops the assignment so the judge runs again.
+ release_on_user_turn: bool,
/// Retained assignments, shared across this router's processor and classifier roles.
///
/// Held on the instance so the two roles share one process-local map through a
@@ -83,6 +113,12 @@ impl AffinityRouter {
self
}
+ /// Re-decides per user turn, holding the target across the tool calls between.
+ pub fn with_release_on_user_turn(mut self) -> Self {
+ self.release_on_user_turn = true;
+ self
+ }
+
/// Restricts latching to `models`; a decision for any other model routes but is not
/// retained.
pub fn with_latch_only(mut self, models: impl IntoIterator<Item = impl Into<ModelId>>) -> Self {
@@ -155,7 +191,8 @@ where
&& let Some(key) = self.affinity_key(request)
{
let mut assignments = self.assignments.lock();
- if self.should_latch(selected_model_id) && !assignments.contains_key(&key) {
+ let writable = self.release_on_user_turn || !assignments.contains_key(&key);
+ if self.should_latch(selected_model_id) && writable {
evict_if_full(&mut assignments);
assignments.insert(key, selected_model_id.clone());
}
@@ -192,6 +229,11 @@ where
let Some(key) = self.affinity_key(request) else {
return Ok((Classification::Scores(Vec::new()), None));
};
+ // Abstaining rather than clearing keeps this read path free of writes, so the judge
+ // decides the turn whatever order concurrent latches land in.
+ if self.release_on_user_turn && has_new_user_turn(&request.llm_request.messages) {
+ return Ok((Classification::Scores(Vec::new()), None));
+ }
let assigned = self.assignments.lock().get(&key).cloned();
Ok((
Classification::Scores(match assigned {
@@ -221,7 +263,7 @@ mod tests {
use std::sync::Arc;
- use switchyard_protocol::{ContentBlock, LlmRequest, Message, Metadata, text_request};
+ use switchyard_protocol::{LlmRequest, Metadata, ToolResult, text_request};
/// Boxed, thread-safe error type keeping the test helpers ergonomic.
type BoxErr = Box<dyn std::error::Error + Send + Sync>;
@@ -750,6 +792,42 @@ mod tests {
Ok(())
}
+ #[tokio::test]
+ async fn release_on_user_turn_drops_the_assignment_only_when_the_user_speaks()
+ -> Result<(), BoxErr> {
+ let router = AffinityRouter::new().with_release_on_user_turn();
+ let mut state = ();
+ let mut opening = task_request(Some(session("session-1", "agent-a")), "add caching", None);
+ retain(&router, &mut state, &mut opening, "weak").await?;
+
+ // A tool continuation holds the assignment, so no judge call.
+ let mut continued = opening.clone();
+ continued.llm_request.messages.push(Message {
+ role: Role::User,
+ content: vec![ContentBlock::ToolResult(ToolResult {
+ tool_call_id: "call-1".to_string(),
+ content: Vec::new(),
+ is_error: None,
+ })],
+ });
+ assert_eq!(
+ scores(&router, &mut state, &mut continued)
+ .await?
+ .first()
+ .map(|s| s.target.as_str()),
+ Some("weak")
+ );
+
+ // A new user message releases it, so the turn abstains and the judge runs.
+ let mut spoke = task_request(
+ Some(session("session-1", "agent-a")),
+ "add caching",
+ Some("no, shared across processes"),
+ );
+ assert!(scores(&router, &mut state, &mut spoke).await?.is_empty());
+ Ok(())
+ }
+
#[tokio::test]
async fn latch_only_retains_matching_models() -> Result<(), BoxErr> {
let router = AffinityRouter::new().with_latch_only(["strong"]);
diff --git a/crates/libsy/src/algorithms/util/turn_pin.rs b/crates/libsy/src/algorithms/util/turn_pin.rs
deleted file mode 100644
index d86250e77..000000000
--- a/crates/libsy/src/algorithms/util/turn_pin.rs
+++ /dev/null
@@ -1,288 +0,0 @@
-// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
-// SPDX-License-Identifier: Apache-2.0
-
-//! Holds one classifier verdict across the tool-call turns that follow a user message.
-
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde::Deserialize;
-use switchyard_protocol::{ContentBlock, Message, ModelId, Request, Response, Role};
-
-use super::decisive;
-use crate::Result;
-use crate::core::algorithm::Driver;
-use crate::core::classifier::{Classification, Classifier};
-use crate::core::state::{State, StateValue};
-
-/// `State.extra` key holding the pinned target.
-const PINNED_TARGET_KEY: &str = "classifier_pinned_target";
-
-/// How often the classifier re-decides a session's target.
-#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum ClassifyTrigger {
- /// Judge every request, tool continuations included.
- #[default]
- EveryRequest,
- /// Judge each new user message and hold that target across the tool calls between.
- UserTurn,
- /// Judge once and reuse that target for the session.
- NewSession,
-}
-
-/// True when the user spoke. Anthropic carries tool results as a `Role::User` message, so
-/// role alone cannot tell a human turn from a tool continuation. The same invariant is
-/// encoded in the Anthropic codec's `message_is_tool_result_only`.
-fn is_user_turn(message: &Message) -> bool {
- message.role == Role::User
- && !message
- .content
- .iter()
- .all(|block| matches!(block, ContentBlock::ToolResult(_)))
-}
-
-/// True when the conversation ends with the user speaking, so the agent is not mid-task.
-fn starts_new_turn(messages: &[Message]) -> bool {
- messages.last().is_some_and(is_user_turn)
-}
-
-fn pinned_target(state: &State) -> Option<ModelId> {
- match state.extra.get(PINNED_TARGET_KEY) {
- Some(StateValue::String(target)) => Some(ModelId::new(target.clone())),
- _ => None,
- }
-}
-
-/// Pins the inner classifier's verdict until the user speaks again.
-///
-/// Without a session id there is no retained state, and every turn is classified.
-pub(crate) struct TurnPin {
- inner: Arc<dyn Classifier<State>>,
-}
-
-impl TurnPin {
- pub(crate) fn new(inner: Arc<dyn Classifier<State>>) -> Self {
- Self { inner }
- }
-}
-
-#[async_trait]
-impl Classifier<State> for TurnPin {
- fn routing_tier(&self, selected_model_id: &ModelId) -> Option<&'static str> {
- self.inner.routing_tier(selected_model_id)
- }
-
- async fn score(
- &self,
- state: &mut State,
- request: &mut Request,
- driver: Option<&Driver>,
- ) -> Result<(Classification, Option<Response>)> {
- if let Some(target) = pinned_target(state)
- && !starts_new_turn(&request.llm_request.messages)
- {
- return Ok((decisive(&target), None));
- }
-
- let (classification, response) = self.inner.score(state, request, driver).await?;
- // An abstention clears the pin. Holding the old target would serve this turn from the
- // fall-through default while its tool continuations reused the previous turn's target.
- match classification.argmax(false)? {
- Some(score) => {
- state.extra.insert(
- PINNED_TARGET_KEY.to_string(),
- StateValue::String(score.target.as_str().to_string()),
- );
- }
- None => {
- state.extra.remove(PINNED_TARGET_KEY);
- }
- }
- Ok((classification, response))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- use parking_lot::Mutex;
- use serde_json::Value;
- use switchyard_protocol::{LlmRequest, ToolCall, ToolResult};
-
- /// Returns queued verdicts in order, counting each consultation.
- struct RecordingClassifier {
- verdicts: Mutex<Vec<Option<&'static str>>>,
- consultations: Mutex<u32>,
- }
-
- impl RecordingClassifier {
- fn new(verdicts: Vec<Option<&'static str>>) -> Arc<Self> {
- Arc::new(Self {
- verdicts: Mutex::new(verdicts.into_iter().rev().collect()),
- consultations: Mutex::new(0),
- })
- }
-
- fn consultations(&self) -> u32 {
- *self.consultations.lock()
- }
- }
-
- #[async_trait]
- impl Classifier<State> for RecordingClassifier {
- async fn score(
- &self,
- _state: &mut State,
- _request: &mut Request,
- _driver: Option<&Driver>,
- ) -> Result<(Classification, Option<Response>)> {
- *self.consultations.lock() += 1;
- let verdict = self.verdicts.lock().pop().flatten();
- Ok((
- match verdict {
- Some(target) => decisive(&ModelId::new(target)),
- None => Classification::Scores(Vec::new()),
- },
- None,
- ))
- }
- }
-
- fn user(text: &str) -> Message {
- Message::text(Role::User, text)
- }
-
- fn tool_result(id: &str) -> Message {
- Message {
- role: Role::User,
- content: vec![ContentBlock::ToolResult(ToolResult {
- tool_call_id: id.to_string(),
- content: Vec::new(),
- is_error: None,
- })],
- }
- }
-
- fn tool_call(id: &str) -> Message {
- Message {
- role: Role::Assistant,
- content: vec![ContentBlock::ToolCall(ToolCall {
- id: id.to_string(),
- name: "read".to_string(),
- arguments: Value::Null,
- })],
- }
- }
-
- async fn selected(
- pin: &TurnPin,
- state: &mut State,
- messages: Vec<Message>,
- ) -> Result<Option<String>> {
- let mut request = Request {
- llm_request: LlmRequest {
- messages,
- ..LlmRequest::default()
- },
- raw_request: None,
- metadata: None,
- };
- let (classification, _) = pin.score(state, &mut request, None).await?;
- Ok(classification
- .argmax(false)?
- .map(|score| score.target.as_str().to_string()))
- }
-
- #[tokio::test]
- async fn tool_continuation_turns_hold_the_pinned_target() -> Result<()> {
- let inner = RecordingClassifier::new(vec![Some("capable"), Some("efficient")]);
- let pin = TurnPin::new(inner.clone());
- let mut state = State::default();
- let opening = vec![user("debug this")];
-
- assert_eq!(
- selected(&pin, &mut state, opening.clone()).await?,
- Some("capable".to_string())
- );
- let mut continued = opening;
- continued.push(tool_call("call-1"));
- continued.push(tool_result("call-1"));
- assert_eq!(
- selected(&pin, &mut state, continued).await?,
- Some("capable".to_string())
- );
- assert_eq!(inner.consultations(), 1);
- Ok(())
- }
-
- #[tokio::test]
- async fn a_fresh_user_message_re_classifies() -> Result<()> {
- let inner = RecordingClassifier::new(vec![Some("efficient"), Some("capable")]);
- let pin = TurnPin::new(inner.clone());
- let mut state = State::default();
- let opening = vec![user("summarise this file")];
-
- assert_eq!(
- selected(&pin, &mut state, opening.clone()).await?,
- Some("efficient".to_string())
- );
- let mut followed_up = opening;
- followed_up.push(tool_call("call-1"));
- followed_up.push(tool_result("call-1"));
- followed_up.push(user("now find the race condition"));
- assert_eq!(
- selected(&pin, &mut state, followed_up).await?,
- Some("capable".to_string())
- );
- assert_eq!(inner.consultations(), 2);
- Ok(())
- }
-
- #[tokio::test]
- async fn an_abstention_clears_an_earlier_pin() -> Result<()> {
- let inner = RecordingClassifier::new(vec![Some("efficient"), None, Some("capable")]);
- let pin = TurnPin::new(inner.clone());
- let mut state = State::default();
- let opening = vec![user("summarise this file")];
-
- assert_eq!(
- selected(&pin, &mut state, opening.clone()).await?,
- Some("efficient".to_string())
- );
- let mut followed_up = opening;
- followed_up.push(user("now find the race condition"));
- assert_eq!(selected(&pin, &mut state, followed_up.clone()).await?, None);
-
- // The abstaining turn is served by the fall-through default, so its tool
- // continuations must not reuse the target pinned by the previous turn.
- followed_up.push(tool_call("call-1"));
- followed_up.push(tool_result("call-1"));
- assert_eq!(
- selected(&pin, &mut state, followed_up).await?,
- Some("capable".to_string())
- );
- assert_eq!(inner.consultations(), 3);
- Ok(())
- }
-
- #[test]
- fn a_turn_starts_only_when_the_user_spoke_last() {
- let mut messages = vec![user("debug this")];
- assert!(starts_new_turn(&messages));
- messages.push(tool_call("call-1"));
- assert!(!starts_new_turn(&messages));
- // Anthropic sends this as a user-role message, so it must not count as a turn.
- messages.push(tool_result("call-1"));
- assert!(!starts_new_turn(&messages));
- messages.push(user("still broken"));
- assert!(starts_new_turn(&messages));
- assert!(!starts_new_turn(&[]));
-
- // A tool result the user appended to counts, because the user did speak.
- let mut mixed = tool_result("call-2");
- mixed.content.extend(user("and also rename foo").content);
- assert!(starts_new_turn(&[mixed]));
- }
-}
diff --git a/crates/libsy/src/lib.rs b/crates/libsy/src/lib.rs
index 231072ba7..b1f9c2943 100644
--- a/crates/libsy/src/lib.rs
+++ b/crates/libsy/src/lib.rs
@@ -23,7 +23,7 @@ pub use algorithms::noop::Noop;
pub use algorithms::passthrough::{Passthrough, PassthroughConfig, PassthroughSubagentConfig};
pub use algorithms::rand::{Random, RandomClassifier};
pub use algorithms::stage::{LlmFallback, StageRouter, StageRouterConfig};
-pub use algorithms::util::affinity::AffinityRouter;
+pub use algorithms::util::affinity::{AffinityRouter, ClassifyTrigger};
pub use algorithms::util::classifier_contract::{
ClassifierContractConfig, ClassifierResponseFormat,
};
@@ -31,7 +31,6 @@ pub use algorithms::util::escalation::EscalationJudgeConfig;
pub use algorithms::util::prompts::{SystemPromptProcessor, TargetPrompts, append_note};
pub use algorithms::util::subagent::{SubagentGate, SubagentOverride};
pub use algorithms::util::tool_signals::{DEFAULT_RECENT_WINDOW, ToolSignals};
-pub use algorithms::util::turn_pin::ClassifyTrigger;
// Stage-router scoring and tier selection — the shared signal-driven routing
// core (scorer, picker, and the `StageClassifier`).