Skip to main content

lean_ctx/proxy/
usage_meter.rs

1//! Measured per-model spend meter.
2//!
3//! [`record`] aggregates the real provider usage extracted by [`super::usage`]
4//! into per-model token sums, prices them with the shared
5//! `ModelPricing` table, and
6//! persists the totals to `proxy_usage.json` so the dashboard, CLI and the
7//! savings ledger (which run in *other* processes) can read the user's real
8//! provider bill.
9//!
10//! Unlike [`super::metrics`] (which resets per proxy lifetime), this meter is a
11//! lifetime-cumulative spend counter: [`resume_from_disk`] seeds the in-memory
12//! totals on proxy startup so a restart never zeroes the user's measured spend.
13
14use std::collections::{HashMap, VecDeque};
15use std::sync::{Mutex, OnceLock};
16
17use serde::{Deserialize, Serialize};
18
19use crate::core::gain::model_pricing::ModelPricing;
20use crate::core::ocla::{OclaRegistry, UsageSink};
21
22/// Projects one managed, provider-measured turn into the OCLA usage sink.
23///
24/// This is deliberately one-way and best-effort: the existing meter remains
25/// authoritative for billing/ledger totals, while OCLA receives a validated
26/// payload-free projection only when complete lineage is present.
27fn project_ocla_usage(u: &super::usage::RealUsage, sink: &dyn UsageSink) {
28    use futures::FutureExt;
29    let Ok(Some(record)) = u.to_ocla_usage_record() else {
30        return;
31    };
32    let _ = sink.record_usage(record).now_or_never();
33}
34
35/// Cumulative real token counts for one model. Cost is derived at read time so a
36/// pricing-table change re-values historical usage consistently.
37#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
38pub struct ModelUsage {
39    pub requests: u64,
40    pub input_tokens: u64,
41    pub output_tokens: u64,
42    pub cache_read_tokens: u64,
43    pub cache_write_tokens: u64,
44    pub reasoning_tokens: u64,
45    /// Requests whose free `count_tokens` probe answered (#701) — the rows the
46    /// verified-savings pair below covers. `serde(default)` keeps pre-#701
47    /// usage files loadable.
48    #[serde(default)]
49    pub counterfactual_requests: u64,
50    /// Provider-counted input tokens the covered requests would have billed
51    /// WITHOUT lean-ctx (sum of probe answers on the original bodies).
52    #[serde(default)]
53    pub counterfactual_input_tokens: u64,
54    /// Input-side tokens those same requests actually billed (input +
55    /// cache read + cache write) — same request, same moment, no confound.
56    #[serde(default)]
57    pub counterfactual_billed_tokens: u64,
58    /// The turns whose response carried the provider's own USD charge
59    /// (OpenRouter usage accounting, #1179). Their tokens are *inside* the
60    /// totals above; pricing subtracts this slice and books its measured USD
61    /// instead of a table estimate. `serde(default)` keeps older files loadable.
62    #[serde(default)]
63    pub measured: MeasuredSlice,
64    /// Recent factual response measurements, not quality/training labels.
65    /// This local diagnostic history must not be pooled into private ranking:
66    /// it has no verified actor/endpoint scope or user-accepted outcome yet.
67    #[serde(default)]
68    pub response_observations: VecDeque<super::usage::ResponseObservation>,
69}
70
71/// Token/cost sums of the turns that reported a measured provider charge.
72#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
73pub struct MeasuredSlice {
74    pub requests: u64,
75    pub input_tokens: u64,
76    pub output_tokens: u64,
77    pub cache_read_tokens: u64,
78    pub cache_write_tokens: u64,
79    /// Sum of provider-reported USD for those turns — the bill, not a table.
80    pub cost_usd: f64,
81}
82
83impl MeasuredSlice {
84    fn merge(&mut self, other: &Self) {
85        self.requests += other.requests;
86        self.input_tokens += other.input_tokens;
87        self.output_tokens += other.output_tokens;
88        self.cache_read_tokens += other.cache_read_tokens;
89        self.cache_write_tokens += other.cache_write_tokens;
90        self.cost_usd += other.cost_usd;
91    }
92}
93
94impl ModelUsage {
95    fn add(&mut self, u: &super::usage::RealUsage) {
96        if let Some(observation) = &u.response_observation {
97            self.add_observation(observation.clone());
98        }
99        self.requests += 1;
100        self.input_tokens += u.input_tokens;
101        self.output_tokens += u.output_tokens;
102        self.cache_read_tokens += u.cache_read_tokens;
103        self.cache_write_tokens += u.cache_write_tokens;
104        self.reasoning_tokens += u.reasoning_tokens;
105        if let Some(cost) = u.provider_cost_usd {
106            self.measured.merge(&MeasuredSlice {
107                requests: 1,
108                input_tokens: u.input_tokens,
109                output_tokens: u.output_tokens,
110                cache_read_tokens: u.cache_read_tokens,
111                cache_write_tokens: u.cache_write_tokens,
112                cost_usd: cost,
113            });
114        }
115        // Verified-savings pair (#701): only when the probe answered by the
116        // time the billed usage arrived — both sides of the pair or neither.
117        if let Some(counted) = u
118            .wire
119            .as_deref()
120            .and_then(|w| w.counterfactual.as_ref())
121            .and_then(super::counterfactual::CounterfactualSlot::get)
122        {
123            self.counterfactual_requests += 1;
124            self.counterfactual_input_tokens += counted;
125            self.counterfactual_billed_tokens +=
126                u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
127        }
128    }
129
130    fn billable_tokens(&self) -> u64 {
131        self.input_tokens + self.output_tokens + self.cache_read_tokens + self.cache_write_tokens
132    }
133
134    fn add_observation(&mut self, observation: super::usage::ResponseObservation) {
135        const MAX_RESPONSE_OBSERVATIONS: usize = 32;
136        self.response_observations.push_back(observation);
137        while self.response_observations.len() > MAX_RESPONSE_OBSERVATIONS {
138            self.response_observations.pop_front();
139        }
140    }
141}
142
143/// One model's measured, priced spend for `/status` and the dashboard.
144#[derive(Debug, Clone, Serialize, PartialEq)]
145pub struct ModelSpend {
146    pub model: String,
147    pub requests: u64,
148    pub input_tokens: u64,
149    pub output_tokens: u64,
150    pub cache_read_tokens: u64,
151    pub cache_write_tokens: u64,
152    pub reasoning_tokens: u64,
153    pub cost_usd: f64,
154    /// Share of `cost_usd` the provider itself reported (OpenRouter usage
155    /// accounting, #1179) — a bill, not a table estimate.
156    pub measured_cost_usd: f64,
157    /// Requests covered by that provider-reported cost.
158    pub measured_requests: u64,
159    /// True when part of the cost had to be priced from a heuristic/fallback
160    /// match — never set by measured or exactly-priced spend.
161    pub pricing_estimated: bool,
162}
163
164/// Cohort-store key for an input-compression holdout arm (#1905). Prefixed so
165/// it never collides with the output-savings arms stored as `control` /
166/// `treatment`, which keeps existing files and readers unchanged.
167#[must_use]
168pub fn compression_cohort_key(arm: super::holdout::Arm) -> String {
169    format!("compression:{}", arm.as_str())
170}
171
172/// Cumulative holdout cohort totals. Keyed by arm name: `"control"` |
173/// `"treatment"` for output savings (#895 Track B), `"compression:control"` |
174/// `"compression:treatment"` for input compression (#1905). The average tokens
175/// per turn are `*_tokens / requests`. Only populated while a holdout is active.
176#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
177pub struct CohortUsage {
178    pub requests: u64,
179    pub input_tokens: u64,
180    pub output_tokens: u64,
181    /// Sum of squared per-turn output tokens, enabling an online sample variance
182    /// (and therefore a confidence interval) without retaining every turn.
183    /// `#[serde(default)]` keeps pre-#895 files loadable.
184    #[serde(default)]
185    pub sum_sq_output: u64,
186    /// Whole prompt per turn — billed input plus cache reads and writes (#1905).
187    /// Compression shrinks the prompt wherever it is billed, so the
188    /// input-compression comparison uses this, not `input_tokens` alone.
189    /// `#[serde(default)]` keeps earlier files loadable.
190    #[serde(default)]
191    pub prompt_tokens: u64,
192    /// Sum of squared per-turn `prompt_tokens`, for its confidence interval.
193    #[serde(default)]
194    pub sum_sq_prompt: u64,
195}
196
197impl CohortUsage {
198    fn add(&mut self, u: &super::usage::RealUsage) {
199        self.requests += 1;
200        self.input_tokens += u.input_tokens;
201        self.output_tokens += u.output_tokens;
202        self.sum_sq_output += u.output_tokens.saturating_mul(u.output_tokens);
203        let prompt = u
204            .input_tokens
205            .saturating_add(u.cache_read_tokens)
206            .saturating_add(u.cache_write_tokens);
207        self.prompt_tokens += prompt;
208        self.sum_sq_prompt += prompt.saturating_mul(prompt);
209    }
210
211    /// Adds another cohort's running totals — every field, so the sums of
212    /// squares (and with them the variance / CI) survive a proxy restart.
213    fn merge(&mut self, other: &Self) {
214        self.requests += other.requests;
215        self.input_tokens += other.input_tokens;
216        self.output_tokens += other.output_tokens;
217        self.sum_sq_output = self.sum_sq_output.saturating_add(other.sum_sq_output);
218        self.prompt_tokens += other.prompt_tokens;
219        self.sum_sq_prompt = self.sum_sq_prompt.saturating_add(other.sum_sq_prompt);
220    }
221
222    /// Average output tokens per turn, or `None` with no observations.
223    #[must_use]
224    pub fn avg_output(&self) -> Option<f64> {
225        if self.requests == 0 {
226            None
227        } else {
228            #[allow(clippy::cast_precision_loss)]
229            Some(self.output_tokens as f64 / self.requests as f64)
230        }
231    }
232
233    /// Unbiased sample variance of per-turn output tokens, or `None` with < 2
234    /// observations. Computed from the running sum / sum-of-squares (clamped at
235    /// 0 to absorb floating-point error on near-constant samples).
236    #[must_use]
237    pub fn variance_output(&self) -> Option<f64> {
238        if self.requests < 2 {
239            return None;
240        }
241        #[allow(clippy::cast_precision_loss)]
242        let n = self.requests as f64;
243        #[allow(clippy::cast_precision_loss)]
244        let sum = self.output_tokens as f64;
245        #[allow(clippy::cast_precision_loss)]
246        let sum_sq = self.sum_sq_output as f64;
247        let var = (sum_sq - sum * sum / n) / (n - 1.0);
248        Some(var.max(0.0))
249    }
250}
251
252/// On-disk shape of the measured spend totals.
253#[derive(Debug, Clone, Default, Serialize, Deserialize)]
254pub struct PersistedUsage {
255    pub ts: u64,
256    pub models: HashMap<String, ModelUsage>,
257    /// Output-savings cohort totals (#895). `#[serde(default)]` keeps older
258    /// `proxy_usage.json` files (written before the holdout existed) loadable.
259    #[serde(default)]
260    pub cohorts: HashMap<String, CohortUsage>,
261    /// The foreground model of the most recent finalized turn and when it was
262    /// seen (unix seconds), so other processes can attribute work to the model
263    /// in use now rather than the all-time largest bucket.
264    #[serde(default)]
265    pub last_model: Option<LastModel>,
266    /// The same totals per project key and model (the folder the agent named
267    /// in each request). Turns that named none stay in `models` only, which
268    /// remains the device total.
269    #[serde(default)]
270    pub projects: HashMap<String, HashMap<String, ModelUsage>>,
271}
272
273/// The model the proxy saw last, with the time it saw it.
274#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
275pub struct LastModel {
276    pub model: String,
277    pub at: u64,
278}
279
280fn last_model_store() -> &'static Mutex<Option<LastModel>> {
281    static STORE: OnceLock<Mutex<Option<LastModel>>> = OnceLock::new();
282    STORE.get_or_init(|| Mutex::new(None))
283}
284
285/// Distinct-model bucket cap. `record` keys on the raw response model string, so
286/// overflow folds into "unknown" to keep the map bounded (real model names < ~50).
287const MAX_TRACKED_MODELS: usize = 256;
288
289const PROXY_USAGE_FILE: &str = "proxy_usage.json";
290
291fn store() -> &'static Mutex<HashMap<String, ModelUsage>> {
292    static STORE: OnceLock<Mutex<HashMap<String, ModelUsage>>> = OnceLock::new();
293    STORE.get_or_init(|| Mutex::new(HashMap::new()))
294}
295
296/// Distinct projects kept apart; turns of further projects stay in the device total.
297const MAX_TRACKED_PROJECTS: usize = 512;
298
299fn project_store() -> &'static Mutex<HashMap<String, HashMap<String, ModelUsage>>> {
300    static STORE: OnceLock<Mutex<HashMap<String, HashMap<String, ModelUsage>>>> = OnceLock::new();
301    STORE.get_or_init(|| Mutex::new(HashMap::new()))
302}
303
304fn cohort_store() -> &'static Mutex<HashMap<String, CohortUsage>> {
305    static STORE: OnceLock<Mutex<HashMap<String, CohortUsage>>> = OnceLock::new();
306    STORE.get_or_init(|| Mutex::new(HashMap::new()))
307}
308
309/// Seeds the in-memory totals from `proxy_usage.json`. Call once on proxy
310/// startup so measured spend is cumulative across restarts. Idempotent-ish: it
311/// merges the persisted totals into whatever is in memory (normally empty).
312pub fn resume_from_disk() {
313    let Some(persisted) = load_persisted() else {
314        return;
315    };
316    {
317        let mut last = last_model_store()
318            .lock()
319            .unwrap_or_else(std::sync::PoisonError::into_inner);
320        if last.is_none() {
321            last.clone_from(&persisted.last_model);
322        }
323    }
324    let mut map = store()
325        .lock()
326        .unwrap_or_else(std::sync::PoisonError::into_inner);
327    merge_models(&mut map, persisted.models);
328    drop(map);
329    let mut projects = project_store()
330        .lock()
331        .unwrap_or_else(std::sync::PoisonError::into_inner);
332    for (project, models) in persisted.projects {
333        merge_models(projects.entry(project).or_default(), models);
334    }
335    drop(projects);
336    let mut cohorts = cohort_store()
337        .lock()
338        .unwrap_or_else(std::sync::PoisonError::into_inner);
339    for (arm, usage) in persisted.cohorts {
340        cohorts.entry(arm).or_default().merge(&usage);
341    }
342}
343
344fn merge_models(map: &mut HashMap<String, ModelUsage>, models: HashMap<String, ModelUsage>) {
345    for (model, usage) in models {
346        let acc = map.entry(model).or_default();
347        acc.requests += usage.requests;
348        acc.input_tokens += usage.input_tokens;
349        acc.output_tokens += usage.output_tokens;
350        acc.cache_read_tokens += usage.cache_read_tokens;
351        acc.cache_write_tokens += usage.cache_write_tokens;
352        acc.reasoning_tokens += usage.reasoning_tokens;
353        acc.counterfactual_requests += usage.counterfactual_requests;
354        acc.counterfactual_input_tokens += usage.counterfactual_input_tokens;
355        acc.counterfactual_billed_tokens += usage.counterfactual_billed_tokens;
356        acc.measured.merge(&usage.measured);
357        for observation in usage.response_observations {
358            acc.add_observation(observation);
359        }
360    }
361}
362
363/// Records one turn's measured usage against its model bucket (and its
364/// output-savings cohort, when tagged) and persists.
365pub fn record(u: &super::usage::RealUsage) {
366    // Gateway store subscription (enterprise#17): forward the full record to
367    // the installed sink (no-op locally). Never blocks the request path.
368    super::usage_sink::push(u);
369
370    // R33: Feed measured usage into kernel envelope pipeline.
371    {
372        let label = u.wire.as_ref().map_or("Unknown", |w| {
373            // provider_kind_from_label expects a static or owned string;
374            // the label lives long enough for the conversion call.
375            match w.provider.as_str() {
376                "Anthropic" => "Anthropic",
377                "OpenAI" | "ChatGPT" => "OpenAI",
378                "Gemini" => "Gemini",
379                "Bedrock" => "Bedrock",
380                "Azure" => "Azure",
381                _ => "Unknown",
382            }
383        });
384        let envelope = super::usage_parity::real_usage_to_envelope(u, label);
385        crate::core::context_kernel::envelope_bridge::record_proxy_envelope(&envelope);
386    }
387
388    // OCLA projection: keep the canonical usage capability on the same single
389    // finalized-turn choke-point without feeding back into billing or ledger
390    // aggregation. Invalid/missing lineage stays explicitly unmanaged.
391    project_ocla_usage(u, OclaRegistry::global().usage_sink.as_ref());
392
393    // Budget windows (enterprise#25): book this turn's measured cost against
394    // the person/day and project/month accumulators the policy gate checks.
395    // The provider's own reported charge wins (#1179); local turns book the
396    // shadow rate — the same valuation the usage store applies — so
397    // local-only budgets stay meaningful.
398    #[cfg(feature = "enterprise")]
399    if let Some(wire) = u.wire.as_deref()
400        && (wire.person.is_some() || wire.project.is_some())
401    {
402        let baseline = crate::core::config::Config::load().proxy.baseline.clone();
403        #[allow(clippy::cast_precision_loss)]
404        let cost_usd = if wire.is_local {
405            let billable =
406                u.input_tokens + u.output_tokens + u.cache_read_tokens + u.cache_write_tokens;
407            baseline.effective_local_shadow_rate() / 1_000_000.0 * billable as f64
408        } else if let Some(measured) = u.provider_cost_usd {
409            measured
410        } else {
411            crate::core::gain::model_pricing::ModelPricing::load()
412                .quote(Some(&u.model))
413                .cost
414                .estimate_usd(
415                    u.input_tokens,
416                    u.output_tokens,
417                    u.cache_write_tokens,
418                    u.cache_read_tokens,
419                )
420        };
421        super::policy_gate::record_spend(wire.person.as_deref(), wire.project.as_deref(), cost_usd);
422    }
423
424    // Mechanism attribution into the local savings ledger (enterprise#19):
425    // provider prompt-cache reads billed below the input rate. Best-effort,
426    // never blocking. A model swap is never booked as a LeanCTX saving.
427    if u.cache_read_tokens > 0 {
428        let cost = crate::core::gain::model_pricing::ModelPricing::load()
429            .quote(Some(&u.model))
430            .cost;
431        #[allow(clippy::cast_precision_loss)]
432        let discount_usd =
433            (cost.input_per_m - cost.cache_read_per_m) / 1_000_000.0 * u.cache_read_tokens as f64;
434        crate::core::savings_ledger::record_caching_event(
435            &u.model,
436            u.cache_read_tokens,
437            discount_usd,
438            u.wire.as_deref().and_then(|w| w.project_key.as_deref()),
439        );
440    }
441
442    // Remember the foreground model for attribution in other processes
443    // (savings ledger). Background models never count as "the model in use".
444    let model = u.model.trim();
445    if !model.is_empty()
446        && model != "unknown"
447        && !crate::core::model_registry::is_background_model(model)
448    {
449        *last_model_store()
450            .lock()
451            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(LastModel {
452            model: model.to_string(),
453            at: std::time::SystemTime::now()
454                .duration_since(std::time::UNIX_EPOCH)
455                .unwrap_or_default()
456                .as_secs(),
457        });
458    }
459
460    let key = normalize_key(&u.model);
461    {
462        let mut map = store()
463            .lock()
464            .unwrap_or_else(std::sync::PoisonError::into_inner);
465        let key = if !map.contains_key(&key) && map.len() >= MAX_TRACKED_MODELS {
466            "unknown".to_string()
467        } else {
468            key
469        };
470        map.entry(key.clone()).or_default().add(u);
471        drop(map);
472        if let Some(project) = u.wire.as_deref().and_then(|w| w.project_key.as_deref()) {
473            let mut projects = project_store()
474                .lock()
475                .unwrap_or_else(std::sync::PoisonError::into_inner);
476            if projects.contains_key(project) || projects.len() < MAX_TRACKED_PROJECTS {
477                projects
478                    .entry(project.to_string())
479                    .or_default()
480                    .entry(key)
481                    .or_default()
482                    .add(u);
483            }
484        }
485    }
486    if u.cohort.output.is_some() || u.cohort.compression.is_some() {
487        let mut cohorts = cohort_store()
488            .lock()
489            .unwrap_or_else(std::sync::PoisonError::into_inner);
490        if let Some(arm) = u.cohort.output {
491            cohorts.entry(arm.as_str().to_string()).or_default().add(u);
492        }
493        if let Some(arm) = u.cohort.compression {
494            cohorts
495                .entry(compression_cohort_key(arm))
496                .or_default()
497                .add(u);
498        }
499    }
500    persist();
501}
502
503/// Live output-savings cohort totals (#895). Empty until a holdout runs.
504#[must_use]
505pub fn cohort_snapshot() -> HashMap<String, CohortUsage> {
506    cohort_store()
507        .lock()
508        .unwrap_or_else(std::sync::PoisonError::into_inner)
509        .clone()
510}
511
512/// Cross-process read of the persisted output-savings cohort totals.
513#[must_use]
514pub fn persisted_cohorts() -> HashMap<String, CohortUsage> {
515    load_persisted().map(|p| p.cohorts).unwrap_or_default()
516}
517
518fn normalize_key(model: &str) -> String {
519    let m = model.trim();
520    if m.is_empty() {
521        "unknown".to_string()
522    } else {
523        m.to_string()
524    }
525}
526
527/// Live per-model measured spend, priced and sorted by USD descending.
528pub fn snapshot() -> Vec<ModelSpend> {
529    let map = store()
530        .lock()
531        .unwrap_or_else(std::sync::PoisonError::into_inner);
532    price_models(&map)
533}
534
535/// Total measured spend across all models (live in-memory totals).
536pub fn total_cost_usd() -> f64 {
537    snapshot().iter().map(|m| m.cost_usd).sum()
538}
539
540/// Cross-model verified-savings totals (#701) for `/status` and the dashboard.
541#[derive(Debug, Clone, Serialize, PartialEq)]
542pub struct VerifiedSavings {
543    /// Requests covered by a successful `count_tokens` probe.
544    pub requests: u64,
545    /// Provider-counted input tokens those requests would have billed
546    /// without lean-ctx.
547    pub counterfactual_input_tokens: u64,
548    /// Input-side tokens (input + cache read + cache write) they actually
549    /// billed.
550    pub billed_input_tokens: u64,
551    /// `counterfactual - billed`; negative when stub overhead outweighed the
552    /// squeeze — reported honestly, never clamped.
553    pub verified_saved_tokens: i64,
554}
555
556/// Aggregated provider-verified savings across all models (#701), or `None`
557/// until at least one probe-covered request has been recorded. Unlike the
558/// `tokens_saved` estimate (bytes/4), both sides of this pair were counted by
559/// the provider on the same request — receipts, not estimates.
560pub fn verified_savings() -> Option<VerifiedSavings> {
561    let map = store()
562        .lock()
563        .unwrap_or_else(std::sync::PoisonError::into_inner);
564    verified_of(&map)
565}
566
567/// Pure aggregation behind [`verified_savings`], shared with tests.
568#[allow(clippy::cast_possible_wrap)]
569fn verified_of(map: &HashMap<String, ModelUsage>) -> Option<VerifiedSavings> {
570    let (mut requests, mut counterfactual, mut billed) = (0u64, 0u64, 0u64);
571    for usage in map.values() {
572        requests += usage.counterfactual_requests;
573        counterfactual += usage.counterfactual_input_tokens;
574        billed += usage.counterfactual_billed_tokens;
575    }
576    (requests > 0).then(|| VerifiedSavings {
577        requests,
578        counterfactual_input_tokens: counterfactual,
579        billed_input_tokens: billed,
580        verified_saved_tokens: counterfactual as i64 - billed as i64,
581    })
582}
583
584/// Prices a model usage map into sorted [`ModelSpend`] rows. Pure: shared by the
585/// in-memory snapshot and the cross-process [`persisted_snapshot`].
586pub fn price_models(map: &HashMap<String, ModelUsage>) -> Vec<ModelSpend> {
587    let pricing = ModelPricing::load();
588    let mut rows: Vec<ModelSpend> = map
589        .iter()
590        .map(|(model, usage)| price_one(&pricing, model, usage))
591        .collect();
592    rows.sort_by(|a, b| {
593        b.cost_usd
594            .partial_cmp(&a.cost_usd)
595            .unwrap_or(std::cmp::Ordering::Equal)
596    });
597    rows
598}
599
600fn price_one(pricing: &ModelPricing, model: &str, usage: &ModelUsage) -> ModelSpend {
601    let quote = pricing.quote(Some(model));
602    // Measured-first (#1179): turns whose response carried the provider's own
603    // USD charge book that exact amount; only the remainder is table-priced.
604    let m = &usage.measured;
605    let derived_cost = quote.cost.estimate_usd(
606        usage.input_tokens.saturating_sub(m.input_tokens),
607        usage.output_tokens.saturating_sub(m.output_tokens),
608        usage
609            .cache_write_tokens
610            .saturating_sub(m.cache_write_tokens),
611        usage.cache_read_tokens.saturating_sub(m.cache_read_tokens),
612    );
613    let derived_requests = usage.requests.saturating_sub(m.requests);
614    ModelSpend {
615        model: model.to_string(),
616        requests: usage.requests,
617        input_tokens: usage.input_tokens,
618        output_tokens: usage.output_tokens,
619        cache_read_tokens: usage.cache_read_tokens,
620        cache_write_tokens: usage.cache_write_tokens,
621        reasoning_tokens: usage.reasoning_tokens,
622        cost_usd: m.cost_usd + derived_cost,
623        measured_cost_usd: m.cost_usd,
624        measured_requests: m.requests,
625        // Fully measured spend is never an estimate, whatever the table says.
626        pricing_estimated: quote.match_kind.is_estimated() && derived_requests > 0,
627    }
628}
629
630fn usage_path() -> Option<std::path::PathBuf> {
631    crate::core::data_dir::lean_ctx_data_dir()
632        .ok()
633        .map(|d| d.join(PROXY_USAGE_FILE))
634}
635
636/// Atomically writes the current in-memory totals to disk.
637fn persist() {
638    let Some(path) = usage_path() else {
639        return;
640    };
641    let models = {
642        let map = store()
643            .lock()
644            .unwrap_or_else(std::sync::PoisonError::into_inner);
645        map.clone()
646    };
647    let cohorts = {
648        let map = cohort_store()
649            .lock()
650            .unwrap_or_else(std::sync::PoisonError::into_inner);
651        map.clone()
652    };
653    let last_model = last_model_store()
654        .lock()
655        .unwrap_or_else(std::sync::PoisonError::into_inner)
656        .clone();
657    let projects = project_store()
658        .lock()
659        .unwrap_or_else(std::sync::PoisonError::into_inner)
660        .clone();
661    let payload = PersistedUsage {
662        ts: std::time::SystemTime::now()
663            .duration_since(std::time::UNIX_EPOCH)
664            .unwrap_or_default()
665            .as_secs(),
666        models,
667        cohorts,
668        last_model,
669        projects,
670    };
671    let Ok(json) = serde_json::to_string(&payload) else {
672        return;
673    };
674    let tmp = path.with_extension("json.tmp");
675    if std::fs::write(&tmp, json).is_ok() {
676        let _ = std::fs::rename(&tmp, &path);
677    }
678}
679
680/// Cross-process read of the persisted measured spend (dashboard / CLI / ledger).
681pub fn load_persisted() -> Option<PersistedUsage> {
682    let path = usage_path()?;
683    let data = std::fs::read_to_string(path).ok()?;
684    serde_json::from_str(&data).ok()
685}
686
687/// Cross-process priced spend rows, read from disk.
688pub fn persisted_snapshot() -> Vec<ModelSpend> {
689    load_persisted()
690        .map(|p| price_models(&p.models))
691        .unwrap_or_default()
692}
693
694/// Priced spend rows of the projects whose key `keep` accepts, summed per model.
695pub fn persisted_snapshot_where(keep: impl Fn(&str) -> bool) -> Vec<ModelSpend> {
696    let Some(persisted) = load_persisted() else {
697        return Vec::new();
698    };
699    let mut models: HashMap<String, ModelUsage> = HashMap::new();
700    for (project, usage) in persisted.projects {
701        if keep(&project) {
702            merge_models(&mut models, usage);
703        }
704    }
705    price_models(&models)
706}
707
708/// Priced spend per project key (the device view's split).
709pub fn persisted_projects() -> Vec<(String, Vec<ModelSpend>)> {
710    let Some(persisted) = load_persisted() else {
711        return Vec::new();
712    };
713    let mut rows: Vec<(String, Vec<ModelSpend>)> = persisted
714        .projects
715        .iter()
716        .map(|(project, models)| (project.clone(), price_models(models)))
717        .collect();
718    rows.sort_by(|a, b| a.0.cmp(&b.0));
719    rows
720}
721
722/// The model carrying the most measured tokens (excludes the "unknown" bucket).
723/// Used to value savings against the real dominant model when no explicit model
724/// is configured.
725pub fn persisted_dominant_model() -> Option<String> {
726    let persisted = load_persisted()?;
727    persisted
728        .models
729        .iter()
730        .filter(|(m, _)| m.as_str() != "unknown" && !m.trim().is_empty())
731        .max_by_key(|(_, u)| u.billable_tokens())
732        .filter(|(_, u)| u.billable_tokens() > 0)
733        .map(|(m, _)| m.clone())
734}
735
736#[cfg(test)]
737mod tests {
738    use super::*;
739
740    fn usage(
741        model: &str,
742        input: u64,
743        output: u64,
744        cache_read: u64,
745    ) -> super::super::usage::RealUsage {
746        super::super::usage::RealUsage {
747            model: model.to_string(),
748            input_tokens: input,
749            output_tokens: output,
750            cache_read_tokens: cache_read,
751            ..Default::default()
752        }
753    }
754
755    /// #895: resuming from disk must carry the sums of squares and prompt
756    /// totals; dropping them zeroed the variance after every proxy restart and
757    /// turned the CI into a zero-width "measurement".
758    #[test]
759    fn cohort_merge_keeps_every_running_total() {
760        let mut persisted = CohortUsage::default();
761        for (out, cached) in [(150, 900), (210, 1_200), (180, 0)] {
762            persisted.add(&usage("claude-sonnet-4.5", 1_000, out, cached));
763        }
764        let mut resumed = CohortUsage::default();
765        resumed.merge(&persisted);
766        assert_eq!(resumed, persisted, "every field survives the restart");
767        assert!(resumed.variance_output().is_some_and(|v| v > 0.0));
768
769        // Merging into live in-memory totals adds field by field.
770        let mut live = CohortUsage::default();
771        live.add(&usage("claude-sonnet-4.5", 500, 100, 0));
772        let expected_sum_sq = live.sum_sq_output + persisted.sum_sq_output;
773        live.merge(&persisted);
774        assert_eq!(live.requests, 4);
775        assert_eq!(live.sum_sq_output, expected_sum_sq);
776        assert_eq!(live.prompt_tokens, 500 + persisted.prompt_tokens);
777    }
778
779    /// A turn whose request named a project is booked to the device total and
780    /// to that project; one that named none to the device total only. Both
781    /// survive the file round trip.
782    #[test]
783    fn spend_is_split_per_project_and_persisted() {
784        let _dir = crate::core::data_dir::isolated_data_dir();
785        let project = format!("{:016x}", std::process::id() as u64 * 7919 + 17);
786        let other = format!("{:016x}", std::process::id() as u64 * 7919 + 18);
787        let turn = |key: Option<&str>, input| super::super::usage::RealUsage {
788            wire: Some(Box::new(super::super::usage::WireContext {
789                project_key: key.map(str::to_string),
790                ..Default::default()
791            })),
792            ..usage("claude-sonnet-4.5", input, 10, 0)
793        };
794        record(&turn(Some(&project), 1_000));
795        record(&turn(Some(&project), 500));
796        record(&turn(Some(&other), 200));
797        record(&turn(None, 100));
798
799        let mine = persisted_snapshot_where(|key| key == project);
800        assert_eq!(mine.len(), 1);
801        assert_eq!(mine[0].requests, 2);
802        assert_eq!(mine[0].input_tokens, 1_500);
803        let persisted = load_persisted().expect("persisted");
804        let device = &persisted.models["claude-sonnet-4.5"];
805        let split: u64 = persisted_projects()
806            .iter()
807            .filter(|(key, _)| *key == project || *key == other)
808            .flat_map(|(_, models)| models.iter().map(|m| m.input_tokens))
809            .sum();
810        assert_eq!(split, 1_700);
811        assert!(
812            device.input_tokens >= 1_800,
813            "the device total keeps every turn, named or not"
814        );
815    }
816
817    /// #701: the verified pair is recorded only when the probe answered — both
818    /// sides of the pair or neither, never a half row.
819    #[test]
820    fn counterfactual_pair_recorded_only_when_probe_answered() {
821        let slot = super::super::counterfactual::CounterfactualSlot::new();
822        slot.set(5_000);
823        let with_probe = super::super::usage::RealUsage {
824            wire: Some(Box::new(super::super::usage::WireContext {
825                counterfactual: Some(slot),
826                ..Default::default()
827            })),
828            cache_write_tokens: 200,
829            ..usage("claude-sonnet-4.5", 1_000, 0, 300)
830        };
831        let mut acc = ModelUsage::default();
832        acc.add(&with_probe);
833        assert_eq!(acc.counterfactual_requests, 1);
834        assert_eq!(acc.counterfactual_input_tokens, 5_000);
835        // billed side = input + cache read + cache write of the same turn.
836        assert_eq!(acc.counterfactual_billed_tokens, 1_000 + 300 + 200);
837
838        // Empty slot (probe failed / still in flight) → row degrades to the
839        // estimate: no pair recorded, normal usage still counted.
840        let empty = super::super::usage::RealUsage {
841            wire: Some(Box::new(super::super::usage::WireContext {
842                counterfactual: Some(super::super::counterfactual::CounterfactualSlot::new()),
843                ..Default::default()
844            })),
845            ..usage("claude-sonnet-4.5", 1_000, 0, 0)
846        };
847        acc.add(&empty);
848        assert_eq!(acc.requests, 2);
849        assert_eq!(acc.counterfactual_requests, 1, "empty slot adds no pair");
850
851        // No wire context at all (tests / non-forward paths) → no pair.
852        acc.add(&usage("claude-sonnet-4.5", 10, 0, 0));
853        assert_eq!(acc.counterfactual_requests, 1);
854    }
855
856    /// #701: cross-model aggregation and the honest signed difference.
857    #[test]
858    fn verified_of_aggregates_and_reports_signed_savings() {
859        let mut map = HashMap::new();
860        assert!(verified_of(&map).is_none(), "no coverage → None, not zeros");
861
862        map.insert(
863            "claude-sonnet-4.5".to_string(),
864            ModelUsage {
865                counterfactual_requests: 2,
866                counterfactual_input_tokens: 10_000,
867                counterfactual_billed_tokens: 6_000,
868                ..Default::default()
869            },
870        );
871        // Stub overhead outweighed the squeeze on this model: billed MORE
872        // than the counterfactual. The total must subtract honestly.
873        map.insert(
874            "claude-haiku-4.5".to_string(),
875            ModelUsage {
876                counterfactual_requests: 1,
877                counterfactual_input_tokens: 1_000,
878                counterfactual_billed_tokens: 1_400,
879                ..Default::default()
880            },
881        );
882        let v = verified_of(&map).expect("covered rows present");
883        assert_eq!(v.requests, 3);
884        assert_eq!(v.counterfactual_input_tokens, 11_000);
885        assert_eq!(v.billed_input_tokens, 7_400);
886        assert_eq!(v.verified_saved_tokens, 3_600);
887
888        map.get_mut("claude-sonnet-4.5")
889            .unwrap()
890            .counterfactual_input_tokens = 0;
891        map.get_mut("claude-sonnet-4.5")
892            .unwrap()
893            .counterfactual_billed_tokens = 0;
894        let negative = verified_of(&map).unwrap();
895        assert_eq!(
896            negative.verified_saved_tokens, -400,
897            "a net-negative verified saving is reported, never clamped"
898        );
899    }
900
901    /// #701: persisted usage files from before the feature load cleanly and
902    /// the new fields round-trip.
903    #[test]
904    fn counterfactual_fields_roundtrip_and_default_for_legacy_files() {
905        let legacy = r#"{"ts":1,"models":{"m":{"requests":1,"input_tokens":10,"output_tokens":5,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0}}}"#;
906        let p: PersistedUsage = serde_json::from_str(legacy).expect("legacy file loads");
907        assert_eq!(p.models["m"].counterfactual_requests, 0);
908
909        let mut p = PersistedUsage::default();
910        p.models.insert(
911            "m".into(),
912            ModelUsage {
913                counterfactual_requests: 4,
914                counterfactual_input_tokens: 9_999,
915                counterfactual_billed_tokens: 5_555,
916                ..Default::default()
917            },
918        );
919        let back: PersistedUsage =
920            serde_json::from_str(&serde_json::to_string(&p).unwrap()).unwrap();
921        assert_eq!(back.models["m"].counterfactual_input_tokens, 9_999);
922        assert_eq!(back.models["m"].counterfactual_billed_tokens, 5_555);
923    }
924
925    #[test]
926    fn prices_known_model_with_cache_split() {
927        let mut map = HashMap::new();
928        let mut acc = ModelUsage::default();
929        acc.add(&usage("claude-sonnet-4.5", 1_000_000, 1_000_000, 1_000_000));
930        map.insert("claude-sonnet-4.5".to_string(), acc);
931
932        let rows = price_models(&map);
933        assert_eq!(rows.len(), 1);
934        let row = &rows[0];
935        // input 3.00 + output 15.00 + cache_read 0.30 (per 1M) = 18.30.
936        assert!(
937            (row.cost_usd - 18.30).abs() < 1e-6,
938            "cost was {}",
939            row.cost_usd
940        );
941        assert!(!row.pricing_estimated, "exact model match");
942        assert_eq!(row.requests, 1);
943    }
944
945    #[test]
946    fn unknown_model_prices_with_fallback_and_is_estimated() {
947        let mut map = HashMap::new();
948        let mut acc = ModelUsage::default();
949        acc.add(&usage("some-novel-model-xyz", 1_000_000, 0, 0));
950        map.insert("some-novel-model-xyz".to_string(), acc);
951
952        let rows = price_models(&map);
953        assert!(rows[0].pricing_estimated, "fallback pricing is estimated");
954        assert!(rows[0].cost_usd > 0.0);
955    }
956
957    /// #1179: turns carrying the provider's own charge book that USD; only the
958    /// remaining (unmeasured) turns are table-priced — and a fully measured
959    /// model is never flagged as estimated, even when the table has no entry.
960    /// (Model name chosen to never hit the embedded or live price tables.)
961    #[test]
962    fn measured_provider_cost_replaces_table_estimate() {
963        const MODEL: &str = "vendor/unlisted-model-20990101";
964        let mut acc = ModelUsage::default();
965        let mut measured = usage(MODEL, 431_600, 22_700, 126_700);
966        measured.provider_cost_usd = Some(0.05);
967        acc.add(&measured);
968
969        let mut map = HashMap::new();
970        map.insert(MODEL.to_string(), acc.clone());
971        let row = &price_models(&map)[0];
972        assert!(
973            (row.cost_usd - 0.05).abs() < 1e-12,
974            "the bill, not the table"
975        );
976        assert!((row.measured_cost_usd - 0.05).abs() < 1e-12);
977        assert_eq!(row.measured_requests, 1);
978        assert!(
979            !row.pricing_estimated,
980            "fully measured spend is not an estimate"
981        );
982
983        // A second, unmeasured turn on the same model: its tokens are priced
984        // from the table ON TOP of the measured USD, never double-counted
985        // (10k tokens at the $2.50/M blended fallback ≈ $0.025).
986        acc.add(&usage(MODEL, 10_000, 0, 0));
987        let mut map = HashMap::new();
988        map.insert(MODEL.to_string(), acc);
989        let row = &price_models(&map)[0];
990        assert!(row.cost_usd > 0.05, "unmeasured remainder adds table cost");
991        assert!(row.cost_usd < 0.2, "measured slice must not be re-priced");
992        assert!(
993            row.pricing_estimated,
994            "unmeasured remainder is heuristically priced"
995        );
996    }
997
998    #[test]
999    fn measured_slice_roundtrips_and_defaults_for_legacy_files() {
1000        let legacy = r#"{"ts":1,"models":{"m":{"requests":1,"input_tokens":10,"output_tokens":5,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0}}}"#;
1001        let p: PersistedUsage = serde_json::from_str(legacy).expect("legacy file loads");
1002        assert_eq!(p.models["m"].measured, MeasuredSlice::default());
1003
1004        let mut p = PersistedUsage::default();
1005        let mut acc = ModelUsage::default();
1006        let mut m = usage("m", 100, 10, 0);
1007        m.provider_cost_usd = Some(0.5);
1008        acc.add(&m);
1009        p.models.insert("m".into(), acc);
1010        let back: PersistedUsage =
1011            serde_json::from_str(&serde_json::to_string(&p).unwrap()).unwrap();
1012        assert_eq!(back.models["m"].measured.requests, 1);
1013        assert!((back.models["m"].measured.cost_usd - 0.5).abs() < 1e-12);
1014    }
1015
1016    #[test]
1017    fn dominant_model_picks_highest_token_real_model() {
1018        let mut models = HashMap::new();
1019        models.insert("claude-haiku-4.5".to_string(), {
1020            let mut u = ModelUsage::default();
1021            u.add(&usage("claude-haiku-4.5", 100, 100, 0));
1022            u
1023        });
1024        models.insert("claude-opus-4.5".to_string(), {
1025            let mut u = ModelUsage::default();
1026            u.add(&usage("claude-opus-4.5", 10_000, 10_000, 0));
1027            u
1028        });
1029        models.insert("unknown".to_string(), {
1030            let mut u = ModelUsage::default();
1031            u.add(&usage("unknown", 999_999, 0, 0));
1032            u
1033        });
1034        let dominant = models
1035            .iter()
1036            .filter(|(m, _)| m.as_str() != "unknown")
1037            .max_by_key(|(_, u)| u.billable_tokens())
1038            .map(|(m, _)| m.clone());
1039        assert_eq!(dominant.as_deref(), Some("claude-opus-4.5"));
1040    }
1041
1042    #[test]
1043    fn empty_model_buckets_as_unknown() {
1044        assert_eq!(normalize_key("  "), "unknown");
1045        assert_eq!(normalize_key(""), "unknown");
1046        assert_eq!(normalize_key("gpt-5.4"), "gpt-5.4");
1047    }
1048
1049    #[test]
1050    fn cohort_avg_output_is_mean_per_turn() {
1051        let mut c = CohortUsage::default();
1052        assert_eq!(c.avg_output(), None, "no observations → None");
1053        c.add(&usage("m", 10, 100, 0));
1054        c.add(&usage("m", 10, 50, 0));
1055        assert_eq!(c.requests, 2);
1056        assert_eq!(c.output_tokens, 150);
1057        assert!((c.avg_output().unwrap() - 75.0).abs() < f64::EPSILON);
1058    }
1059
1060    #[test]
1061    fn persisted_usage_without_cohorts_field_loads() {
1062        // proxy_usage.json written before #895 has no `cohorts` key; serde(default)
1063        // must backfill an empty map so old files stay loadable.
1064        let json = r#"{"ts":1,"models":{"gpt-5.4":{"requests":1,"input_tokens":10,"output_tokens":5,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0}}}"#;
1065        let p: PersistedUsage = serde_json::from_str(json).expect("loads legacy file");
1066        assert_eq!(p.models.len(), 1);
1067        assert!(p.cohorts.is_empty());
1068    }
1069
1070    #[test]
1071    fn persisted_usage_roundtrips_cohorts() {
1072        let mut p = PersistedUsage::default();
1073        p.cohorts.insert(
1074            "control".into(),
1075            CohortUsage {
1076                requests: 3,
1077                input_tokens: 30,
1078                output_tokens: 300,
1079                sum_sq_output: 30_000,
1080                ..CohortUsage::default()
1081            },
1082        );
1083        let json = serde_json::to_string(&p).unwrap();
1084        let back: PersistedUsage = serde_json::from_str(&json).unwrap();
1085        assert_eq!(back.cohorts.get("control").unwrap().output_tokens, 300);
1086    }
1087
1088    #[test]
1089    fn managed_usage_projects_once_and_unmanaged_is_skipped() {
1090        let sink = crate::core::ocla::builtin::usage_sink::BuiltinUsageSink::new();
1091        let usage = super::super::usage::RealUsage {
1092            model: "gpt-5".into(),
1093            input_tokens: 100,
1094            output_tokens: 40,
1095            cache_read_tokens: 20,
1096            cache_write_tokens: 5,
1097            wire: Some(Box::new(super::super::usage::WireContext {
1098                lineage: Some(crate::core::ocla::OclaRequestContext {
1099                    request_id: "request-1".into(),
1100                    session_id: "session-1".into(),
1101                    agent_id: "agent-1".into(),
1102                    content_ref: "blake3:content".into(),
1103                    tenant_id: None,
1104                    trace_id: "tr-unit".into(),
1105                    task_id: None,
1106                    parent_task_id: None,
1107                }),
1108                ..Default::default()
1109            })),
1110            ..Default::default()
1111        };
1112
1113        project_ocla_usage(&usage, &sink);
1114        assert_eq!(sink.record_count(), 1);
1115        assert_eq!(sink.total_input_tokens(), 125);
1116        assert_eq!(sink.total_output_tokens(), 40);
1117
1118        project_ocla_usage(
1119            &super::super::usage::RealUsage {
1120                model: "unmanaged".into(),
1121                input_tokens: 999,
1122                ..Default::default()
1123            },
1124            &sink,
1125        );
1126        assert_eq!(sink.record_count(), 1);
1127    }
1128}