Skip to main content

agentmux_srv_core/backend/model_gateway/
spend.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What each agent has used through the gateway today, counted from the usage in each response times
5//! the route's price table. The live table is in memory; once [`attach`] has been called every change is also
6//! written to the history store (`storage::spend_day`) and the last two days are read back at start, so an srv
7//! restart does not start the day again. The day is the UTC day.
8
9use super::catalog::Model;
10use crate::agents::types::TokenCounts;
11use crate::backend::storage::spend_day::SpendDayRow;
12use crate::backend::storage::store::Store;
13use std::collections::{HashMap, HashSet};
14use std::sync::{mpsc, Arc, Mutex, OnceLock};
15
16#[derive(Debug, Clone, Default, PartialEq)]
17pub struct Spend {
18    pub requests: u64,
19    pub tokens: TokenCounts,
20    pub cost_usd: f64,
21}
22
23/// One agent's day on one route, with the highest alert level already sent for the agent's day.
24#[derive(Debug, Clone, Default)]
25struct Day {
26    spend: Spend,
27    alerted: u8,
28}
29
30/// Agent, route and UTC day.
31type DayKey = (String, String, i64);
32
33fn table() -> &'static Mutex<HashMap<DayKey, Day>> {
34    static TABLE: OnceLock<Mutex<HashMap<DayKey, Day>>> = OnceLock::new();
35    TABLE.get_or_init(Default::default)
36}
37
38enum Write {
39    Save(SpendDayRow),
40    Clear(String, i64),
41}
42
43/// The writer thread's inbox, once [`attach`] has started it. A change is queued, not written, so a response
44/// settling (on the stream's task) never waits on SQLite.
45fn writer() -> &'static OnceLock<mpsc::Sender<Write>> {
46    static WRITER: OnceLock<mpsc::Sender<Write>> = OnceLock::new();
47    &WRITER
48}
49
50fn row_of(key: &DayKey, day: &Day) -> SpendDayRow {
51    let t = &day.spend.tokens;
52    SpendDayRow {
53        agent_id: key.0.clone(),
54        route: key.1.clone(),
55        day: key.2,
56        requests: day.spend.requests,
57        input: t.input,
58        output: t.output,
59        cache_creation: t.cache_creation,
60        cache_read: t.cache_read,
61        cost_usd: day.spend.cost_usd,
62        alerted: day.alerted,
63    }
64}
65
66fn queue(write: Write) {
67    if let Some(tx) = writer().get() {
68        let _ = tx.send(write);
69    }
70}
71
72/// Reads the last two days back from `store` into the live table, keeping what the table already holds.
73/// Returns the number of rows read.
74pub fn restore(store: &Store, now_ms: i64) -> usize {
75    let rows = match store.spend_day_load(day(now_ms) - 1) {
76        Ok(rows) => rows,
77        Err(e) => {
78            tracing::warn!(error = %e, "model gateway: the spend of earlier days could not be read; today starts at zero");
79            return 0;
80        }
81    };
82    let mut table = table().lock().unwrap();
83    let n = rows.len();
84    for r in rows {
85        let spend = Spend {
86            requests: r.requests,
87            tokens: TokenCounts { input: r.input, output: r.output, cache_creation: r.cache_creation, cache_read: r.cache_read, ..Default::default() },
88            cost_usd: r.cost_usd,
89        };
90        table.entry((r.agent_id, r.route, r.day)).or_insert(Day { spend, alerted: r.alerted });
91    }
92    n
93}
94
95/// Keeps the day's table in `store` from now on: reads the last two days, then writes each change from a thread of its own.
96pub fn attach(store: Arc<Store>) {
97    let restored = restore(&store, agentmux_common::time::now_ms());
98    let (tx, rx) = mpsc::channel::<Write>();
99    if writer().set(tx).is_err() {
100        return;
101    }
102    tracing::info!(rows = restored, "model gateway: the day's spend is kept in the history store");
103    let spawned = std::thread::Builder::new().name("gateway-spend".into()).spawn(move || {
104        for write in rx {
105            let done = match write {
106                Write::Save(row) => store.spend_day_save(&row),
107                Write::Clear(agent, d) => store.spend_day_clear(&agent, d).map(|_| ()),
108            };
109            if let Err(e) = done {
110                tracing::warn!(error = %e, "model gateway: a day of spend was not written");
111            }
112        }
113    });
114    if let Err(e) = spawned {
115        tracing::warn!(error = %e, "model gateway: the spend writer did not start; the day is kept in memory only");
116    }
117}
118
119/// Provider-reported spend per agent since its current process started (see
120/// [`reset_session`]). An agent whose responses never carried a charge (not on
121/// a route) has no entry, and keeps the price-table estimate.
122fn sessions() -> &'static Mutex<HashMap<String, f64>> {
123    static SESSIONS: OnceLock<Mutex<HashMap<String, f64>>> = OnceLock::new();
124    SESSIONS.get_or_init(Default::default)
125}
126
127/// The agents whose responses have carried a provider charge: they are on a
128/// route, so a response of theirs that reports none is priced by the route's
129/// own table and still belongs in their session total.
130fn routed() -> &'static Mutex<HashSet<String>> {
131    static ROUTED: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
132    ROUTED.get_or_init(Default::default)
133}
134
135/// The cumulative provider total last put on a `result` frame, per agent: what
136/// a frame's turn-scoped `cost_usd` is measured from.
137fn last_totals() -> &'static Mutex<HashMap<String, f64>> {
138    static LAST: OnceLock<Mutex<HashMap<String, f64>>> = OnceLock::new();
139    LAST.get_or_init(Default::default)
140}
141
142/// Clears `agent`'s provider-reported session total: a new process (spawn,
143/// restart, resume) starts its own, as the harness's own total does.
144pub fn reset_session(agent: &str) {
145    sessions().lock().unwrap().remove(agent);
146    last_totals().lock().unwrap().remove(agent);
147    routed().lock().unwrap().remove(agent);
148}
149
150/// The provider-reported spend for `agent` since [`reset_session`], or `None`
151/// when none of its responses reported a charge (the agent is not on a route).
152pub fn session_usd(agent: &str) -> Option<f64> {
153    sessions().lock().unwrap().get(agent).copied()
154}
155
156fn day(now_ms: i64) -> i64 {
157    now_ms.div_euclid(86_400_000)
158}
159
160/// The cost of `tokens` on `model`: a cached read at the cache price, the rest of the input at the input price.
161pub fn cost(model: &Model, tokens: &TokenCounts) -> f64 {
162    let per_m = |n: u64, price: f64| n as f64 * price / 1_000_000.0;
163    per_m(tokens.input, model.price_in)
164        + per_m(tokens.cache_creation, super::catalog::cache_write_price(model))
165        + per_m(tokens.cache_read, model.price_cache_read)
166        + per_m(tokens.output, model.price_out)
167}
168
169/// Adds one response to the agent's day on `route` and returns that response's cost: the
170/// provider's own charge when the response reported one (`actual`), else the
171/// price table's estimate.
172pub fn record(agent: &str, route: &str, model: &Model, tokens: &TokenCounts, actual: Option<f64>, now_ms: i64) -> f64 {
173    let actual = actual.filter(|c| c.is_finite() && *c >= 0.0);
174    let cost = actual.unwrap_or_else(|| cost(model, tokens));
175    // A route agent's session total holds every response of its own, priced by
176    // the provider where it said and by the route's table where it did not (an
177    // interrupted stream, say); only a response that never saw a charge at all
178    // leaves an agent off a route with no total.
179    let on_route = match actual {
180        Some(_) => {
181            routed().lock().unwrap().insert(agent.to_string());
182            true
183        }
184        None => routed().lock().unwrap().contains(agent),
185    };
186    if on_route {
187        *sessions().lock().unwrap().entry(agent.to_string()).or_insert(0.0) += actual.unwrap_or(cost);
188    }
189    let mut table = table().lock().unwrap();
190    let day_now = day(now_ms);
191    // This agent's old days go; another agent's are dropped when it records, and `today` never reads them.
192    table.retain(|(a, _, d), _| a != agent || *d >= day_now - 1);
193    let key = (agent.to_string(), route.to_string(), day_now);
194    let entry = table.entry(key.clone()).or_default();
195    entry.spend.requests += 1;
196    entry.spend.tokens.input += tokens.input;
197    entry.spend.tokens.output += tokens.output;
198    entry.spend.tokens.cache_creation += tokens.cache_creation;
199    entry.spend.tokens.cache_read += tokens.cache_read;
200    entry.spend.cost_usd += cost;
201    queue(Write::Save(row_of(&key, entry)));
202    cost
203}
204
205/// `line`, a JSON frame from the harness, with a route agent's `result` totals
206/// replaced by the provider's own charge: the harness prices its tokens with
207/// Claude's rates, which on a route are wrong by orders of magnitude (#30143).
208/// `total_cost_usd` becomes the session total, which the turn ledger takes the
209/// rise of; `cost_usd` becomes this turn's rise, because the pane adds each
210/// frame's value to its running total. `None` when the line is not a `result`
211/// frame, reports no total, or the agent is not on a route (none of its
212/// responses carried a charge).
213pub fn rewrite_result_total(line: &str, agent: &str) -> Option<String> {
214    let real = session_usd(agent)?;
215    let mut frame: serde_json::Value = serde_json::from_str(line).ok()?;
216    if frame.get("type").and_then(serde_json::Value::as_str) != Some("result") {
217        return None;
218    }
219    frame.get("total_cost_usd")?.as_f64()?;
220    frame["total_cost_usd"] = serde_json::json!(real);
221    // `total_cost_usd` is the session total (the turn ledger takes its rise);
222    // `cost_usd` is turn-scoped — the pane ADDS each frame's value, so it must
223    // be the rise since the previous frame, never the cumulative total.
224    let previous = last_totals().lock().unwrap().insert(agent.to_string(), real).unwrap_or(0.0);
225    if frame.get("cost_usd").is_some() {
226        frame["cost_usd"] = serde_json::json!((real - previous).max(0.0));
227    }
228    Some(frame.to_string())
229}
230
231/// The agent's use so far today, over every route it used.
232pub fn today(agent: &str, now_ms: i64) -> Spend {
233    let d = day(now_ms);
234    let mut sum = Spend::default();
235    for (_, one) in table().lock().unwrap().iter().filter(|((a, _, day), _)| a == agent && *day == d) {
236        sum.requests += one.spend.requests;
237        sum.cost_usd += one.spend.cost_usd;
238        sum.tokens.input += one.spend.tokens.input;
239        sum.tokens.output += one.spend.tokens.output;
240        sum.tokens.cache_creation += one.spend.tokens.cache_creation;
241        sum.tokens.cache_read += one.spend.tokens.cache_read;
242    }
243    sum
244}
245
246/// The agents that have a day of spend today.
247pub fn agents_today(now_ms: i64) -> Vec<String> {
248    let d = day(now_ms);
249    let mut agents: Vec<String> = table().lock().unwrap().keys().filter(|(_, _, day)| *day == d).map(|(a, _, _)| a.clone()).collect();
250    agents.sort();
251    agents.dedup();
252    agents
253}
254
255/// What every agent has spent on `route` so far today.
256pub fn route_today_usd(route: &str, now_ms: i64) -> f64 {
257    let d = day(now_ms);
258    table().lock().unwrap().iter().filter(|((_, r, day), _)| r == route && *day == d).map(|(_, one)| one.spend.cost_usd).sum()
259}
260
261/// The highest alert level (0, 50, 80 or 100) already sent for the agent's day.
262pub fn alerted(agent: &str, now_ms: i64) -> u8 {
263    let d = day(now_ms);
264    table().lock().unwrap().iter().filter(|((a, _, day), _)| a == agent && *day == d).map(|(_, one)| one.alerted).max().unwrap_or(0)
265}
266
267/// Records the alert level sent for the agent's day, on each of its rows so it survives a restart. A raised cap sets it
268/// back down to where the day now stands.
269pub fn set_alerted(agent: &str, level: u8, now_ms: i64) {
270    let d = day(now_ms);
271    let mut table = table().lock().unwrap();
272    let mut any = false;
273    for (key, one) in table.iter_mut().filter(|((a, _, day), _)| a == agent && *day == d) {
274        one.alerted = level;
275        queue(Write::Save(row_of(key, one)));
276        any = true;
277    }
278    // An agent refused by its route's cap has spent nothing of its own today: its level lives on a row with no route.
279    if !any && level > 0 {
280        let key = (agent.to_string(), String::new(), d);
281        let one = Day { alerted: level, ..Default::default() };
282        queue(Write::Save(row_of(&key, &one)));
283        table.insert(key, one);
284    }
285}
286
287/// Zeroes the agent's day (a spend that was wrong): its rows are removed, here and in the store. Returns the
288/// dollars that were counted.
289pub fn reset_today(agent: &str, now_ms: i64) -> f64 {
290    let d = day(now_ms);
291    let mut removed = 0.0;
292    // The clear is queued before the lock is let go, so a response settling at the same time cannot queue its row ahead of
293    // it: the writer would then delete spend that is still counted here.
294    let mut table = table().lock().unwrap();
295    table.retain(|(a, _, day), one| {
296        let gone = a == agent && *day == d;
297        if gone {
298            removed += one.spend.cost_usd;
299        }
300        !gone
301    });
302    queue(Write::Clear(agent.to_string(), d));
303    drop(table);
304    removed
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use crate::backend::model_gateway::catalog;
311
312    #[test]
313    fn a_cache_write_on_the_key_route_counts_at_its_real_rate_or_the_dearest_and_on_a_model_route_at_the_input_price() {
314        let written = TokenCounts { cache_creation: 2_000_000, ..Default::default() };
315        let sonnet = catalog::key_route_price("claude-sonnet-5-5");
316        assert!((catalog::key_route_cost(sonnet, &written, Some((1_000_000, 1_000_000))) - 9.75).abs() < 1e-9, "3.75 for the five-minute write and 6.00 for the one-hour write");
317        assert!((catalog::key_route_cost(sonnet, &written, None) - 12.0).abs() < 1e-9, "not told which kind: all at 2 times the 3.00 input price");
318        assert!((cost(sonnet, &written) - 12.0).abs() < 1e-9, "the estimate never counts a key's cache write under");
319        let cache_heavy = TokenCounts { input: 100, output: 1_000, cache_creation: 50_000, cache_read: 400_000 };
320        let expected = 100.0 * 3.0 / 1e6 + 50_000.0 * 6.0 / 1e6 + 400_000.0 * 0.3 / 1e6 + 1_000.0 * 15.0 / 1e6;
321        assert!((catalog::key_route_cost(sonnet, &cache_heavy, Some((0, 50_000))) - expected).abs() < 1e-9, "a cache-heavy turn counts its one-hour writes at 2 times input");
322        let route = catalog::route("openrouter").unwrap().model("deepseek/deepseek-v4.1-flash-1017").unwrap();
323        assert!((cost(route, &written) - 2.0 * route.price_in).abs() < 1e-9, "a model route counts a cache write at the input price");
324    }
325
326    #[test]
327    fn a_response_is_priced_by_the_models_table_and_summed_per_agent_and_day() {
328        let model = catalog::route("openrouter").unwrap().model("deepseek/deepseek-v4.1-flash-1017").unwrap();
329        let used = TokenCounts { input: 1_000_000, output: 500_000, cache_read: 2_000_000, ..Default::default() };
330        let one = record("spend-agent", "openrouter", model, &used, None, 1_000);
331        assert!((one - (0.15 + 0.30 + 0.006)).abs() < 1e-9, "{one}");
332        record("spend-agent", "openrouter", model, &used, None, 2_000);
333        let sum = today("spend-agent", 3_000);
334        assert_eq!((sum.requests, sum.tokens.output), (2, 1_000_000));
335        assert!((sum.cost_usd - 2.0 * one).abs() < 1e-9);
336        assert_eq!(session_usd("spend-agent"), None, "no provider charge reported: not a route agent");
337        assert_eq!(today("spend-agent", 86_400_000 + 5), Spend::default(), "the next UTC day starts at zero");
338        assert_eq!(today("spend-other", 3_000), Spend::default());
339    }
340
341    /// The provider's own charge, when the response reports one, is the cost
342    /// (not the table's Claude-priced estimate) and is what a route agent's
343    /// session total sums (issue #30143).
344    #[test]
345    fn a_providers_own_charge_is_used_and_summed_per_session() {
346        let model = catalog::route("openrouter").unwrap().model("deepseek/deepseek-v4.1-flash-1017").unwrap();
347        let used = TokenCounts { input: 1_000_000, ..Default::default() };
348        let one = record("spend-route", "openrouter", model, &used, Some(0.004), 1_000);
349        assert!((one - 0.004).abs() < 1e-12, "{one}");
350        assert_eq!(session_usd("spend-route"), Some(0.004));
351        record("spend-route", "openrouter", model, &used, Some(0.006), 2_000);
352        assert!((session_usd("spend-route").unwrap() - 0.010).abs() < 1e-12);
353        assert!((today("spend-route", 3_000).cost_usd - 0.010).abs() < 1e-12);
354        // A route response that reported no charge (an interrupted stream) is
355        // priced by the route's table and still counts, rather than vanishing
356        // from the pane's session figure.
357        let estimate = cost(model, &used);
358        record("spend-route", "openrouter", model, &used, None, 3_000);
359        let total = session_usd("spend-route").unwrap();
360        assert!((total - (0.010 + estimate)).abs() < 1e-12, "{total}");
361        reset_session("spend-route");
362        assert_eq!(session_usd("spend-route"), None, "a new process starts its own total");
363        record("spend-route", "openrouter", model, &used, None, 4_000);
364        assert_eq!(session_usd("spend-route"), None, "and a costless response alone does not make one");
365    }
366
367    #[test]
368    fn a_route_agents_result_totals_are_rewritten_to_the_providers_charge() {
369        let model = catalog::route("openrouter").unwrap().model("deepseek/deepseek-v4.1-flash-1017").unwrap();
370        let used = TokenCounts { input: 1_000_000, ..Default::default() };
371        record("spend-rewrite", "openrouter", model, &used, Some(0.0042), 1_000);
372        let line = r#"{"type":"result","total_cost_usd":97.41,"cost_usd":97.41,"num_turns":1}"#;
373        let out = rewrite_result_total(line, "spend-rewrite").expect("rewritten");
374        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
375        assert_eq!(v["total_cost_usd"].as_f64(), Some(0.0042));
376        assert_eq!(v["cost_usd"].as_f64(), Some(0.0042), "the first frame's turn cost is the whole total");
377        // A second turn: the total is cumulative, the turn figure is the rise.
378        record("spend-rewrite", "openrouter", model, &used, Some(0.0058), 2_000);
379        let out = rewrite_result_total(line, "spend-rewrite").expect("rewritten");
380        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
381        let total = v["total_cost_usd"].as_f64().unwrap();
382        assert!((total - 0.01).abs() < 1e-12, "{total}");
383        let turn = v["cost_usd"].as_f64().unwrap();
384        assert!((turn - 0.0058).abs() < 1e-12, "never the cumulative total: {turn}");
385        assert_eq!(v["num_turns"].as_u64(), Some(1), "the rest of the frame is untouched");
386        assert!(rewrite_result_total(r#"{"type":"assistant"}"#, "spend-rewrite").is_none(), "not a result frame");
387        assert!(rewrite_result_total(line, "spend-estimate-only").is_none(), "no provider charge: unchanged");
388    }
389
390    #[test]
391    fn a_day_is_summed_over_routes_and_a_routes_over_agents_and_it_comes_back_from_the_store() {
392        let model = catalog::route("openrouter").unwrap().model("deepseek/deepseek-v4.1-flash-1017").unwrap();
393        let used = TokenCounts { input: 1_000_000, ..Default::default() };
394        let now = agentmux_common::time::now_ms();
395        record("spend-sum-a", "route-x", model, &used, Some(1.5), now);
396        record("spend-sum-a", "route-y", model, &used, Some(0.5), now);
397        record("spend-sum-b", "route-x", model, &used, Some(2.0), now);
398        assert!((today("spend-sum-a", now).cost_usd - 2.0).abs() < 1e-12, "both routes count for the agent");
399        assert!((route_today_usd("route-x", now) - 3.5).abs() < 1e-12, "both agents count for the route");
400        assert_eq!(alerted("spend-sum-a", now), 0);
401        set_alerted("spend-sum-a", 50, now);
402        assert_eq!(alerted("spend-sum-a", now), 50);
403        assert!(agents_today(now).contains(&"spend-sum-a".to_string()));
404        set_alerted("spend-sum-none", 100, now);
405        assert_eq!(alerted("spend-sum-none", now), 100, "kept for an agent with no spend of its own");
406        assert_eq!(today("spend-sum-none", now), Spend::default());
407
408        // What was saved is what a restart reads back: the rows the table would write, loaded into a store.
409        let store = Store::open(std::path::Path::new(":memory:")).unwrap();
410        for (key, one) in table().lock().unwrap().iter().filter(|((a, _, _), _)| a == "spend-sum-a") {
411            store.spend_day_save(&row_of(key, one)).unwrap();
412        }
413        table().lock().unwrap().retain(|(a, _, _), _| a != "spend-sum-a");
414        assert_eq!(today("spend-sum-a", now), Spend::default());
415        assert_eq!(restore(&store, now), 2);
416        assert!((today("spend-sum-a", now).cost_usd - 2.0).abs() < 1e-12);
417        assert_eq!(alerted("spend-sum-a", now), 50, "the alert already sent is not sent again after a restart");
418
419        let removed = reset_today("spend-sum-a", now);
420        assert!((removed - 2.0).abs() < 1e-12);
421        assert_eq!(today("spend-sum-a", now), Spend::default());
422        assert!((today("spend-sum-b", now).cost_usd - 2.0).abs() < 1e-12, "another agent's day is untouched");
423    }
424}