Skip to main content

agentmux_srv_core/backend/storage/
spend_day.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What each agent has used through the model gateway, per route and UTC day (`db_agent_spend_day`), so an
5//! srv restart does not start the day again (`docs/specs/SPEC_ROUTE_AGENT_BRAKES_2026_11_10.md` section 3.1).
6//! `backend::model_gateway::spend` keeps the live table and writes each changed row here.
7//!
8//! The table is created on first use (`CREATE TABLE IF NOT EXISTS`), as `container_limits` does: no schema bump,
9//! and an older build ignores a table it does not know.
10
11use rusqlite::params;
12
13use super::error::StoreError;
14use super::store::Store;
15
16const CREATE_TABLE: &str = "CREATE TABLE IF NOT EXISTS db_agent_spend_day (
17    agent_id       TEXT NOT NULL,
18    route          TEXT NOT NULL,
19    day            INTEGER NOT NULL,
20    requests       INTEGER NOT NULL DEFAULT 0,
21    input          INTEGER NOT NULL DEFAULT 0,
22    output         INTEGER NOT NULL DEFAULT 0,
23    cache_creation INTEGER NOT NULL DEFAULT 0,
24    cache_read     INTEGER NOT NULL DEFAULT 0,
25    cost_usd       REAL NOT NULL DEFAULT 0,
26    alerted        INTEGER NOT NULL DEFAULT 0,
27    PRIMARY KEY (agent_id, route, day)
28)";
29
30/// How many days of rows are kept.
31pub const KEEP_DAYS: i64 = 14;
32
33/// One agent's use on one route for one UTC day (`day` is days since the epoch).
34#[derive(Debug, Clone, Default, PartialEq)]
35pub struct SpendDayRow {
36    pub agent_id: String,
37    pub route: String,
38    pub day: i64,
39    pub requests: u64,
40    pub input: u64,
41    pub output: u64,
42    pub cache_creation: u64,
43    pub cache_read: u64,
44    pub cost_usd: f64,
45    /// The highest alert level sent for this agent's day so far (0, 50, 80 or 100).
46    pub alerted: u8,
47}
48
49impl Store {
50    /// Writes `row`, replacing the stored one for its agent, route and day.
51    pub fn spend_day_save(&self, row: &SpendDayRow) -> Result<(), StoreError> {
52        let conn = self.conn.lock().unwrap();
53        conn.execute_batch(CREATE_TABLE)?;
54        conn.execute(
55            "INSERT OR REPLACE INTO db_agent_spend_day
56             (agent_id, route, day, requests, input, output, cache_creation, cache_read, cost_usd, alerted)
57             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
58            params![
59                row.agent_id, row.route, row.day, row.requests as i64, row.input as i64, row.output as i64,
60                row.cache_creation as i64, row.cache_read as i64, row.cost_usd, row.alerted
61            ],
62        )?;
63        Ok(())
64    }
65
66    /// Every stored row from `since_day` on; the older ones are dropped, the table keeping [`KEEP_DAYS`] days.
67    pub fn spend_day_load(&self, since_day: i64) -> Result<Vec<SpendDayRow>, StoreError> {
68        let conn = self.conn.lock().unwrap();
69        conn.execute_batch(CREATE_TABLE)?;
70        conn.execute("DELETE FROM db_agent_spend_day WHERE day < ?1", params![since_day - KEEP_DAYS])?;
71        let mut stmt = conn.prepare(
72            "SELECT agent_id, route, day, requests, input, output, cache_creation, cache_read, cost_usd, alerted
73             FROM db_agent_spend_day WHERE day >= ?1",
74        )?;
75        let rows = stmt.query_map(params![since_day], |r| {
76            Ok(SpendDayRow {
77                agent_id: r.get(0)?,
78                route: r.get(1)?,
79                day: r.get(2)?,
80                requests: r.get::<_, i64>(3)? as u64,
81                input: r.get::<_, i64>(4)? as u64,
82                output: r.get::<_, i64>(5)? as u64,
83                cache_creation: r.get::<_, i64>(6)? as u64,
84                cache_read: r.get::<_, i64>(7)? as u64,
85                cost_usd: r.get(8)?,
86                alerted: r.get::<_, i64>(9)? as u8,
87            })
88        })?;
89        Ok(rows.collect::<Result<Vec<_>, _>>()?)
90    }
91
92    /// Deletes `agent_id`'s rows for `day` (the "Reset today" button). The number of rows removed.
93    pub fn spend_day_clear(&self, agent_id: &str, day: i64) -> Result<usize, StoreError> {
94        let conn = self.conn.lock().unwrap();
95        conn.execute_batch(CREATE_TABLE)?;
96        Ok(conn.execute("DELETE FROM db_agent_spend_day WHERE agent_id = ?1 AND day = ?2", params![agent_id, day])?)
97    }
98}
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103
104    fn row(agent: &str, route: &str, day: i64, cost: f64) -> SpendDayRow {
105        SpendDayRow { agent_id: agent.into(), route: route.into(), day, requests: 3, output: 40, cost_usd: cost, alerted: 50, ..Default::default() }
106    }
107
108    #[test]
109    fn a_saved_row_comes_back_and_a_second_save_replaces_it() {
110        let store = Store::open(std::path::Path::new(":memory:")).unwrap();
111        assert!(store.spend_day_load(0).unwrap().is_empty(), "no table yet: nothing, not an error");
112        store.spend_day_save(&row("glim", "openrouter", 20_000, 4.5)).unwrap();
113        store.spend_day_save(&row("glim", "openrouter", 20_000, 9.25)).unwrap();
114        store.spend_day_save(&row("glim", "other", 20_000, 1.0)).unwrap();
115        let mut rows = store.spend_day_load(20_000).unwrap();
116        rows.sort_by(|a, b| b.route.cmp(&a.route));
117        assert_eq!(rows.len(), 2);
118        assert_eq!((rows[1].route.as_str(), rows[1].cost_usd, rows[1].alerted, rows[1].requests), ("openrouter", 9.25, 50, 3));
119    }
120
121    #[test]
122    fn loading_drops_days_past_the_keep_window_and_clear_removes_one_agents_day() {
123        let store = Store::open(std::path::Path::new(":memory:")).unwrap();
124        store.spend_day_save(&row("glim", "openrouter", 20_000 - KEEP_DAYS - 1, 1.0)).unwrap();
125        store.spend_day_save(&row("glim", "openrouter", 20_000, 2.0)).unwrap();
126        store.spend_day_save(&row("aria", "openrouter", 20_000, 3.0)).unwrap();
127        assert_eq!(store.spend_day_load(0).unwrap().len(), 3);
128        assert_eq!(store.spend_day_load(20_000).unwrap().len(), 2, "the old row was dropped");
129        assert_eq!(store.spend_day_clear("glim", 20_000).unwrap(), 1);
130        let left = store.spend_day_load(0).unwrap();
131        assert_eq!(left.len(), 1);
132        assert_eq!(left[0].agent_id, "aria");
133    }
134}