Skip to main content

switchyard_libsy/algorithms/util/
cache_history.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::collections::{HashMap, VecDeque};
5
6use switchyard_costs::Pricing;
7use switchyard_protocol::{ModelId, Usage};
8
9const RECENT_TURNS: usize = 8;
10
11/// Per-agent input usage observed inside one Stage session.
12#[derive(Clone, Debug, Default)]
13pub struct StageCacheHistory(HashMap<String, AgentHistory>);
14
15#[derive(Clone, Debug, Default)]
16struct AgentHistory {
17    served: Option<ModelId>,
18    models: HashMap<ModelId, VecDeque<InputTokens>>,
19}
20
21#[derive(Clone, Copy, Debug)]
22struct InputTokens {
23    total: u64,
24    cached: u64,
25    continued: bool,
26}
27
28impl InputTokens {
29    fn from_usage(usage: &Usage, continued: bool) -> Option<Self> {
30        let cached = usage.cached_input_tokens()?;
31        let total = usage
32            .input_tokens?
33            .checked_add(cached)?
34            .checked_add(usage.cache_creation_input_tokens().unwrap_or(0))?;
35        (total > 0).then_some(Self {
36            total,
37            cached,
38            continued,
39        })
40    }
41}
42
43impl StageCacheHistory {
44    pub(crate) fn record(&mut self, agent: Option<&str>, model: &ModelId, usage: Option<&Usage>) {
45        let agent = agent.unwrap_or_default();
46        let history = match self.0.get_mut(agent) {
47            Some(history) => history,
48            None => self.0.entry(agent.to_owned()).or_default(),
49        };
50        let continued = history.served.as_ref() == Some(model);
51        if !continued {
52            history.served = Some(model.clone());
53        }
54        if let Some(tokens) = usage.and_then(|usage| InputTokens::from_usage(usage, continued)) {
55            if let Some(window) = history.models.get_mut(model) {
56                if window.len() == RECENT_TURNS {
57                    window.pop_front();
58                }
59                window.push_back(tokens);
60            } else {
61                history
62                    .models
63                    .insert(model.clone(), VecDeque::from([tokens]));
64            }
65        } else {
66            history.models.remove(model);
67        }
68    }
69
70    /// Returns the last serving model and the fraction of input cost saved by staying.
71    /// Both estimates use the same next prompt, so its token count cancels.
72    pub(crate) fn savings_on_switch(
73        &self,
74        agent: Option<&str>,
75        switch: &ModelId,
76        pricing: &Pricing,
77    ) -> Option<(&ModelId, f64)> {
78        let history = self.0.get(agent.unwrap_or_default())?;
79        let stay = history.served.as_ref()?;
80        if stay == switch {
81            return None;
82        }
83        let unit_cost = |model: &ModelId| {
84            let window = history.models.get(model)?;
85            // Two same-model continuations give a warmer estimate for staying.
86            // Returning to a model uses its whole window, including cold turns.
87            let continuations_only =
88                model == stay && window.iter().filter(|t| t.continued).nth(1).is_some();
89            let (total, cached) = window
90                .iter()
91                .filter(|turn| !continuations_only || turn.continued)
92                .try_fold((0_u64, 0_u64), |(total, cached), turn| {
93                    Some((
94                        total.checked_add(turn.total)?,
95                        cached.checked_add(turn.cached)?,
96                    ))
97                })?;
98            Some(pricing.estimate_input_cost(model.as_str(), total, cached)? / total as f64)
99        };
100        let stay_cost = unit_cost(stay)?;
101        let switch_cost = unit_cost(switch)?;
102        (switch_cost > stay_cost).then(|| (stay, (switch_cost - stay_cost) / switch_cost))
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn stay_uses_two_recent_continuations_and_return_uses_the_full_window() {
112        let a = ModelId::from("a");
113        let b = ModelId::from("b");
114        let prices = Pricing::parse(br#"{"prices":[{"models":["a","b"],"input":1,"cache_read":0,"output":1,"cache_write":1}]}"#).unwrap();
115        let mut history = StageCacheHistory::default();
116        let record = |history: &mut StageCacheHistory, model: &ModelId, regular, cached| {
117            history.record(
118                None,
119                model,
120                Some(&Usage {
121                    input_tokens: Some(regular),
122                    cache: Usage::cache_details(Some(cached), None),
123                    ..Default::default()
124                }),
125            );
126        };
127        let saved =
128            |history: &StageCacheHistory| history.savings_on_switch(None, &b, &prices).unwrap().1;
129        record(&mut history, &b, 100, 0);
130        record(&mut history, &b, 0, 100);
131        record(&mut history, &b, 0, 100);
132        record(&mut history, &a, 60, 40);
133        record(&mut history, &a, 0, 100);
134        assert!((saved(&history) - 0.1).abs() < 1e-10);
135
136        record(&mut history, &a, 60, 140);
137        assert!((saved(&history) - 0.4).abs() < 1e-10);
138        record(&mut history, &b, 100, 0);
139        record(&mut history, &a, 100, 0);
140        assert!((saved(&history) - 0.6).abs() < 1e-10);
141
142        for _ in 0..RECENT_TURNS {
143            record(&mut history, &b, 100, 0);
144            record(&mut history, &a, 50, 50);
145        }
146        assert!((saved(&history) - 0.5).abs() < 1e-10);
147    }
148
149    #[test]
150    fn requires_reported_usage_known_prices_and_a_cheaper_stay() {
151        let a = ModelId::from("a");
152        let b = ModelId::from("b");
153        let prices = Pricing::parse(br#"{"prices":[{"models":["a","b"],"input":10,"cache_read":0,"output":50,"cache_write":20}]}"#).unwrap();
154        let mut history = StageCacheHistory::default();
155        let usage = |input, cached, writes| Usage {
156            input_tokens: Some(input),
157            cache: Usage::cache_details(cached, writes),
158            ..Usage::default()
159        };
160        // Both models must have observations, and a reported zero is usable.
161        history.record(None, &b, Some(&usage(500, Some(0), None)));
162        assert!(history.savings_on_switch(None, &a, &prices).is_none());
163        history.record(None, &a, Some(&usage(0, Some(200), Some(100))));
164        history.record(None, &a, Some(&usage(100, Some(0), None)));
165        let (previous, saved) = history.savings_on_switch(None, &b, &prices).unwrap();
166        assert_eq!(previous, &a);
167        assert!((saved - 0.5).abs() < 1e-10);
168        assert!(history.savings_on_switch(None, &a, &prices).is_none());
169        assert!(
170            history
171                .savings_on_switch(None, &b, &Pricing::default())
172                .is_none()
173        );
174
175        history.record(None, &a, None);
176        assert!(history.savings_on_switch(None, &b, &prices).is_none());
177        history.record(None, &a, Some(&usage(500, Some(0), None)));
178        assert!(history.savings_on_switch(None, &b, &prices).is_none());
179
180        history.record(None, &b, Some(&usage(10, None, None)));
181        history.record(None, &a, Some(&usage(0, Some(1_000), None)));
182        assert!(history.savings_on_switch(None, &b, &prices).is_none());
183    }
184}