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    /// Average output tokens per turn, or `None` with no observations.
212    #[must_use]
213    pub fn avg_output(&self) -> Option<f64> {
214        if self.requests == 0 {
215            None
216        } else {
217            #[allow(clippy::cast_precision_loss)]
218            Some(self.output_tokens as f64 / self.requests as f64)
219        }
220    }
221
222    /// Unbiased sample variance of per-turn output tokens, or `None` with < 2
223    /// observations. Computed from the running sum / sum-of-squares (clamped at
224    /// 0 to absorb floating-point error on near-constant samples).
225    #[must_use]
226    pub fn variance_output(&self) -> Option<f64> {
227        if self.requests < 2 {
228            return None;
229        }
230        #[allow(clippy::cast_precision_loss)]
231        let n = self.requests as f64;
232        #[allow(clippy::cast_precision_loss)]
233        let sum = self.output_tokens as f64;
234        #[allow(clippy::cast_precision_loss)]
235        let sum_sq = self.sum_sq_output as f64;
236        let var = (sum_sq - sum * sum / n) / (n - 1.0);
237        Some(var.max(0.0))
238    }
239}
240
241/// On-disk shape of the measured spend totals.
242#[derive(Debug, Clone, Default, Serialize, Deserialize)]
243pub struct PersistedUsage {
244    pub ts: u64,
245    pub models: HashMap<String, ModelUsage>,
246    /// Output-savings cohort totals (#895). `#[serde(default)]` keeps older
247    /// `proxy_usage.json` files (written before the holdout existed) loadable.
248    #[serde(default)]
249    pub cohorts: HashMap<String, CohortUsage>,
250}
251
252/// Distinct-model bucket cap. `record` keys on the raw response model string, so
253/// overflow folds into "unknown" to keep the map bounded (real model names < ~50).
254const MAX_TRACKED_MODELS: usize = 256;
255
256const PROXY_USAGE_FILE: &str = "proxy_usage.json";
257
258fn store() -> &'static Mutex<HashMap<String, ModelUsage>> {
259    static STORE: OnceLock<Mutex<HashMap<String, ModelUsage>>> = OnceLock::new();
260    STORE.get_or_init(|| Mutex::new(HashMap::new()))
261}
262
263fn cohort_store() -> &'static Mutex<HashMap<String, CohortUsage>> {
264    static STORE: OnceLock<Mutex<HashMap<String, CohortUsage>>> = OnceLock::new();
265    STORE.get_or_init(|| Mutex::new(HashMap::new()))
266}
267
268/// Seeds the in-memory totals from `proxy_usage.json`. Call once on proxy
269/// startup so measured spend is cumulative across restarts. Idempotent-ish: it
270/// merges the persisted totals into whatever is in memory (normally empty).
271pub fn resume_from_disk() {
272    let Some(persisted) = load_persisted() else {
273        return;
274    };
275    let mut map = store()
276        .lock()
277        .unwrap_or_else(std::sync::PoisonError::into_inner);
278    for (model, usage) in persisted.models {
279        let acc = map.entry(model).or_default();
280        acc.requests += usage.requests;
281        acc.input_tokens += usage.input_tokens;
282        acc.output_tokens += usage.output_tokens;
283        acc.cache_read_tokens += usage.cache_read_tokens;
284        acc.cache_write_tokens += usage.cache_write_tokens;
285        acc.reasoning_tokens += usage.reasoning_tokens;
286        acc.counterfactual_requests += usage.counterfactual_requests;
287        acc.counterfactual_input_tokens += usage.counterfactual_input_tokens;
288        acc.counterfactual_billed_tokens += usage.counterfactual_billed_tokens;
289        acc.measured.merge(&usage.measured);
290        for observation in usage.response_observations {
291            acc.add_observation(observation);
292        }
293    }
294    drop(map);
295    let mut cohorts = cohort_store()
296        .lock()
297        .unwrap_or_else(std::sync::PoisonError::into_inner);
298    for (arm, usage) in persisted.cohorts {
299        let acc = cohorts.entry(arm).or_default();
300        acc.requests += usage.requests;
301        acc.input_tokens += usage.input_tokens;
302        acc.output_tokens += usage.output_tokens;
303    }
304}
305
306/// Records one turn's measured usage against its model bucket (and its
307/// output-savings cohort, when tagged) and persists.
308pub fn record(u: &super::usage::RealUsage) {
309    // Gateway store subscription (enterprise#17): forward the full record to
310    // the installed sink (no-op locally). Never blocks the request path.
311    super::usage_sink::push(u);
312
313    // R33: Feed measured usage into kernel envelope pipeline.
314    {
315        let label = u.wire.as_ref().map_or("Unknown", |w| {
316            // provider_kind_from_label expects a static or owned string;
317            // the label lives long enough for the conversion call.
318            match w.provider.as_str() {
319                "Anthropic" => "Anthropic",
320                "OpenAI" | "ChatGPT" => "OpenAI",
321                "Gemini" => "Gemini",
322                "Bedrock" => "Bedrock",
323                "Azure" => "Azure",
324                _ => "Unknown",
325            }
326        });
327        let envelope = super::usage_parity::real_usage_to_envelope(u, label);
328        crate::core::context_kernel::envelope_bridge::record_proxy_envelope(&envelope);
329    }
330
331    // OCLA projection: keep the canonical usage capability on the same single
332    // finalized-turn choke-point without feeding back into billing or ledger
333    // aggregation. Invalid/missing lineage stays explicitly unmanaged.
334    project_ocla_usage(u, OclaRegistry::global().usage_sink.as_ref());
335
336    // Budget windows (enterprise#25): book this turn's measured cost against
337    // the person/day and project/month accumulators the policy gate checks.
338    // The provider's own reported charge wins (#1179); local turns book the
339    // shadow rate — the same valuation the usage store applies — so
340    // local-only budgets stay meaningful.
341    #[cfg(feature = "enterprise")]
342    if let Some(wire) = u.wire.as_deref()
343        && (wire.person.is_some() || wire.project.is_some())
344    {
345        let baseline = crate::core::config::Config::load().proxy.baseline.clone();
346        #[allow(clippy::cast_precision_loss)]
347        let cost_usd = if wire.is_local {
348            let billable =
349                u.input_tokens + u.output_tokens + u.cache_read_tokens + u.cache_write_tokens;
350            baseline.effective_local_shadow_rate() / 1_000_000.0 * billable as f64
351        } else if let Some(measured) = u.provider_cost_usd {
352            measured
353        } else {
354            crate::core::gain::model_pricing::ModelPricing::load()
355                .quote(Some(&u.model))
356                .cost
357                .estimate_usd(
358                    u.input_tokens,
359                    u.output_tokens,
360                    u.cache_write_tokens,
361                    u.cache_read_tokens,
362                )
363        };
364        super::policy_gate::record_spend(wire.person.as_deref(), wire.project.as_deref(), cost_usd);
365    }
366
367    // Mechanism attribution into the local savings ledger (enterprise#19):
368    // provider prompt-cache reads billed below the input rate. Best-effort,
369    // never blocking. A model swap is never booked as a LeanCTX saving.
370    if u.cache_read_tokens > 0 {
371        let cost = crate::core::gain::model_pricing::ModelPricing::load()
372            .quote(Some(&u.model))
373            .cost;
374        #[allow(clippy::cast_precision_loss)]
375        let discount_usd =
376            (cost.input_per_m - cost.cache_read_per_m) / 1_000_000.0 * u.cache_read_tokens as f64;
377        crate::core::savings_ledger::record_caching_event(
378            &u.model,
379            u.cache_read_tokens,
380            discount_usd,
381        );
382    }
383
384    let key = normalize_key(&u.model);
385    {
386        let mut map = store()
387            .lock()
388            .unwrap_or_else(std::sync::PoisonError::into_inner);
389        let key = if !map.contains_key(&key) && map.len() >= MAX_TRACKED_MODELS {
390            "unknown".to_string()
391        } else {
392            key
393        };
394        map.entry(key).or_default().add(u);
395    }
396    if u.cohort.output.is_some() || u.cohort.compression.is_some() {
397        let mut cohorts = cohort_store()
398            .lock()
399            .unwrap_or_else(std::sync::PoisonError::into_inner);
400        if let Some(arm) = u.cohort.output {
401            cohorts.entry(arm.as_str().to_string()).or_default().add(u);
402        }
403        if let Some(arm) = u.cohort.compression {
404            cohorts
405                .entry(compression_cohort_key(arm))
406                .or_default()
407                .add(u);
408        }
409    }
410    persist();
411}
412
413/// Live output-savings cohort totals (#895). Empty until a holdout runs.
414#[must_use]
415pub fn cohort_snapshot() -> HashMap<String, CohortUsage> {
416    cohort_store()
417        .lock()
418        .unwrap_or_else(std::sync::PoisonError::into_inner)
419        .clone()
420}
421
422/// Cross-process read of the persisted output-savings cohort totals.
423#[must_use]
424pub fn persisted_cohorts() -> HashMap<String, CohortUsage> {
425    load_persisted().map(|p| p.cohorts).unwrap_or_default()
426}
427
428fn normalize_key(model: &str) -> String {
429    let m = model.trim();
430    if m.is_empty() {
431        "unknown".to_string()
432    } else {
433        m.to_string()
434    }
435}
436
437/// Live per-model measured spend, priced and sorted by USD descending.
438pub fn snapshot() -> Vec<ModelSpend> {
439    let map = store()
440        .lock()
441        .unwrap_or_else(std::sync::PoisonError::into_inner);
442    price_models(&map)
443}
444
445/// Total measured spend across all models (live in-memory totals).
446pub fn total_cost_usd() -> f64 {
447    snapshot().iter().map(|m| m.cost_usd).sum()
448}
449
450/// Cross-model verified-savings totals (#701) for `/status` and the dashboard.
451#[derive(Debug, Clone, Serialize, PartialEq)]
452pub struct VerifiedSavings {
453    /// Requests covered by a successful `count_tokens` probe.
454    pub requests: u64,
455    /// Provider-counted input tokens those requests would have billed
456    /// without lean-ctx.
457    pub counterfactual_input_tokens: u64,
458    /// Input-side tokens (input + cache read + cache write) they actually
459    /// billed.
460    pub billed_input_tokens: u64,
461    /// `counterfactual - billed`; negative when stub overhead outweighed the
462    /// squeeze — reported honestly, never clamped.
463    pub verified_saved_tokens: i64,
464}
465
466/// Aggregated provider-verified savings across all models (#701), or `None`
467/// until at least one probe-covered request has been recorded. Unlike the
468/// `tokens_saved` estimate (bytes/4), both sides of this pair were counted by
469/// the provider on the same request — receipts, not estimates.
470pub fn verified_savings() -> Option<VerifiedSavings> {
471    let map = store()
472        .lock()
473        .unwrap_or_else(std::sync::PoisonError::into_inner);
474    verified_of(&map)
475}
476
477/// Pure aggregation behind [`verified_savings`], shared with tests.
478#[allow(clippy::cast_possible_wrap)]
479fn verified_of(map: &HashMap<String, ModelUsage>) -> Option<VerifiedSavings> {
480    let (mut requests, mut counterfactual, mut billed) = (0u64, 0u64, 0u64);
481    for usage in map.values() {
482        requests += usage.counterfactual_requests;
483        counterfactual += usage.counterfactual_input_tokens;
484        billed += usage.counterfactual_billed_tokens;
485    }
486    (requests > 0).then(|| VerifiedSavings {
487        requests,
488        counterfactual_input_tokens: counterfactual,
489        billed_input_tokens: billed,
490        verified_saved_tokens: counterfactual as i64 - billed as i64,
491    })
492}
493
494/// Prices a model usage map into sorted [`ModelSpend`] rows. Pure: shared by the
495/// in-memory snapshot and the cross-process [`persisted_snapshot`].
496pub fn price_models(map: &HashMap<String, ModelUsage>) -> Vec<ModelSpend> {
497    let pricing = ModelPricing::load();
498    let mut rows: Vec<ModelSpend> = map
499        .iter()
500        .map(|(model, usage)| price_one(&pricing, model, usage))
501        .collect();
502    rows.sort_by(|a, b| {
503        b.cost_usd
504            .partial_cmp(&a.cost_usd)
505            .unwrap_or(std::cmp::Ordering::Equal)
506    });
507    rows
508}
509
510fn price_one(pricing: &ModelPricing, model: &str, usage: &ModelUsage) -> ModelSpend {
511    let quote = pricing.quote(Some(model));
512    // Measured-first (#1179): turns whose response carried the provider's own
513    // USD charge book that exact amount; only the remainder is table-priced.
514    let m = &usage.measured;
515    let derived_cost = quote.cost.estimate_usd(
516        usage.input_tokens.saturating_sub(m.input_tokens),
517        usage.output_tokens.saturating_sub(m.output_tokens),
518        usage
519            .cache_write_tokens
520            .saturating_sub(m.cache_write_tokens),
521        usage.cache_read_tokens.saturating_sub(m.cache_read_tokens),
522    );
523    let derived_requests = usage.requests.saturating_sub(m.requests);
524    ModelSpend {
525        model: model.to_string(),
526        requests: usage.requests,
527        input_tokens: usage.input_tokens,
528        output_tokens: usage.output_tokens,
529        cache_read_tokens: usage.cache_read_tokens,
530        cache_write_tokens: usage.cache_write_tokens,
531        reasoning_tokens: usage.reasoning_tokens,
532        cost_usd: m.cost_usd + derived_cost,
533        measured_cost_usd: m.cost_usd,
534        measured_requests: m.requests,
535        // Fully measured spend is never an estimate, whatever the table says.
536        pricing_estimated: quote.match_kind.is_estimated() && derived_requests > 0,
537    }
538}
539
540fn usage_path() -> Option<std::path::PathBuf> {
541    crate::core::data_dir::lean_ctx_data_dir()
542        .ok()
543        .map(|d| d.join(PROXY_USAGE_FILE))
544}
545
546/// Atomically writes the current in-memory totals to disk.
547fn persist() {
548    let Some(path) = usage_path() else {
549        return;
550    };
551    let models = {
552        let map = store()
553            .lock()
554            .unwrap_or_else(std::sync::PoisonError::into_inner);
555        map.clone()
556    };
557    let cohorts = {
558        let map = cohort_store()
559            .lock()
560            .unwrap_or_else(std::sync::PoisonError::into_inner);
561        map.clone()
562    };
563    let payload = PersistedUsage {
564        ts: std::time::SystemTime::now()
565            .duration_since(std::time::UNIX_EPOCH)
566            .unwrap_or_default()
567            .as_secs(),
568        models,
569        cohorts,
570    };
571    let Ok(json) = serde_json::to_string(&payload) else {
572        return;
573    };
574    let tmp = path.with_extension("json.tmp");
575    if std::fs::write(&tmp, json).is_ok() {
576        let _ = std::fs::rename(&tmp, &path);
577    }
578}
579
580/// Cross-process read of the persisted measured spend (dashboard / CLI / ledger).
581pub fn load_persisted() -> Option<PersistedUsage> {
582    let path = usage_path()?;
583    let data = std::fs::read_to_string(path).ok()?;
584    serde_json::from_str(&data).ok()
585}
586
587/// Cross-process priced spend rows, read from disk.
588pub fn persisted_snapshot() -> Vec<ModelSpend> {
589    load_persisted()
590        .map(|p| price_models(&p.models))
591        .unwrap_or_default()
592}
593
594/// The model carrying the most measured tokens (excludes the "unknown" bucket).
595/// Used to value savings against the real dominant model when no explicit model
596/// is configured.
597pub fn persisted_dominant_model() -> Option<String> {
598    let persisted = load_persisted()?;
599    persisted
600        .models
601        .iter()
602        .filter(|(m, _)| m.as_str() != "unknown" && !m.trim().is_empty())
603        .max_by_key(|(_, u)| u.billable_tokens())
604        .filter(|(_, u)| u.billable_tokens() > 0)
605        .map(|(m, _)| m.clone())
606}
607
608#[cfg(test)]
609mod tests {
610    use super::*;
611
612    fn usage(
613        model: &str,
614        input: u64,
615        output: u64,
616        cache_read: u64,
617    ) -> super::super::usage::RealUsage {
618        super::super::usage::RealUsage {
619            model: model.to_string(),
620            input_tokens: input,
621            output_tokens: output,
622            cache_read_tokens: cache_read,
623            ..Default::default()
624        }
625    }
626
627    /// #701: the verified pair is recorded only when the probe answered — both
628    /// sides of the pair or neither, never a half row.
629    #[test]
630    fn counterfactual_pair_recorded_only_when_probe_answered() {
631        let slot = super::super::counterfactual::CounterfactualSlot::new();
632        slot.set(5_000);
633        let with_probe = super::super::usage::RealUsage {
634            wire: Some(Box::new(super::super::usage::WireContext {
635                counterfactual: Some(slot),
636                ..Default::default()
637            })),
638            cache_write_tokens: 200,
639            ..usage("claude-sonnet-4.5", 1_000, 0, 300)
640        };
641        let mut acc = ModelUsage::default();
642        acc.add(&with_probe);
643        assert_eq!(acc.counterfactual_requests, 1);
644        assert_eq!(acc.counterfactual_input_tokens, 5_000);
645        // billed side = input + cache read + cache write of the same turn.
646        assert_eq!(acc.counterfactual_billed_tokens, 1_000 + 300 + 200);
647
648        // Empty slot (probe failed / still in flight) → row degrades to the
649        // estimate: no pair recorded, normal usage still counted.
650        let empty = super::super::usage::RealUsage {
651            wire: Some(Box::new(super::super::usage::WireContext {
652                counterfactual: Some(super::super::counterfactual::CounterfactualSlot::new()),
653                ..Default::default()
654            })),
655            ..usage("claude-sonnet-4.5", 1_000, 0, 0)
656        };
657        acc.add(&empty);
658        assert_eq!(acc.requests, 2);
659        assert_eq!(acc.counterfactual_requests, 1, "empty slot adds no pair");
660
661        // No wire context at all (tests / non-forward paths) → no pair.
662        acc.add(&usage("claude-sonnet-4.5", 10, 0, 0));
663        assert_eq!(acc.counterfactual_requests, 1);
664    }
665
666    /// #701: cross-model aggregation and the honest signed difference.
667    #[test]
668    fn verified_of_aggregates_and_reports_signed_savings() {
669        let mut map = HashMap::new();
670        assert!(verified_of(&map).is_none(), "no coverage → None, not zeros");
671
672        map.insert(
673            "claude-sonnet-4.5".to_string(),
674            ModelUsage {
675                counterfactual_requests: 2,
676                counterfactual_input_tokens: 10_000,
677                counterfactual_billed_tokens: 6_000,
678                ..Default::default()
679            },
680        );
681        // Stub overhead outweighed the squeeze on this model: billed MORE
682        // than the counterfactual. The total must subtract honestly.
683        map.insert(
684            "claude-haiku-4.5".to_string(),
685            ModelUsage {
686                counterfactual_requests: 1,
687                counterfactual_input_tokens: 1_000,
688                counterfactual_billed_tokens: 1_400,
689                ..Default::default()
690            },
691        );
692        let v = verified_of(&map).expect("covered rows present");
693        assert_eq!(v.requests, 3);
694        assert_eq!(v.counterfactual_input_tokens, 11_000);
695        assert_eq!(v.billed_input_tokens, 7_400);
696        assert_eq!(v.verified_saved_tokens, 3_600);
697
698        map.get_mut("claude-sonnet-4.5")
699            .unwrap()
700            .counterfactual_input_tokens = 0;
701        map.get_mut("claude-sonnet-4.5")
702            .unwrap()
703            .counterfactual_billed_tokens = 0;
704        let negative = verified_of(&map).unwrap();
705        assert_eq!(
706            negative.verified_saved_tokens, -400,
707            "a net-negative verified saving is reported, never clamped"
708        );
709    }
710
711    /// #701: persisted usage files from before the feature load cleanly and
712    /// the new fields round-trip.
713    #[test]
714    fn counterfactual_fields_roundtrip_and_default_for_legacy_files() {
715        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}}}"#;
716        let p: PersistedUsage = serde_json::from_str(legacy).expect("legacy file loads");
717        assert_eq!(p.models["m"].counterfactual_requests, 0);
718
719        let mut p = PersistedUsage::default();
720        p.models.insert(
721            "m".into(),
722            ModelUsage {
723                counterfactual_requests: 4,
724                counterfactual_input_tokens: 9_999,
725                counterfactual_billed_tokens: 5_555,
726                ..Default::default()
727            },
728        );
729        let back: PersistedUsage =
730            serde_json::from_str(&serde_json::to_string(&p).unwrap()).unwrap();
731        assert_eq!(back.models["m"].counterfactual_input_tokens, 9_999);
732        assert_eq!(back.models["m"].counterfactual_billed_tokens, 5_555);
733    }
734
735    #[test]
736    fn prices_known_model_with_cache_split() {
737        let mut map = HashMap::new();
738        let mut acc = ModelUsage::default();
739        acc.add(&usage("claude-sonnet-4.5", 1_000_000, 1_000_000, 1_000_000));
740        map.insert("claude-sonnet-4.5".to_string(), acc);
741
742        let rows = price_models(&map);
743        assert_eq!(rows.len(), 1);
744        let row = &rows[0];
745        // input 3.00 + output 15.00 + cache_read 0.30 (per 1M) = 18.30.
746        assert!(
747            (row.cost_usd - 18.30).abs() < 1e-6,
748            "cost was {}",
749            row.cost_usd
750        );
751        assert!(!row.pricing_estimated, "exact model match");
752        assert_eq!(row.requests, 1);
753    }
754
755    #[test]
756    fn unknown_model_prices_with_fallback_and_is_estimated() {
757        let mut map = HashMap::new();
758        let mut acc = ModelUsage::default();
759        acc.add(&usage("some-novel-model-xyz", 1_000_000, 0, 0));
760        map.insert("some-novel-model-xyz".to_string(), acc);
761
762        let rows = price_models(&map);
763        assert!(rows[0].pricing_estimated, "fallback pricing is estimated");
764        assert!(rows[0].cost_usd > 0.0);
765    }
766
767    /// #1179: turns carrying the provider's own charge book that USD; only the
768    /// remaining (unmeasured) turns are table-priced — and a fully measured
769    /// model is never flagged as estimated, even when the table has no entry.
770    /// (Model name chosen to never hit the embedded or live price tables.)
771    #[test]
772    fn measured_provider_cost_replaces_table_estimate() {
773        const MODEL: &str = "vendor/unlisted-model-20990101";
774        let mut acc = ModelUsage::default();
775        let mut measured = usage(MODEL, 431_600, 22_700, 126_700);
776        measured.provider_cost_usd = Some(0.05);
777        acc.add(&measured);
778
779        let mut map = HashMap::new();
780        map.insert(MODEL.to_string(), acc.clone());
781        let row = &price_models(&map)[0];
782        assert!(
783            (row.cost_usd - 0.05).abs() < 1e-12,
784            "the bill, not the table"
785        );
786        assert!((row.measured_cost_usd - 0.05).abs() < 1e-12);
787        assert_eq!(row.measured_requests, 1);
788        assert!(
789            !row.pricing_estimated,
790            "fully measured spend is not an estimate"
791        );
792
793        // A second, unmeasured turn on the same model: its tokens are priced
794        // from the table ON TOP of the measured USD, never double-counted
795        // (10k tokens at the $2.50/M blended fallback ≈ $0.025).
796        acc.add(&usage(MODEL, 10_000, 0, 0));
797        let mut map = HashMap::new();
798        map.insert(MODEL.to_string(), acc);
799        let row = &price_models(&map)[0];
800        assert!(row.cost_usd > 0.05, "unmeasured remainder adds table cost");
801        assert!(row.cost_usd < 0.2, "measured slice must not be re-priced");
802        assert!(
803            row.pricing_estimated,
804            "unmeasured remainder is heuristically priced"
805        );
806    }
807
808    #[test]
809    fn measured_slice_roundtrips_and_defaults_for_legacy_files() {
810        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}}}"#;
811        let p: PersistedUsage = serde_json::from_str(legacy).expect("legacy file loads");
812        assert_eq!(p.models["m"].measured, MeasuredSlice::default());
813
814        let mut p = PersistedUsage::default();
815        let mut acc = ModelUsage::default();
816        let mut m = usage("m", 100, 10, 0);
817        m.provider_cost_usd = Some(0.5);
818        acc.add(&m);
819        p.models.insert("m".into(), acc);
820        let back: PersistedUsage =
821            serde_json::from_str(&serde_json::to_string(&p).unwrap()).unwrap();
822        assert_eq!(back.models["m"].measured.requests, 1);
823        assert!((back.models["m"].measured.cost_usd - 0.5).abs() < 1e-12);
824    }
825
826    #[test]
827    fn dominant_model_picks_highest_token_real_model() {
828        let mut models = HashMap::new();
829        models.insert("claude-haiku-4.5".to_string(), {
830            let mut u = ModelUsage::default();
831            u.add(&usage("claude-haiku-4.5", 100, 100, 0));
832            u
833        });
834        models.insert("claude-opus-4.5".to_string(), {
835            let mut u = ModelUsage::default();
836            u.add(&usage("claude-opus-4.5", 10_000, 10_000, 0));
837            u
838        });
839        models.insert("unknown".to_string(), {
840            let mut u = ModelUsage::default();
841            u.add(&usage("unknown", 999_999, 0, 0));
842            u
843        });
844        let dominant = models
845            .iter()
846            .filter(|(m, _)| m.as_str() != "unknown")
847            .max_by_key(|(_, u)| u.billable_tokens())
848            .map(|(m, _)| m.clone());
849        assert_eq!(dominant.as_deref(), Some("claude-opus-4.5"));
850    }
851
852    #[test]
853    fn empty_model_buckets_as_unknown() {
854        assert_eq!(normalize_key("  "), "unknown");
855        assert_eq!(normalize_key(""), "unknown");
856        assert_eq!(normalize_key("gpt-5.4"), "gpt-5.4");
857    }
858
859    #[test]
860    fn cohort_avg_output_is_mean_per_turn() {
861        let mut c = CohortUsage::default();
862        assert_eq!(c.avg_output(), None, "no observations → None");
863        c.add(&usage("m", 10, 100, 0));
864        c.add(&usage("m", 10, 50, 0));
865        assert_eq!(c.requests, 2);
866        assert_eq!(c.output_tokens, 150);
867        assert!((c.avg_output().unwrap() - 75.0).abs() < f64::EPSILON);
868    }
869
870    #[test]
871    fn persisted_usage_without_cohorts_field_loads() {
872        // proxy_usage.json written before #895 has no `cohorts` key; serde(default)
873        // must backfill an empty map so old files stay loadable.
874        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}}}"#;
875        let p: PersistedUsage = serde_json::from_str(json).expect("loads legacy file");
876        assert_eq!(p.models.len(), 1);
877        assert!(p.cohorts.is_empty());
878    }
879
880    #[test]
881    fn persisted_usage_roundtrips_cohorts() {
882        let mut p = PersistedUsage::default();
883        p.cohorts.insert(
884            "control".into(),
885            CohortUsage {
886                requests: 3,
887                input_tokens: 30,
888                output_tokens: 300,
889                sum_sq_output: 30_000,
890                ..CohortUsage::default()
891            },
892        );
893        let json = serde_json::to_string(&p).unwrap();
894        let back: PersistedUsage = serde_json::from_str(&json).unwrap();
895        assert_eq!(back.cohorts.get("control").unwrap().output_tokens, 300);
896    }
897
898    #[test]
899    fn managed_usage_projects_once_and_unmanaged_is_skipped() {
900        let sink = crate::core::ocla::builtin::usage_sink::BuiltinUsageSink::new();
901        let usage = super::super::usage::RealUsage {
902            model: "gpt-5".into(),
903            input_tokens: 100,
904            output_tokens: 40,
905            cache_read_tokens: 20,
906            cache_write_tokens: 5,
907            wire: Some(Box::new(super::super::usage::WireContext {
908                lineage: Some(crate::core::ocla::OclaRequestContext {
909                    request_id: "request-1".into(),
910                    session_id: "session-1".into(),
911                    agent_id: "agent-1".into(),
912                    content_ref: "blake3:content".into(),
913                    tenant_id: None,
914                    trace_id: "tr-unit".into(),
915                    task_id: None,
916                    parent_task_id: None,
917                }),
918                ..Default::default()
919            })),
920            ..Default::default()
921        };
922
923        project_ocla_usage(&usage, &sink);
924        assert_eq!(sink.record_count(), 1);
925        assert_eq!(sink.total_input_tokens(), 125);
926        assert_eq!(sink.total_output_tokens(), 40);
927
928        project_ocla_usage(
929            &super::super::usage::RealUsage {
930                model: "unmanaged".into(),
931                input_tokens: 999,
932                ..Default::default()
933            },
934            &sink,
935        );
936        assert_eq!(sink.record_count(), 1);
937    }
938}