Skip to main content

lean_ctx/core/
proxy_usage.rs

1// SPDX-License-Identifier: Apache-2.0
2//! On-disk record of the proxy's measured provider spend (`proxy_usage.json`).
3//!
4//! The proxy's usage meter (`proxy::usage_meter`) aggregates the real
5//! provider usage of every finalized turn into these per-model sums and
6//! persists them; the dashboard, CLI, stats and the savings ledger (which run
7//! in *other* processes) read them back through [`load_persisted`] to learn
8//! the user's real provider bill.
9
10use std::collections::{HashMap, VecDeque};
11
12use serde::{Deserialize, Serialize};
13
14/// Where provider usage was observed, not an assertion of answer quality or
15/// successful generation. Terminal usage also accompanies failed responses.
16#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
17#[serde(rename_all = "snake_case")]
18pub enum UsageBoundary {
19    BodyEnd,
20    ProviderTerminalUsage,
21    StreamEnd,
22    StreamError,
23}
24
25/// Payload-free local measurement. Unknown cost stays unknown; neither HTTP
26/// status nor receipt of usage supplies the private runtime's quality label.
27#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
28#[serde(deny_unknown_fields)]
29pub struct ResponseObservation {
30    pub schema_version: u8,
31    pub http_status: u16,
32    /// Monotonic elapsed time from upstream dispatch (including retries) to
33    /// the indicated usage boundary, not necessarily full response latency.
34    pub usage_observed_ms: u64,
35    pub boundary: UsageBoundary,
36    pub provider_cost_usd: Option<f64>,
37}
38
39/// Cumulative real token counts for one model. Cost is derived at read time so a
40/// pricing-table change re-values historical usage consistently.
41#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
42pub struct ModelUsage {
43    pub requests: u64,
44    pub input_tokens: u64,
45    pub output_tokens: u64,
46    pub cache_read_tokens: u64,
47    pub cache_write_tokens: u64,
48    pub reasoning_tokens: u64,
49    /// Requests whose free `count_tokens` probe answered (#701) — the rows the
50    /// verified-savings pair below covers. `serde(default)` keeps pre-#701
51    /// usage files loadable.
52    #[serde(default)]
53    pub counterfactual_requests: u64,
54    /// Provider-counted input tokens the covered requests would have billed
55    /// WITHOUT lean-ctx (sum of probe answers on the original bodies).
56    #[serde(default)]
57    pub counterfactual_input_tokens: u64,
58    /// Input-side tokens those same requests actually billed (input +
59    /// cache read + cache write) — same request, same moment, no confound.
60    #[serde(default)]
61    pub counterfactual_billed_tokens: u64,
62    /// The turns whose response carried the provider's own USD charge
63    /// (OpenRouter usage accounting, #1179). Their tokens are *inside* the
64    /// totals above; pricing subtracts this slice and books its measured USD
65    /// instead of a table estimate. `serde(default)` keeps older files loadable.
66    #[serde(default)]
67    pub measured: MeasuredSlice,
68    /// Recent factual response measurements, not quality/training labels.
69    /// This local diagnostic history must not be pooled into private ranking:
70    /// it has no verified actor/endpoint scope or user-accepted outcome yet.
71    #[serde(default)]
72    pub response_observations: VecDeque<ResponseObservation>,
73    /// Input tokens the proxy's wire compression removed before forwarding
74    /// (the request-body estimate, bytes / 4). An estimate, not a provider
75    /// count — the verified pair above is the measured one. `serde(default)`
76    /// keeps older files loadable.
77    #[serde(default)]
78    pub saved_tokens: u64,
79}
80
81/// Token/cost sums of the turns that reported a measured provider charge.
82#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
83pub struct MeasuredSlice {
84    pub requests: u64,
85    pub input_tokens: u64,
86    pub output_tokens: u64,
87    pub cache_read_tokens: u64,
88    pub cache_write_tokens: u64,
89    /// Sum of provider-reported USD for those turns — the bill, not a table.
90    pub cost_usd: f64,
91}
92
93impl MeasuredSlice {
94    pub fn merge(&mut self, other: &Self) {
95        self.requests += other.requests;
96        self.input_tokens += other.input_tokens;
97        self.output_tokens += other.output_tokens;
98        self.cache_read_tokens += other.cache_read_tokens;
99        self.cache_write_tokens += other.cache_write_tokens;
100        self.cost_usd += other.cost_usd;
101    }
102}
103
104impl ModelUsage {
105    #[must_use]
106    pub fn billable_tokens(&self) -> u64 {
107        self.input_tokens + self.output_tokens + self.cache_read_tokens + self.cache_write_tokens
108    }
109
110    pub fn add_observation(&mut self, observation: ResponseObservation) {
111        const MAX_RESPONSE_OBSERVATIONS: usize = 32;
112        self.response_observations.push_back(observation);
113        while self.response_observations.len() > MAX_RESPONSE_OBSERVATIONS {
114            self.response_observations.pop_front();
115        }
116    }
117}
118
119/// Cumulative holdout cohort totals. Keyed by arm name: `"control"` |
120/// `"treatment"` for output savings (#895 Track B), `"compression:control"` |
121/// `"compression:treatment"` for input compression (#1905). The average tokens
122/// per turn are `*_tokens / requests`. Only populated while a holdout is active.
123#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
124pub struct CohortUsage {
125    pub requests: u64,
126    pub input_tokens: u64,
127    pub output_tokens: u64,
128    /// Sum of squared per-turn output tokens, enabling an online sample variance
129    /// (and therefore a confidence interval) without retaining every turn.
130    /// `#[serde(default)]` keeps pre-#895 files loadable.
131    #[serde(default)]
132    pub sum_sq_output: u64,
133    /// Whole prompt per turn — billed input plus cache reads and writes (#1905).
134    /// Compression shrinks the prompt wherever it is billed, so the
135    /// input-compression comparison uses this, not `input_tokens` alone.
136    /// `#[serde(default)]` keeps earlier files loadable.
137    #[serde(default)]
138    pub prompt_tokens: u64,
139    /// Sum of squared per-turn `prompt_tokens`, for its confidence interval.
140    #[serde(default)]
141    pub sum_sq_prompt: u64,
142}
143
144impl CohortUsage {
145    /// Adds another cohort's running totals — every field, so the sums of
146    /// squares (and with them the variance / CI) survive a proxy restart.
147    pub fn merge(&mut self, other: &Self) {
148        self.requests += other.requests;
149        self.input_tokens += other.input_tokens;
150        self.output_tokens += other.output_tokens;
151        self.sum_sq_output = self.sum_sq_output.saturating_add(other.sum_sq_output);
152        self.prompt_tokens += other.prompt_tokens;
153        self.sum_sq_prompt = self.sum_sq_prompt.saturating_add(other.sum_sq_prompt);
154    }
155
156    /// Average output tokens per turn, or `None` with no observations.
157    #[must_use]
158    pub fn avg_output(&self) -> Option<f64> {
159        if self.requests == 0 {
160            None
161        } else {
162            #[allow(clippy::cast_precision_loss)]
163            Some(self.output_tokens as f64 / self.requests as f64)
164        }
165    }
166
167    /// Unbiased sample variance of per-turn output tokens, or `None` with < 2
168    /// observations. Computed from the running sum / sum-of-squares (clamped at
169    /// 0 to absorb floating-point error on near-constant samples).
170    #[must_use]
171    pub fn variance_output(&self) -> Option<f64> {
172        if self.requests < 2 {
173            return None;
174        }
175        #[allow(clippy::cast_precision_loss)]
176        let n = self.requests as f64;
177        #[allow(clippy::cast_precision_loss)]
178        let sum = self.output_tokens as f64;
179        #[allow(clippy::cast_precision_loss)]
180        let sum_sq = self.sum_sq_output as f64;
181        let var = (sum_sq - sum * sum / n) / (n - 1.0);
182        Some(var.max(0.0))
183    }
184}
185
186/// On-disk shape of the measured spend totals.
187#[derive(Debug, Clone, Default, Serialize, Deserialize)]
188pub struct PersistedUsage {
189    pub ts: u64,
190    pub models: HashMap<String, ModelUsage>,
191    /// Output-savings cohort totals (#895). `#[serde(default)]` keeps older
192    /// `proxy_usage.json` files (written before the holdout existed) loadable.
193    #[serde(default)]
194    pub cohorts: HashMap<String, CohortUsage>,
195    /// The foreground model of the most recent finalized turn and when it was
196    /// seen (unix seconds), so other processes can attribute work to the model
197    /// in use now rather than the all-time largest bucket.
198    #[serde(default)]
199    pub last_model: Option<LastModel>,
200    /// The same totals per project key and model (the folder the agent named
201    /// in each request). Turns that named none stay in `models` only, which
202    /// remains the device total.
203    #[serde(default)]
204    pub projects: HashMap<String, HashMap<String, ModelUsage>>,
205    /// The same totals per app session (the `x-leanctx-session-id` header a
206    /// launching app sends, see `core::activity::SESSION_HEADER`); only the
207    /// most recently used sessions are kept. Attribution only.
208    #[serde(default)]
209    pub sessions: HashMap<String, SessionUsage>,
210    /// The same totals for turns that carried no (valid) session header —
211    /// the unattributed bucket of the session ledger. Never evicted.
212    #[serde(default)]
213    pub unattributed: SessionUsage,
214}
215
216/// One app session's totals per model and when the proxy last saw it.
217#[derive(Debug, Clone, Default, Serialize, Deserialize)]
218pub struct SessionUsage {
219    /// Unix seconds of the session's newest turn.
220    pub last_seen: u64,
221    pub models: HashMap<String, ModelUsage>,
222}
223
224/// The model the proxy saw last, with the time it saw it.
225#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
226pub struct LastModel {
227    pub model: String,
228    pub at: u64,
229}
230
231const PROXY_USAGE_FILE: &str = "proxy_usage.json";
232
233/// Where the measured spend totals live in the data directory.
234#[must_use]
235pub fn usage_path() -> Option<std::path::PathBuf> {
236    crate::core::data_dir::lean_ctx_data_dir()
237        .ok()
238        .map(|d| d.join(PROXY_USAGE_FILE))
239}
240
241/// Cross-process read of the persisted measured spend (dashboard / CLI / ledger).
242#[must_use]
243pub fn load_persisted() -> Option<PersistedUsage> {
244    let path = usage_path()?;
245    let data = std::fs::read_to_string(path).ok()?;
246    serde_json::from_str(&data).ok()
247}
248
249/// The model carrying the most measured tokens (excludes the "unknown" bucket).
250/// Used to value savings against the real dominant model when no explicit model
251/// is configured.
252#[must_use]
253pub fn persisted_dominant_model() -> Option<String> {
254    let persisted = load_persisted()?;
255    persisted
256        .models
257        .iter()
258        .filter(|(m, _)| m.as_str() != "unknown" && !m.trim().is_empty())
259        .max_by_key(|(_, u)| u.billable_tokens())
260        .filter(|(_, u)| u.billable_tokens() > 0)
261        .map(|(m, _)| m.clone())
262}