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
feat(switchyard-server): Add `/v1/routing/session-stats` (#225)
Graham King02d3f234b593
diff --git a/Cargo.lock b/Cargo.lockindex 67e410ec5..71f7048b8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -692,6 +692,12 @@ version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"+[[package]]+name = "humantime"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15"+[[package]]name = "hyper"version = "1.10.1"@@ -2074,6 +2080,7 @@ dependencies = ["clap","futures-util","http-body-util",+ "humantime","opentelemetry","opentelemetry-otlp","opentelemetry-prometheus",diff --git a/crates/switchyard-server/Cargo.toml b/crates/switchyard-server/Cargo.tomlindex 492089774..c0d1b52c7 100644--- a/crates/switchyard-server/Cargo.toml+++ b/crates/switchyard-server/Cargo.toml@@ -31,6 +31,7 @@ toml = "1.1"switchyard-llm-client.workspace = trueserde_json.workspace = trueswitchyard-translation.workspace = true+humantime = "2.4"tokio.workspace = truetracing.workspace = truetracing-opentelemetry = "0.33"diff --git a/crates/switchyard-server/README.md b/crates/switchyard-server/README.mdindex 343c14da8..e92e47f4c 100644--- a/crates/switchyard-server/README.md+++ b/crates/switchyard-server/README.md@@ -78,6 +78,14 @@ responses.Random-route `weights` are relative, follow target order, and do not need to sum to one. Omit themfor equal weighting. The optional `seed` reproduces the selection sequence for the same call order.+## Session routing log++Pass `--routing-log-file PATH` to append one JSON record after each completed routed response.+Streaming responses are recorded after the stream drains. When enabled,+`GET /v1/routing/session-stats?session_id=ID` rescans the durable log and returns call and token+totals for that exact `proxy_x_session_id`, grouped by served model. The endpoint returns `404` when+the session has no records and is not registered when routing logging is disabled.+An `llm_classifier` route sends each task to `classifier_target` for a capability verdict, thenroutes to `weak_target` or `strong_target`. Beyond the three targets it accepts these keys; only`base_threshold` is required, and anything the judge cannot decide routes to `strong_target`:diff --git a/crates/switchyard-server/src/cli.rs b/crates/switchyard-server/src/cli.rsindex ac176f288..b31dd9b0f 100644--- a/crates/switchyard-server/src/cli.rs+++ b/crates/switchyard-server/src/cli.rs@@ -44,6 +44,10 @@ pub(crate) struct ServerArgs {#[arg(long)]dry_run: bool,+ /// Append durable per-request routing records to this JSONL file.+ #[arg(long, value_name = "PATH")]+ routing_log_file: Option<PathBuf>,+/// TLS certificate path in PEM format.#[arg(long, requires = "tls_key")]tls_cert: Option<PathBuf>,@@ -60,7 +64,10 @@ impl ServerArgs {}fn into_runtime(self) -> ServerResult<(ServerState, ServerRunOptions)> {- let state = load_server_state(&self.config)?;+ let mut state = load_server_state(&self.config)?;+ if let Some(path) = self.routing_log_file {+ state = state.with_routing_log(path)?;+ }let tls = match (self.tls_cert, self.tls_key) {(Some(cert), Some(key)) => {if !cert.exists() || !key.exists() {diff --git a/crates/switchyard-server/src/lib.rs b/crates/switchyard-server/src/lib.rsindex be00ffc59..d90ed6465 100644--- a/crates/switchyard-server/src/lib.rs+++ b/crates/switchyard-server/src/lib.rs@@ -7,6 +7,7 @@ pub mod config;mod metrics;mod observability;mod response;+mod routing_log;mod sse;mod stats;mod usage_metrics;@@ -21,7 +22,8 @@ use std::path::PathBuf;use std::sync::Arc;use std::time::{Duration, Instant};-use axum::extract::{rejection::JsonRejection, DefaultBodyLimit, Request as HttpRequest, State};+use axum::extract::rejection::{JsonRejection, QueryRejection};+use axum::extract::{DefaultBodyLimit, Query, Request as HttpRequest, State};use axum::http::header::CONTENT_TYPE;use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode};use axum::middleware::Next;@@ -31,10 +33,13 @@ use axum::{Extension, Json, Router};use axum_server::tls_rustls::RustlsConfig;use libsy::{Algorithm, Context, Decision, LibsyError, LlmClientError, Metadata, Request, RunObservation,- RunObserver,+ RunObserver, Usage,};+use parking_lot::Mutex;+use serde::Deserialize;use serde_json::{json, Value};use tokio::net::{TcpListener, TcpSocket};+use tokio::task;use tracing::{Instrument, Level};use switchyard_translation::{decode_request, WireFormat};@@ -87,9 +92,44 @@ pub struct ServerState {routes: Arc<BTreeMap<String, Arc<dyn Algorithm>>>,metrics: prometheus::Registry,stats: StatsAccumulator,+ routing_log: Option<SharedRoutingLog>,track_cache_eligibility: bool,}+#[derive(Clone)]+struct SharedRoutingLog {+ writer: Arc<Mutex<routing_log::RoutingLog>>,+ path: PathBuf,+}++impl SharedRoutingLog {+ fn new(path: PathBuf) -> ServerResult<Self> {+ Ok(Self {+ writer: Arc::new(Mutex::new(routing_log::RoutingLog::new(path.clone())?)),+ path,+ })+ }++ fn append(+ &self,+ context: routing_log::RoutingLogContext,+ model: &str,+ tier: Option<&str>,+ usage: &Usage,+ ) {+ if let Err(error) = self.writer.lock().append(context, model, tier, usage) {+ tracing::warn!(path = %self.path.display(), %error, "routing log append failed");+ }+ }++ fn snapshot_session(+ &self,+ session_id: &str,+ ) -> std::io::Result<Option<routing_log::SessionStatsSnapshot>> {+ routing_log::snapshot(&self.path, session_id)+ }+}+impl ServerState {/// Creates server state from route model IDs and their libsy algorithms.pub fn new(@@ -113,10 +153,17 @@ impl ServerState {routes: Arc::new(entries),metrics,stats: StatsAccumulator::default(),+ routing_log: None,track_cache_eligibility: tracking_enabled_from_env(),})}+ /// Enables durable per-request routing records at `path`.+ pub fn with_routing_log(mut self, path: impl Into<PathBuf>) -> ServerResult<Self> {+ self.routing_log = Some(SharedRoutingLog::new(path.into())?);+ Ok(self)+ }+/// Returns the route model IDs served by the configured algorithms.pub fn models(&self) -> impl Iterator<Item = &str> {self.routes.keys().map(String::as_str)@@ -295,7 +342,7 @@ async fn stamp_request_start(mut request: HttpRequest, next: Next) -> Response {/// Builds an Axum router for the supported LLM wire formats.pub fn build_switchyard_router(state: ServerState) -> Router {- Router::new()+ let mut router = Router::new().route("/v1/chat/completions", post(openai_chat_completions)).route("/v1/messages", post(anthropic_messages)).route("/v1/responses", post(openai_responses))@@ -304,7 +351,11 @@ pub fn build_switchyard_router(state: ServerState) -> Router {.route("/v1/stats", get(get_stats)).route("/v1/stats/reset", post(reset_stats)).route("/metrics", get(prometheus_metrics))- .route("/health", get(health))+ .route("/health", get(health));+ if state.routing_log.is_some() {+ router = router.route("/v1/routing/session-stats", get(get_session_stats));+ }+ router.fallback(not_found).layer(DefaultBodyLimit::max(DEFAULT_MAX_REQUEST_BODY_BYTES))// `layer` only wraps routes registered before it, so this stays last.@@ -432,6 +483,10 @@ async fn handle_endpoint_inner(body: std::result::Result<Json<Value>, JsonRejection>,wire_format: WireFormat,) -> Response {+ let routing_log_context = state+ .routing_log+ .as_ref()+ .map(|_| routing_log::RoutingLogContext::from_headers(&normalized_headers(&headers)));let metadata = metadata_from_headers(&headers);let request_log = RequestLogContext {started: started.0,@@ -453,7 +508,17 @@ async fn handle_endpoint_inner(};let response = match llm_json_body(body) {- Ok(body) => handle_llm_request(state, started, metadata, body, wire_format).await,+ Ok(body) => {+ handle_llm_request(+ state,+ started,+ metadata,+ body,+ wire_format,+ routing_log_context,+ )+ .await+ }Err(message) => invalid_body_error(message),};metrics::record_client_response(response.status().as_u16());@@ -520,6 +585,7 @@ async fn handle_llm_request(metadata: Metadata,body: Value,wire_format: WireFormat,+ routing_log_context: Option<routing_log::RoutingLogContext>,) -> Response {let cache_probe = state.track_cache_eligibility.then(|| prefix_probe(&body));let (algorithm, request) = match resolve_route(&state, metadata, body, wire_format) {@@ -555,6 +621,7 @@ async fn handle_llm_request(started.0,state.stats,cache_eligible,+ state.routing_log.zip(routing_log_context),)} else {response@@ -787,6 +854,54 @@ async fn reset_stats(State(state): State<ServerState>) -> Json<Value> {Json(json!({"status": "reset"}))}+#[derive(Deserialize)]+struct SessionStatsQuery {+ session_id: String,+}++// TODO: This loads the entire file. It should stream the JSONL instead.+// Huge files will crash the demo server.+async fn get_session_stats(+ State(state): State<ServerState>,+ query: std::result::Result<Query<SessionStatsQuery>, QueryRejection>,+) -> Response {+ let Query(query) = match query {+ Ok(query) => query,+ Err(error) => {+ return error_response(+ StatusCode::BAD_REQUEST,+ error.to_string(),+ "invalid_request_error",+ "invalid_query",+ )+ }+ };+ let Some(routing_log) = state.routing_log else {+ // Should be unreachable+ return not_found().await;+ };+ let session_id = query.session_id.clone();+ // Loading and de-serializing a large file is a time consuming blocking operation+ let snapshot =+ match task::spawn_blocking(move || routing_log.snapshot_session(&session_id)).await {+ Ok(s) => s,+ Err(err) => {+ return server_error(format!("failed to snapshot: {err}"));+ }+ };++ match snapshot {+ Ok(Some(snapshot)) => (StatusCode::OK, Json(snapshot)).into_response(),+ Ok(None) => error_response(+ StatusCode::NOT_FOUND,+ "Routing session not found",+ "not_found",+ "routing_session_not_found",+ ),+ Err(error) => server_error(format!("failed to read routing log: {error}")),+ }+}+async fn health() -> Json<Value> {Json(json!({"status": "ok"}))}diff --git a/crates/switchyard-server/src/routing_log.rs b/crates/switchyard-server/src/routing_log.rsnew file mode 100644index 000000000..fcc851c83--- /dev/null+++ b/crates/switchyard-server/src/routing_log.rs@@ -0,0 +1,252 @@+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+// SPDX-License-Identifier: Apache-2.0++//! Durable per-request routing records and session snapshots.++use std::borrow::Cow;+use std::collections::BTreeMap;+use std::fs;+use std::io::{BufRead, BufReader, Write};+use std::path::{Path, PathBuf};+use std::time::SystemTime;++use humantime::format_rfc3339_millis;+use libsy::Usage;+use serde::{Deserialize, Serialize};++use crate::usage_metrics::token_usage;+use crate::{ServerError, ServerResult};++const SESSION_ID_HEADER: &str = "proxy_x_session_id";+const TASK_HEADER: &str = "x-switchyard-intake-task";+const TRIAL_ID_HEADER: &str = "x-switchyard-trial-id";++/// Append-only writer for one routing JSONL file.+pub(crate) struct RoutingLog(fs::File);++impl RoutingLog {+ pub(crate) fn new(path: impl Into<PathBuf>) -> ServerResult<Self> {+ let path = path.into();+ if let Some(parent) = path+ .parent()+ .filter(|parent| !parent.as_os_str().is_empty())+ {+ fs::create_dir_all(parent).map_err(|error| routing_log_error(&path, error))?;+ }+ let file = fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(&path)+ .map_err(|error| routing_log_error(&path, error))?;+ Ok(Self(file))+ }++ pub(crate) fn append(+ &mut self,+ context: RoutingLogContext,+ model: &str,+ tier: Option<&str>,+ usage: &Usage,+ ) -> std::io::Result<()> {+ let usage = token_usage(usage);+ let record = RoutingRecord {+ ts: format_rfc3339_millis(SystemTime::now()).to_string().into(),+ task: context.task.map(Cow::Owned),+ trial_id: context.trial_id.map(Cow::Owned),+ session_id: context.session_id.map(Cow::Owned),+ model: model.into(),+ tier: tier.unwrap_or("").into(),+ prompt_tokens: usage.prompt_tokens,+ cached_tokens: usage.cached_tokens,+ cache_creation_tokens: usage.cache_creation_tokens,+ completion_tokens: usage.completion_tokens,+ reasoning_tokens: usage.reasoning_tokens,+ total_tokens: usage.prompt_tokens.saturating_add(usage.completion_tokens),+ };+ let mut line = serde_json::to_vec(&record).map_err(std::io::Error::other)?;+ line.push(b'\n');++ self.0.write_all(&line)+ }+}++/// Reads complete records without synchronizing with the writer.+pub(crate) fn snapshot(+ path: &Path,+ session_id: &str,+) -> std::io::Result<Option<SessionStatsSnapshot>> {+ let mut reader = BufReader::with_capacity(64 * 1024, fs::File::open(path)?);+ let mut line = Vec::new();+ let mut snapshot = SessionStatsSnapshot::new(session_id);+ loop {+ line.clear();+ if reader.read_until(b'\n', &mut line)? == 0 {+ break;+ }+ if !line.ends_with(b"\n") {+ break;+ }+ let Ok(record) = serde_json::from_slice::<RoutingRecord>(&line) else {+ continue;+ };+ snapshot.add_record(&record, session_id);+ }+ snapshot.sum_totals();+ Ok((snapshot.total_calls > 0).then_some(snapshot))+}++/// Request headers retained until terminal usage is available.+pub(crate) struct RoutingLogContext {+ task: Option<String>,+ trial_id: Option<String>,+ session_id: Option<String>,+}++impl RoutingLogContext {+ pub(crate) fn from_headers(headers: &BTreeMap<String, String>) -> Self {+ Self {+ task: nonempty_header(headers, TASK_HEADER),+ trial_id: nonempty_header(headers, TRIAL_ID_HEADER),+ session_id: nonempty_header(headers, SESSION_ID_HEADER),+ }+ }+}++/// One appended routing record, and the read schema [`snapshot`] parses back,+/// so the written and expected shapes cannot drift apart. Missing fields+/// default so a record from an older schema still contributes what it has.+#[derive(Default, Deserialize, Serialize)]+#[serde(default)]+struct RoutingRecord<'a> {+ ts: Cow<'a, str>,+ #[serde(borrow)]+ task: Option<Cow<'a, str>>,+ #[serde(borrow)]+ trial_id: Option<Cow<'a, str>>,+ #[serde(borrow)]+ session_id: Option<Cow<'a, str>>,+ model: Cow<'a, str>,+ tier: Cow<'a, str>,+ prompt_tokens: u64,+ cached_tokens: u64,+ cache_creation_tokens: u64,+ completion_tokens: u64,+ reasoning_tokens: u64,+ total_tokens: u64,+}++/// Session totals returned by the routing stats endpoint.+#[derive(Serialize)]+pub(crate) struct SessionStatsSnapshot {+ session_id: String,+ total_calls: u64,+ total_prompt_tokens: u64,+ total_cached_tokens: u64,+ total_cache_creation_tokens: u64,+ total_completion_tokens: u64,+ models: BTreeMap<String, SessionModelStats>,+}++#[derive(Default, Serialize)]+struct SessionModelStats {+ calls: u64,+ prompt_tokens: u64,+ cached_tokens: u64,+ cache_creation_tokens: u64,+ completion_tokens: u64,+}++impl SessionStatsSnapshot {+ fn new(session_id: &str) -> Self {+ Self {+ session_id: session_id.to_string(),+ total_calls: 0,+ total_prompt_tokens: 0,+ total_cached_tokens: 0,+ total_cache_creation_tokens: 0,+ total_completion_tokens: 0,+ models: BTreeMap::new(),+ }+ }++ fn add_record(&mut self, record: &RoutingRecord<'_>, session_id: &str) {+ if record.session_id.as_deref() != Some(session_id) {+ return;+ }+ let model = match record.model.as_ref() {+ "" => "unknown",+ model => model,+ };+ let stats = self.models.entry(model.to_string()).or_default();+ stats.calls = stats.calls.saturating_add(1);+ stats.prompt_tokens = stats.prompt_tokens.saturating_add(record.prompt_tokens);+ stats.cached_tokens = stats.cached_tokens.saturating_add(record.cached_tokens);+ stats.cache_creation_tokens = stats+ .cache_creation_tokens+ .saturating_add(record.cache_creation_tokens);+ stats.completion_tokens = stats+ .completion_tokens+ .saturating_add(record.completion_tokens);+ }++ /// Session totals are exactly the sum of the per-model stats, so they are+ /// derived once rather than accumulated alongside them.+ fn sum_totals(&mut self) {+ for stats in self.models.values() {+ self.total_calls = self.total_calls.saturating_add(stats.calls);+ self.total_prompt_tokens = self.total_prompt_tokens.saturating_add(stats.prompt_tokens);+ self.total_cached_tokens = self.total_cached_tokens.saturating_add(stats.cached_tokens);+ self.total_cache_creation_tokens = self+ .total_cache_creation_tokens+ .saturating_add(stats.cache_creation_tokens);+ self.total_completion_tokens = self+ .total_completion_tokens+ .saturating_add(stats.completion_tokens);+ }+ }+}++fn nonempty_header(headers: &BTreeMap<String, String>, name: &str) -> Option<String> {+ headers.get(name).filter(|value| !value.is_empty()).cloned()+}++fn routing_log_error(path: &Path, error: std::io::Error) -> ServerError {+ ServerError::new(format!(+ "failed to initialize routing log {}: {error}",+ path.display()+ ))+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Only the requested session is counted, absent fields fall back to zero+ /// and `unknown`, and an unparseable line does not abort the scan.+ #[test]+ fn snapshot_counts_only_the_requested_session() {+ let dir = tempfile::tempdir().expect("temp dir");+ let path = dir.path().join("routing.jsonl");+ fs::write(+ &path,+ concat!(+ r#"{"session_id":"a","model":"m1","prompt_tokens":10,"completion_tokens":2}"#,+ "\n",+ r#"{"session_id":"b","model":"m1","prompt_tokens":99,"completion_tokens":99}"#,+ "\n",+ "not json\n",+ r#"{"session_id":"a","prompt_tokens":5}"#,+ "\n",+ ),+ )+ .expect("write log");++ let stats = snapshot(&path, "a").expect("read log").expect("session a");+ assert_eq!(stats.total_calls, 2);+ assert_eq!(stats.total_prompt_tokens, 15);+ assert_eq!(stats.total_completion_tokens, 2);+ assert_eq!(stats.models["m1"].calls, 1);+ assert_eq!(stats.models["unknown"].prompt_tokens, 5);+ assert!(snapshot(&path, "missing").expect("read log").is_none());+ }+}diff --git a/crates/switchyard-server/src/usage_metrics.rs b/crates/switchyard-server/src/usage_metrics.rsindex 341e23e66..6937b585f 100644--- a/crates/switchyard-server/src/usage_metrics.rs+++ b/crates/switchyard-server/src/usage_metrics.rs@@ -9,7 +9,9 @@ use futures_util::StreamExt;use libsy::{LlmResponse, LlmResponseChunk, Response, Usage};use opentelemetry::{global, KeyValue};+use crate::routing_log::RoutingLogContext;use crate::stats::{StatsAccumulator, TokenUsage};+use crate::SharedRoutingLog;/// Observes a routed response without changing its aggregate or streaming contents.pub(crate) fn observe(@@ -19,6 +21,7 @@ pub(crate) fn observe(started: Instant,stats: StatsAccumulator,cache_eligible: f64,+ routing_log: Option<(SharedRoutingLog, RoutingLogContext)>,) -> Response {let Response {llm_response,@@ -37,6 +40,9 @@ pub(crate) fn observe(started,cache_eligible,);+ if let Some((log, context)) = routing_log {+ log.append(context, &model, tier.as_deref(), &agg.usage);+ }LlmResponse::Agg(agg)}LlmResponse::Stream(mut stream) => {@@ -59,14 +65,18 @@ pub(crate) fn observe(return;}}+ let usage = latest_usage.unwrap_or_default();record_terminal(&stats,- &latest_usage.unwrap_or_default(),+ &usage,&model,tier.as_deref(),started,cache_eligible,);+ if let Some((log, context)) = routing_log {+ log.append(context, &model, tier.as_deref(), &usage);+ }};LlmResponse::Stream(Box::pin(wrapped))}diff --git a/crates/switchyard-server/tests/server.rs b/crates/switchyard-server/tests/server.rsindex be9322568..2a5cea95b 100644--- a/crates/switchyard-server/tests/server.rs+++ b/crates/switchyard-server/tests/server.rs@@ -935,6 +935,49 @@ async fn all_inbound_formats_run_libsy_and_return_the_caller_format() -> TestResOk(())}+#[tokio::test]+async fn routing_log_exposes_session_stats() -> TestResult {+ let upstream = MockUpstream::start().await?;+ let temp_dir = tempfile::tempdir()?;+ let log_path = temp_dir.path().join("routing.jsonl");+ let state = random_state(&upstream.base_url, &[(ROUTE_MODEL, &["model/a"])])?+ .with_routing_log(&log_path)?;+ let app = build_switchyard_router(state);++ let request = HttpRequest::builder()+ .method("POST")+ .uri("/v1/chat/completions")+ .header("content-type", "application/json")+ .header("proxy_x_session_id", "session-1")+ .body(Body::from(serde_json::to_vec(&json!({+ "model": ROUTE_MODEL,+ "messages": [{"role": "user", "content": "hello"}]+ }))?))?;+ let response = app.clone().oneshot(request).await?;+ assert_eq!(response.status(), StatusCode::OK);++ let stats = send(+ &app,+ "GET",+ "/v1/routing/session-stats?session_id=session-1",+ None,+ )+ .await?+ .json()?;+ assert_eq!(stats["total_calls"], 1);+ assert_eq!(stats["total_prompt_tokens"], 10);+ assert_eq!(stats["total_cached_tokens"], 7);+ assert_eq!(stats["models"]["model/a"]["completion_tokens"], 2);++ let records = std::fs::read_to_string(log_path)?;+ let first: Value =+ serde_json::from_str(records.lines().next().ok_or("routing log was empty")?)?;+ assert!(first["ts"]+ .as_str()+ .is_some_and(|value| value.ends_with('Z')));+ Ok(())+}+#[tokio::test]async fn streaming_response_is_framed_for_the_inbound_api() -> TestResult {let (_upstream, app) = test_app(&[(ROUTE_MODEL, &["model/a"])]).await?;