Skip to main content

lean_ctx_proxy/
usage_meter.rs

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