Skip to main content

lean_ctx/proxy/
usage.rs

1//! Real provider-reported token usage extraction.
2//!
3//! The proxy already rewrites requests; this module reads the *response* so the
4//! dashboard/terminal can show **measured** cost (the user's real provider bill)
5//! instead of an estimate. All three providers report the exact model and the
6//! billed token breakdown — including prompt-cache reads/writes — in the final
7//! event of a stream (or the body of a non-streaming response):
8//!
9//! - Anthropic: `message_start` carries model + input/cache tokens, the final
10//!   `message_delta` carries `output_tokens`. Non-streaming: one `usage` object.
11//! - OpenAI Responses: the `response.completed` event nests `response.usage`.
12//! - OpenAI Chat Completions: the final chunk carries `usage` (needs
13//!   `stream_options.include_usage`, which the proxy injects).
14//! - Gemini: every chunk carries `usageMetadata`; the last one has the totals.
15//!
16//! [`RealUsage`] normalizes every provider onto the four billable buckets that
17//! `crate::core::gain::model_pricing::ModelCost::estimate_usd` prices:
18//! uncached input, output (incl. reasoning/thoughts), cache-read, cache-write.
19
20use futures::{Stream, StreamExt};
21use serde::{Deserialize, Serialize};
22use serde_json::Value;
23
24/// Where provider usage was observed, not an assertion of answer quality or
25/// successful generation. Terminal usage also accompanies failed responses.
26#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
27#[serde(rename_all = "snake_case")]
28pub enum UsageBoundary {
29    BodyEnd,
30    ProviderTerminalUsage,
31    StreamEnd,
32    StreamError,
33}
34
35/// Payload-free local measurement. Unknown cost stays unknown; neither HTTP
36/// status nor receipt of usage supplies the private runtime's quality label.
37#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
38#[serde(deny_unknown_fields)]
39pub struct ResponseObservation {
40    pub schema_version: u8,
41    pub http_status: u16,
42    /// Monotonic elapsed time from upstream dispatch (including retries) to
43    /// the indicated usage boundary, not necessarily full response latency.
44    pub usage_observed_ms: u64,
45    pub boundary: UsageBoundary,
46    pub provider_cost_usd: Option<f64>,
47}
48
49/// LLM provider whose response shape a [`Scanner`] understands.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum Provider {
52    Anthropic,
53    /// Covers both Chat Completions and the Responses API (same `usage` dialects
54    /// are detected by field name).
55    OpenAi,
56    Gemini,
57}
58
59impl Provider {
60    /// Maps the proxy's `provider_label` (`"Anthropic"`, `"OpenAI"`/`"ChatGPT"`, else Gemini).
61    pub fn from_label(label: &str) -> Self {
62        match label {
63            "Anthropic" | "Bedrock" => Self::Anthropic,
64            "OpenAI" | "ChatGPT" | "Azure" => Self::OpenAi,
65            _ => Self::Gemini,
66        }
67    }
68}
69
70/// One LLM turn's real, provider-reported usage, normalized to billable buckets.
71///
72/// `output_tokens` already includes reasoning/thinking tokens (they are billed at
73/// the output rate); `reasoning_tokens` is retained only for display.
74#[derive(Debug, Clone, Default, PartialEq)]
75pub struct RealUsage {
76    pub model: String,
77    /// Input tokens billed at the input rate (cache reads/writes excluded).
78    pub input_tokens: u64,
79    /// Output tokens billed at the output rate (includes reasoning/thoughts).
80    pub output_tokens: u64,
81    /// Input tokens served from the prompt cache (billed at the cache-read rate).
82    pub cache_read_tokens: u64,
83    /// Input tokens written to the prompt cache (Anthropic + OpenRouter models
84    /// with explicit cache-write pricing; 0 elsewhere).
85    pub cache_write_tokens: u64,
86    /// Reasoning/thinking subset of `output_tokens` (display only).
87    pub reasoning_tokens: u64,
88    /// USD the provider *actually charged* for this turn, when the response
89    /// reports it. OpenRouter: `usage.cost` in credits (≡ USD); for BYOK
90    /// requests the separate `cost_details.upstream_inference_cost` is added
91    /// when it differs from `cost` (#746 — non-BYOK mirrors cost there).
92    /// The measured figure beats any price-table estimate wherever both exist.
93    /// `None` for providers that report tokens only (Anthropic/OpenAI/Gemini).
94    pub provider_cost_usd: Option<f64>,
95    /// Holdout arms for this turn: output shaping (#895 Track B) and input
96    /// compression (#1905), each `None` when that holdout is off. Stamped from
97    /// the request, not parsed from the response.
98    pub cohort: super::holdout::Cohorts,
99    /// Request-side gateway context (enterprise#11/#17/#18): identity tags,
100    /// compression savings and baseline inputs, stamped from the request before
101    /// it left for the upstream. `None` outside the forward path (e.g. tests
102    /// that only parse response bodies).
103    pub wire: Option<Box<WireContext>>,
104    /// Present only for measured upstream responses, never cache hits or
105    /// synthetic parser inputs. Kept local in the existing usage meter.
106    pub response_observation: Option<ResponseObservation>,
107}
108
109/// Request-side context the forward path knows and the response scanner does
110/// not: who sent the request (gateway identity, enterprise#11), what the proxy
111/// saved on the wire, and the counterfactual-baseline inputs (enterprise#18).
112/// Travels inside [`RealUsage`] so `usage_meter::record` stays the single
113/// choke-point through which every measured turn flows.
114#[derive(Debug, Clone, Default, PartialEq)]
115pub struct WireContext {
116    /// Provider label (`Anthropic|OpenAI|ChatGPT|Gemini`) of the serving route.
117    pub provider: String,
118    /// Person tag from the gateway key (enterprise#11).
119    pub person: Option<String>,
120    /// Team tag from the gateway key.
121    pub team: Option<String>,
122    /// Project: `x-leanctx-project` header wins over the key's default project.
123    pub project: Option<String>,
124    /// Local project key of the folder the agent named in the request
125    /// (`super::project_attribution`); splits measured spend per project.
126    pub project_key: Option<String>,
127    /// Estimated tokens this request saved through wire compression
128    /// (bytes/4 heuristic, same basis as the proxy stats).
129    pub saved_tokens: u64,
130    /// Estimated request tokens BEFORE lean-ctx compression (bytes/4) — the
131    /// SEE-attribution input of the avoided-cost baseline (enterprise#18).
132    pub uncompressed_input_tokens: u64,
133    /// True when the serving upstream is a local/loopback endpoint — billed via
134    /// the transparent `local_shadow_rate`, never 0 (enterprise#15/#18).
135    pub is_local: bool,
136    /// Originally requested model when the router downgraded/aliased it
137    /// (enterprise#13); `None` for passthrough.
138    pub routed_from: Option<String>,
139    /// Provider-counted input tokens of the ORIGINAL (uncompressed) request,
140    /// from the free `count_tokens` probe (#701). `None` when metering is off
141    /// or no probe was spawned; an empty slot at read time (probe failed or
142    /// still in flight) degrades the row to the local estimate.
143    pub counterfactual: Option<super::counterfactual::CounterfactualSlot>,
144    /// Complete, validated OCLA lineage for managed HTTP requests. `None` keeps
145    /// legacy, malformed and non-HTTP traffic explicitly unmanaged.
146    pub lineage: Option<crate::core::ocla::OclaRequestContext>,
147}
148
149impl WireContext {
150    #[must_use]
151    pub fn ocla_request_context(&self) -> Option<&crate::core::ocla::OclaRequestContext> {
152        self.lineage.as_ref()
153    }
154}
155
156impl RealUsage {
157    /// Projects measured proxy usage into the payload-free canonical OCLA record.
158    /// Missing lineage is unmanaged; invalid data and arithmetic overflow fail
159    /// closed for OCLA without disturbing the existing usage pipeline.
160    pub fn to_ocla_usage_record(
161        &self,
162    ) -> crate::core::ocla::OclaResult<Option<crate::core::ocla::UsageRecord>> {
163        use crate::core::ocla::{OclaError, UsageRecord};
164
165        let Some(context) = self
166            .wire
167            .as_deref()
168            .and_then(WireContext::ocla_request_context)
169            .cloned()
170        else {
171            return Ok(None);
172        };
173        context.validate()?;
174        if self.model.trim().is_empty() {
175            return Err(OclaError::InvalidRequest("model is required".into()));
176        }
177        let input_tokens = self
178            .input_tokens
179            .checked_add(self.cache_read_tokens)
180            .and_then(|value| value.checked_add(self.cache_write_tokens))
181            .ok_or_else(|| OclaError::InvalidRequest("input token total overflow".into()))?;
182        let provider_billed_tokens = input_tokens
183            .checked_add(self.output_tokens)
184            .ok_or_else(|| OclaError::InvalidRequest("billed token total overflow".into()))?;
185
186        Ok(Some(UsageRecord {
187            context,
188            model: self.model.clone(),
189            input_tokens,
190            output_tokens: self.output_tokens,
191            provider_billed_tokens,
192        }))
193    }
194
195    /// True once any model, token or measured-cost field has been observed —
196    /// the gate for recording. Avoids emitting empty rows for streams that
197    /// never reported usage.
198    fn is_meaningful(&self) -> bool {
199        !self.model.is_empty()
200            || self.input_tokens > 0
201            || self.output_tokens > 0
202            || self.cache_read_tokens > 0
203            || self.cache_write_tokens > 0
204            || self.provider_cost_usd.is_some()
205    }
206}
207
208/// Upper bound on a single buffered line before we give up on it. Usage events
209/// are tiny; this only guards against a pathological newline-free stream.
210const MAX_LINE_BYTES: usize = 1 << 20; // 1 MiB
211
212/// Incrementally extracts [`RealUsage`] from a response stream (or a full body).
213///
214/// `feed` is called with raw response chunks and keeps only the trailing partial
215/// line buffered (O(1) memory beyond one line); `finalize` returns the merged
216/// usage once the stream ends.
217pub struct Scanner {
218    provider: Provider,
219    /// Model parsed from the request URL (Gemini puts it there, not in the body).
220    url_model: Option<String>,
221    /// Holdout arms (#895, #1905), stamped onto the usage at finalize.
222    cohort: super::holdout::Cohorts,
223    /// Request-side gateway context (enterprise#11/#18), stamped at finalize.
224    wire: Option<Box<WireContext>>,
225    /// Billed USD from a gateway response header (#1189), stamped at finalize
226    /// unless the body already reported the charge.
227    header_cost: Option<f64>,
228    buf: Vec<u8>,
229    usage: RealUsage,
230    terminal_usage_seen: bool,
231    anthropic_final_usage_seen: bool,
232    response_clock: Option<(std::time::Instant, u16)>,
233    stream_failed: bool,
234}
235
236impl Scanner {
237    pub fn new(provider: Provider, url_model: Option<String>) -> Self {
238        Self {
239            provider,
240            url_model,
241            cohort: super::holdout::Cohorts::default(),
242            wire: None,
243            header_cost: None,
244            buf: Vec::new(),
245            usage: RealUsage::default(),
246            terminal_usage_seen: false,
247            anthropic_final_usage_seen: false,
248            response_clock: None,
249            stream_failed: false,
250        }
251    }
252
253    /// Starts measurement at the caller's actual upstream dispatch boundary.
254    #[must_use]
255    #[cfg(feature = "http-server")]
256    pub(crate) fn with_response_clock(
257        mut self,
258        started: Option<std::time::Instant>,
259        status: u16,
260    ) -> Self {
261        self.response_clock = started.map(|started| (started, status));
262        self
263    }
264
265    pub(super) fn mark_stream_error(&mut self) {
266        self.stream_failed = true;
267    }
268
269    /// Tags the usage this scanner produces with its output and compression holdout arms.
270    #[must_use]
271    pub fn with_cohort(mut self, cohort: super::holdout::Cohorts) -> Self {
272        self.cohort = cohort;
273        self
274    }
275
276    /// Attaches the request-side gateway context (identity tags, wire savings,
277    /// baseline inputs — enterprise#11/#17/#18) stamped onto the usage record.
278    #[must_use]
279    pub fn with_wire_context(mut self, wire: Option<Box<WireContext>>) -> Self {
280        self.wire = wire;
281        self
282    }
283
284    /// Attaches a billed USD figure reported by the upstream via a response
285    /// header (LiteLLM `x-litellm-response-cost`, or the operator-configured
286    /// `[proxy] cost_response_header`, #1189). Applied at finalize only when
287    /// the body did not already carry a measured cost — a body figure
288    /// (OpenRouter `usage.cost`) is the bill itself and always wins.
289    #[must_use]
290    pub fn with_header_cost(mut self, cost: Option<f64>) -> Self {
291        self.header_cost = cost.filter(|c| c.is_finite() && *c >= 0.0);
292        self
293    }
294
295    /// Feeds a raw streaming chunk, scanning every complete line it completes.
296    pub fn feed(&mut self, chunk: &[u8]) {
297        self.buf.extend_from_slice(chunk);
298        while let Some(nl) = self.buf.iter().position(|&b| b == b'\n') {
299            let mut line: Vec<u8> = self.buf.drain(..=nl).collect();
300            line.pop(); // drop '\n'
301            if line.last() == Some(&b'\r') {
302                line.pop();
303            }
304            self.scan_line(&line);
305        }
306        if self.buf.len() > MAX_LINE_BYTES {
307            self.buf.clear();
308        }
309    }
310
311    /// Feeds a complete non-streaming JSON response body.
312    pub fn feed_body(&mut self, body: &[u8]) {
313        if let Ok(v) = serde_json::from_slice::<Value>(body) {
314            self.absorb(&v);
315        }
316    }
317
318    /// A provider terminal measurement is independent of later transport EOF.
319    pub(super) fn has_terminal_usage(&self) -> bool {
320        self.terminal_usage_seen && (self.usage.is_meaningful() || self.header_cost.is_some())
321    }
322
323    /// Retain only an observed terminal measurement on an interrupted stream.
324    pub(super) fn finalize_terminal(self) -> Option<RealUsage> {
325        if self.has_terminal_usage() {
326            self.finalize_at(UsageBoundary::ProviderTerminalUsage)
327        } else {
328            None
329        }
330    }
331
332    /// Consumes the scanner, flushing any trailing partial line (a final event
333    /// may arrive without a newline) and returning the merged usage if any.
334    pub fn finalize(self) -> Option<RealUsage> {
335        self.finalize_at(UsageBoundary::StreamEnd)
336    }
337
338    pub(crate) fn finalize_at(mut self, boundary: UsageBoundary) -> Option<RealUsage> {
339        if !self.buf.is_empty() {
340            let line = std::mem::take(&mut self.buf);
341            self.scan_line(&line);
342        }
343        // Gateway header cost (#1189): measured, but the body figure is the
344        // bill itself (OpenRouter usage.cost) and keeps priority when present.
345        if self.usage.provider_cost_usd.is_none() {
346            self.usage.provider_cost_usd = self.header_cost;
347        }
348        if self.usage.is_meaningful() {
349            self.usage.cohort = self.cohort;
350            self.usage.wire = self.wire;
351            self.usage.response_observation =
352                self.response_clock
353                    .map(|(started, status)| ResponseObservation {
354                        schema_version: 1,
355                        http_status: status,
356                        usage_observed_ms: u64::try_from(started.elapsed().as_millis())
357                            .unwrap_or(u64::MAX),
358                        boundary: if self.stream_failed {
359                            UsageBoundary::StreamError
360                        } else {
361                            boundary
362                        },
363                        provider_cost_usd: self.usage.provider_cost_usd,
364                    });
365            Some(self.usage)
366        } else {
367            None
368        }
369    }
370
371    fn scan_line(&mut self, line: &[u8]) {
372        let Ok(text) = std::str::from_utf8(line) else {
373            return;
374        };
375        let trimmed = text.trim();
376        if trimmed.is_empty() {
377            return;
378        }
379        // Cheap pre-filter: skip the bulk of the stream (content deltas) and only
380        // JSON-parse lines that can carry usage or the model name.
381        if !self.line_might_be_relevant(trimmed) {
382            return;
383        }
384        let json_str = if let Some(rest) = trimmed.strip_prefix("data:") {
385            // SSE (Anthropic, OpenAI, Gemini with alt=sse).
386            let r = rest.trim();
387            if r.is_empty() || r == "[DONE]" {
388                return;
389            }
390            r
391        } else if trimmed.starts_with('{') {
392            // NDJSON / array-element line (Gemini x-ndjson). Tolerate the array
393            // punctuation a streamed JSON array puts around an element.
394            trimmed
395                .trim_start_matches([',', '['])
396                .trim_end_matches([',', ']'])
397                .trim()
398        } else {
399            return;
400        };
401        if let Ok(v) = serde_json::from_str::<Value>(json_str) {
402            self.absorb(&v);
403        }
404    }
405
406    fn line_might_be_relevant(&self, s: &str) -> bool {
407        match self.provider {
408            // Anthropic `message_start`/`message_delta` and OpenAI `usage`/
409            // `response.*` events all contain the substring "usage".
410            Provider::Anthropic => s.contains("usage") || s.contains("message_stop"),
411            Provider::OpenAi => s.contains("usage"),
412            Provider::Gemini => s.contains("usageMetadata"),
413        }
414    }
415
416    fn absorb(&mut self, v: &Value) {
417        match self.provider {
418            Provider::Anthropic => absorb_anthropic(&mut self.usage, v),
419            Provider::OpenAi => absorb_openai(&mut self.usage, v),
420            Provider::Gemini => absorb_gemini(&mut self.usage, v, self.url_model.as_deref()),
421        }
422        match self.provider {
423            Provider::Anthropic => {
424                if v.get("type").and_then(Value::as_str) == Some("message_delta")
425                    && v.pointer("/usage/output_tokens")
426                        .and_then(Value::as_u64)
427                        .is_some()
428                {
429                    self.anthropic_final_usage_seen = true;
430                }
431                self.terminal_usage_seen |= self.anthropic_final_usage_seen
432                    && v.get("type").and_then(Value::as_str) == Some("message_stop");
433            }
434            Provider::OpenAi => {
435                let response_terminal = matches!(
436                    v.get("type").and_then(Value::as_str),
437                    Some("response.completed" | "response.incomplete" | "response.failed")
438                ) && has_reported_totals(
439                    v.pointer("/response/usage"),
440                    "input_tokens",
441                    "output_tokens",
442                );
443                let chat_terminal =
444                    has_reported_totals(v.get("usage"), "prompt_tokens", "completion_tokens")
445                        && v.get("choices")
446                            .and_then(Value::as_array)
447                            .is_some_and(Vec::is_empty);
448                self.terminal_usage_seen |= response_terminal || chat_terminal;
449            }
450            // finishReason is per candidate, not proof that the entire request
451            // has finished. Preserve EOF accounting without inventing a terminal.
452            Provider::Gemini => {}
453        }
454    }
455}
456
457fn has_reported_totals(usage: Option<&Value>, input: &str, output: &str) -> bool {
458    usage.is_some_and(|usage| {
459        (usage.get(input).and_then(Value::as_u64).is_some()
460            && usage.get(output).and_then(Value::as_u64).is_some())
461            || usage
462                .get("cost")
463                .and_then(Value::as_f64)
464                .is_some_and(|cost| cost.is_finite() && cost >= 0.0)
465    })
466}
467
468/// Anthropic: model + input/cache live on `message` (streaming `message_start`
469/// or a non-streaming body); `output_tokens` arrives later on the event-level
470/// `usage` of `message_delta`. Latest non-zero wins, so the cumulative final
471/// delta is authoritative.
472fn absorb_anthropic(u: &mut RealUsage, v: &Value) {
473    let msg = v.get("message").unwrap_or(v);
474    if let Some(model) = msg.get("model").and_then(Value::as_str)
475        && !model.is_empty()
476    {
477        u.model = model.to_string();
478    }
479    let Some(usage) = msg.get("usage").or_else(|| v.get("usage")) else {
480        return;
481    };
482    if let Some(n) = usage.get("input_tokens").and_then(Value::as_u64) {
483        u.input_tokens = n;
484    }
485    if let Some(n) = usage.get("cache_read_input_tokens").and_then(Value::as_u64) {
486        u.cache_read_tokens = n;
487    }
488    if let Some(n) = usage
489        .get("cache_creation_input_tokens")
490        .and_then(Value::as_u64)
491    {
492        u.cache_write_tokens = n;
493    }
494    if let Some(n) = usage.get("output_tokens").and_then(Value::as_u64)
495        && n > 0
496    {
497        u.output_tokens = n;
498    }
499}
500
501/// OpenAI Chat Completions + Responses. `response.completed` nests the payload
502/// under `response`; chat chunks and non-streaming bodies are top-level. Both
503/// `usage` dialects are accepted (Responses: `input_tokens`/`output_tokens`;
504/// Chat: `prompt_tokens`/`completion_tokens`). `cached_tokens` is the cache-read
505/// portion of the reported input; OpenAI bills no separate cache write, but
506/// OpenRouter reports one (`prompt_tokens_details.cache_write_tokens`) for
507/// models with explicit cache-write pricing.
508///
509/// OpenRouter usage accounting additionally carries the money actually charged:
510/// `usage.cost` (credits ≡ USD) and, for BYOK requests, the upstream provider's
511/// own bill under `cost_details.upstream_inference_cost`. Their sum is this
512/// turn's real price — measured, not table-derived.
513fn absorb_openai(u: &mut RealUsage, v: &Value) {
514    let root = v.get("response").unwrap_or(v);
515    if let Some(model) = root.get("model").and_then(Value::as_str)
516        && !model.is_empty()
517    {
518        u.model = model.to_string();
519    }
520    let Some(usage) = root.get("usage") else {
521        return;
522    };
523    if usage.is_null() {
524        // `response.created` / `response.in_progress` carry `usage: null`.
525        return;
526    }
527
528    // Measured cost (OpenRouter dialect). Parsed before the token guard so a
529    // cost-bearing usage object is never lost, and `0` is preserved — a
530    // `:free` model's real price IS zero, not "unknown".
531    if let Some(cost) = usage.get("cost").and_then(Value::as_f64) {
532        let upstream = usage
533            .get("cost_details")
534            .and_then(|d| d.get("upstream_inference_cost"))
535            .and_then(Value::as_f64)
536            .unwrap_or(0.0);
537        // #746: non-BYOK responses may mirror `cost` in upstream_inference_cost;
538        // summing both would double-count. BYOK responses split the total:
539        // `cost` = OpenRouter fee (small), `upstream` = provider bill (large,
540        // always different from cost). Only add when genuinely distinct.
541        let byok_upstream = if upstream > 0.0 && upstream != cost {
542            upstream
543        } else {
544            0.0
545        };
546        u.provider_cost_usd = Some(cost + byok_upstream);
547    }
548
549    let total_input = usage
550        .get("input_tokens")
551        .or_else(|| usage.get("prompt_tokens"))
552        .and_then(Value::as_u64)
553        .unwrap_or(0);
554    let total_output = usage
555        .get("output_tokens")
556        .or_else(|| usage.get("completion_tokens"))
557        .and_then(Value::as_u64)
558        .unwrap_or(0);
559    let input_details = usage
560        .get("input_tokens_details")
561        .or_else(|| usage.get("prompt_tokens_details"));
562    let cached = input_details
563        .and_then(|d| d.get("cached_tokens"))
564        .and_then(Value::as_u64)
565        .unwrap_or(0);
566    let cache_write = input_details
567        .and_then(|d| d.get("cache_write_tokens"))
568        .and_then(Value::as_u64)
569        .unwrap_or(0);
570    let reasoning = usage
571        .get("output_tokens_details")
572        .or_else(|| usage.get("completion_tokens_details"))
573        .and_then(|d| d.get("reasoning_tokens"))
574        .and_then(Value::as_u64)
575        .unwrap_or(0);
576
577    if total_input == 0 && total_output == 0 {
578        return;
579    }
580    // OpenRouter counts cache writes inside prompt_tokens (unlike Anthropic's
581    // separate bucket) — subtract both cached reads and writes so the three
582    // buckets stay disjoint and are never double-priced.
583    u.input_tokens = total_input
584        .saturating_sub(cached)
585        .saturating_sub(cache_write);
586    u.cache_read_tokens = cached;
587    u.cache_write_tokens = cache_write;
588    u.output_tokens = total_output;
589    u.reasoning_tokens = reasoning;
590}
591
592/// Gemini: `usageMetadata` carries the counts; `modelVersion` (or the request
593/// URL) the model. `thoughtsTokenCount` is billed at the output rate and is not
594/// part of `candidatesTokenCount`, so it is added into `output_tokens`.
595fn absorb_gemini(u: &mut RealUsage, v: &Value, url_model: Option<&str>) {
596    if let Some(mv) = v.get("modelVersion").and_then(Value::as_str)
597        && !mv.is_empty()
598    {
599        u.model = mv.to_string();
600    } else if u.model.is_empty()
601        && let Some(m) = url_model
602        && !m.is_empty()
603    {
604        u.model = m.to_string();
605    }
606    let Some(um) = v.get("usageMetadata") else {
607        return;
608    };
609    let prompt = um
610        .get("promptTokenCount")
611        .and_then(Value::as_u64)
612        .unwrap_or(0);
613    let candidates = um
614        .get("candidatesTokenCount")
615        .and_then(Value::as_u64)
616        .unwrap_or(0);
617    let cached = um
618        .get("cachedContentTokenCount")
619        .and_then(Value::as_u64)
620        .unwrap_or(0);
621    let thoughts = um
622        .get("thoughtsTokenCount")
623        .and_then(Value::as_u64)
624        .unwrap_or(0);
625    if prompt == 0 && candidates == 0 && thoughts == 0 {
626        return;
627    }
628    u.input_tokens = prompt.saturating_sub(cached);
629    u.cache_read_tokens = cached;
630    u.cache_write_tokens = 0;
631    u.output_tokens = candidates + thoughts;
632    u.reasoning_tokens = thoughts;
633}
634
635/// Extracts the model from a Gemini request path
636/// (`/v1beta/models/{model}:generateContent`). Returns `None` for other paths.
637pub fn gemini_model_from_path(path: &str) -> Option<String> {
638    let after = path.rsplit_once("/models/").map(|(_, m)| m)?;
639    let model = after.split(':').next().unwrap_or(after).trim();
640    if model.is_empty() {
641        None
642    } else {
643        Some(model.to_string())
644    }
645}
646
647/// Wraps a response byte stream so every chunk is forwarded **byte-for-byte**
648/// while a [`Scanner`] observes it; on stream end the merged usage is recorded.
649/// Memory overhead is one buffered SSE line, never the whole response.
650pub fn tee_stream<S, B, E>(
651    inner: S,
652    scanner: Scanner,
653) -> impl Stream<Item = Result<B, E>> + Send + 'static
654where
655    S: Stream<Item = Result<B, E>> + Send + Unpin + 'static,
656    B: AsRef<[u8]> + Send + 'static,
657    E: Send + 'static,
658{
659    futures::stream::unfold(
660        (inner, Some(scanner)),
661        |(mut inner, mut scanner)| async move {
662            match inner.next().await {
663                Some(Ok(chunk)) => {
664                    if let Some(s) = scanner.as_mut() {
665                        s.feed(chunk.as_ref());
666                    }
667                    if scanner.as_ref().is_some_and(Scanner::has_terminal_usage)
668                        && let Some(usage) = scanner.take().and_then(Scanner::finalize_terminal)
669                    {
670                        super::usage_meter::record(&usage);
671                    }
672                    Some((Ok(chunk), (inner, scanner)))
673                }
674                Some(err) => {
675                    if let Some(mut s) = scanner.take() {
676                        s.mark_stream_error();
677                        if let Some(usage) = s.finalize_at(UsageBoundary::StreamError) {
678                            super::usage_meter::record(&usage);
679                        }
680                    }
681                    Some((err, (inner, scanner)))
682                }
683                None => {
684                    if let Some(s) = scanner.take()
685                        && let Some(usage) = s.finalize()
686                    {
687                        super::usage_meter::record(&usage);
688                    }
689                    None
690                }
691            }
692        },
693    )
694}
695
696#[cfg(test)]
697mod tests {
698    use super::*;
699
700    fn feed_lines(
701        provider: Provider,
702        url_model: Option<&str>,
703        lines: &[&str],
704    ) -> Option<RealUsage> {
705        let mut s = Scanner::new(provider, url_model.map(str::to_string));
706        for line in lines {
707            s.feed(line.as_bytes());
708            s.feed(b"\n");
709        }
710        s.finalize()
711    }
712
713    #[test]
714    fn anthropic_merges_message_start_and_delta() {
715        let u = feed_lines(
716            Provider::Anthropic,
717            None,
718            &[
719                r#"data: {"type":"message_start","message":{"model":"claude-opus-4-5-20251101","usage":{"input_tokens":100,"cache_read_input_tokens":2000,"cache_creation_input_tokens":50,"output_tokens":1}}}"#,
720                r#"data: {"type":"content_block_delta","index":0,"delta":{"text":"hello"}}"#,
721                r#"data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":73}}"#,
722                "data: {\"type\":\"message_stop\"}",
723            ],
724        )
725        .expect("usage");
726        assert_eq!(u.model, "claude-opus-4-5-20251101");
727        assert_eq!(u.input_tokens, 100);
728        assert_eq!(u.cache_read_tokens, 2000);
729        assert_eq!(u.cache_write_tokens, 50);
730        assert_eq!(u.output_tokens, 73);
731    }
732
733    #[test]
734    fn anthropic_non_streaming_body() {
735        let mut s = Scanner::new(Provider::Anthropic, None);
736        s.feed_body(
737            br#"{"model":"claude-sonnet-4-5","usage":{"input_tokens":24,"output_tokens":18,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}"#,
738        );
739        let u = s.finalize().expect("usage");
740        assert_eq!(u.model, "claude-sonnet-4-5");
741        assert_eq!(u.input_tokens, 24);
742        assert_eq!(u.output_tokens, 18);
743    }
744
745    #[test]
746    fn scanner_stamps_wire_context_onto_usage() {
747        // enterprise#11/#17: the request-side context must survive scanning and
748        // arrive on the finalized record that usage_meter/store consume.
749        let wire = Box::new(WireContext {
750            provider: "Anthropic".into(),
751            person: Some("yves".into()),
752            team: None,
753            project: Some("billing".into()),
754            project_key: None,
755            saved_tokens: 42,
756            uncompressed_input_tokens: 500,
757            is_local: false,
758            routed_from: None,
759            counterfactual: None,
760            lineage: None,
761        });
762        let mut s = Scanner::new(Provider::Anthropic, None).with_wire_context(Some(wire.clone()));
763        s.feed_body(
764            br#"{"model":"claude-sonnet-4-5","usage":{"input_tokens":24,"output_tokens":18}}"#,
765        );
766        let u = s.finalize().expect("usage");
767        assert_eq!(u.wire, Some(wire));
768    }
769
770    fn managed_context() -> crate::core::ocla::OclaRequestContext {
771        crate::core::ocla::OclaRequestContext {
772            request_id: "req-1".into(),
773            session_id: "session-1".into(),
774            agent_id: "agent-1".into(),
775            content_ref: "blake3:abc".into(),
776            tenant_id: None,
777            trace_id: "tr-unit".into(),
778            task_id: None,
779            parent_task_id: None,
780        }
781    }
782
783    #[test]
784    fn ocla_projection_includes_cache_tokens_once() {
785        let usage = RealUsage {
786            model: "gpt-5".into(),
787            input_tokens: 100,
788            output_tokens: 40,
789            cache_read_tokens: 20,
790            cache_write_tokens: 5,
791            wire: Some(Box::new(WireContext {
792                lineage: Some(managed_context()),
793                ..Default::default()
794            })),
795            ..Default::default()
796        };
797        let record = usage
798            .to_ocla_usage_record()
799            .expect("valid projection")
800            .expect("managed record");
801        assert_eq!(record.input_tokens, 125);
802        assert_eq!(record.output_tokens, 40);
803        assert_eq!(record.provider_billed_tokens, 165);
804        assert_eq!(record.context, managed_context());
805    }
806
807    #[test]
808    fn ocla_projection_keeps_missing_lineage_unmanaged() {
809        let usage = RealUsage {
810            model: "gpt-5".into(),
811            input_tokens: 1,
812            ..Default::default()
813        };
814        assert_eq!(usage.to_ocla_usage_record().unwrap(), None);
815    }
816
817    #[test]
818    fn ocla_projection_fails_closed_on_overflow_or_invalid_context() {
819        let overflow = RealUsage {
820            model: "gpt-5".into(),
821            input_tokens: u64::MAX,
822            cache_read_tokens: 1,
823            wire: Some(Box::new(WireContext {
824                lineage: Some(managed_context()),
825                ..Default::default()
826            })),
827            ..Default::default()
828        };
829        assert!(overflow.to_ocla_usage_record().is_err());
830
831        let mut invalid = managed_context();
832        invalid.request_id.clear();
833        let invalid = RealUsage {
834            model: "gpt-5".into(),
835            wire: Some(Box::new(WireContext {
836                lineage: Some(invalid),
837                ..Default::default()
838            })),
839            ..Default::default()
840        };
841        assert!(invalid.to_ocla_usage_record().is_err());
842    }
843
844    #[test]
845    fn openai_responses_completed_event() {
846        let u = feed_lines(
847            Provider::OpenAi,
848            None,
849            &[
850                r#"data: {"type":"response.created","response":{"model":"gpt-5.4","usage":null}}"#,
851                r#"data: {"type":"response.completed","response":{"model":"gpt-5.4","usage":{"input_tokens":1289,"input_tokens_details":{"cached_tokens":289},"output_tokens":685,"output_tokens_details":{"reasoning_tokens":640},"total_tokens":1974}}}"#,
852            ],
853        )
854        .expect("usage");
855        assert_eq!(u.model, "gpt-5.4");
856        assert_eq!(u.input_tokens, 1000); // 1289 - 289 cached
857        assert_eq!(u.cache_read_tokens, 289);
858        assert_eq!(u.output_tokens, 685);
859        assert_eq!(u.reasoning_tokens, 640);
860    }
861
862    #[test]
863    fn openai_chat_final_usage_chunk() {
864        let u = feed_lines(
865            Provider::OpenAi,
866            None,
867            &[
868                r#"data: {"choices":[{"delta":{"content":"hi"}}],"model":"gpt-5.4-mini"}"#,
869                r#"data: {"choices":[],"model":"gpt-5.4-mini","usage":{"prompt_tokens":500,"prompt_tokens_details":{"cached_tokens":100},"completion_tokens":40,"total_tokens":540}}"#,
870                "data: [DONE]",
871            ],
872        )
873        .expect("usage");
874        assert_eq!(u.model, "gpt-5.4-mini");
875        assert_eq!(u.input_tokens, 400);
876        assert_eq!(u.cache_read_tokens, 100);
877        assert_eq!(u.output_tokens, 40);
878        assert_eq!(u.provider_cost_usd, None, "OpenAI reports no usage.cost");
879    }
880
881    #[test]
882    fn openrouter_cost_and_cache_writes_are_measured() {
883        // #1179: OpenRouter usage accounting — the final streamed chunk carries
884        // the billed USD (`cost`) and the cache-write bucket inside
885        // prompt_tokens_details. All three token buckets must stay disjoint.
886        let u = feed_lines(
887            Provider::OpenAi,
888            None,
889            &[
890                r#"data: {"choices":[{"delta":{"content":"hi"}}],"model":"deepseek/deepseek-v4-flash-20260423"}"#,
891                r#"data: {"choices":[],"model":"deepseek/deepseek-v4-flash-20260423","usage":{"prompt_tokens":700,"prompt_tokens_details":{"cached_tokens":150,"cache_write_tokens":50},"completion_tokens":40,"cost":0.0123,"cost_details":{"upstream_inference_cost":null},"total_tokens":740}}"#,
892                "data: [DONE]",
893            ],
894        )
895        .expect("usage");
896        assert_eq!(u.input_tokens, 500, "700 - 150 cached - 50 cache-write");
897        assert_eq!(u.cache_read_tokens, 150);
898        assert_eq!(u.cache_write_tokens, 50);
899        assert_eq!(u.output_tokens, 40);
900        let cost = u.provider_cost_usd.expect("measured cost");
901        assert!((cost - 0.0123).abs() < 1e-12);
902    }
903
904    #[test]
905    fn openrouter_byok_adds_upstream_inference_cost() {
906        let mut s = Scanner::new(Provider::OpenAi, None);
907        s.feed_body(
908            br#"{"model":"anthropic/claude-sonnet-5","usage":{"prompt_tokens":100,"completion_tokens":10,"cost":0.05,"cost_details":{"upstream_inference_cost":0.95}}}"#,
909        );
910        let u = s.finalize().expect("usage");
911        let cost = u.provider_cost_usd.expect("measured cost");
912        assert!(
913            (cost - 1.0).abs() < 1e-12,
914            "OpenRouter fee + BYOK upstream bill"
915        );
916    }
917
918    /// #746: non-BYOK responses mirror `cost` in `upstream_inference_cost`.
919    /// The gateway must not sum both — that would double-count.
920    #[test]
921    fn non_byok_upstream_equal_to_cost_is_not_doubled() {
922        let mut s = Scanner::new(Provider::OpenAi, None);
923        s.feed_body(
924            br#"{"model":"deepseek/deepseek-v4-flash","usage":{"prompt_tokens":50,"completion_tokens":5,"cost":0.000001568,"cost_details":{"upstream_inference_cost":0.000001568}}}"#,
925        );
926        let u = s.finalize().expect("usage");
927        let cost = u.provider_cost_usd.expect("measured cost");
928        assert!(
929            (cost - 0.000001568).abs() < 1e-15,
930            "#746: must book cost once, not 2x; got {cost}"
931        );
932    }
933
934    #[test]
935    fn gateway_header_cost_fills_when_body_has_none() {
936        // #1189: a LiteLLM-style gateway reports the bill in a header; tokens
937        // come from a normal OpenAI-shaped body without `usage.cost`.
938        let mut s = Scanner::new(Provider::OpenAi, None).with_header_cost(Some(0.0042));
939        s.feed_body(
940            br#"{"model":"azure-gpt-4o","usage":{"prompt_tokens":100,"completion_tokens":10}}"#,
941        );
942        let u = s.finalize().expect("usage");
943        assert_eq!(u.provider_cost_usd, Some(0.0042), "header is measured");
944    }
945
946    #[test]
947    fn body_reported_cost_beats_the_header_figure() {
948        // OpenRouter behind another gateway: `usage.cost` is the bill itself.
949        let mut s = Scanner::new(Provider::OpenAi, None).with_header_cost(Some(9.99));
950        s.feed_body(
951            br#"{"model":"deepseek/deepseek-v4-flash","usage":{"prompt_tokens":100,"completion_tokens":10,"cost":0.05}}"#,
952        );
953        let u = s.finalize().expect("usage");
954        assert_eq!(u.provider_cost_usd, Some(0.05), "body wins over header");
955    }
956
957    #[test]
958    fn openrouter_free_model_reports_zero_cost_as_measured() {
959        let mut s = Scanner::new(Provider::OpenAi, None);
960        s.feed_body(
961            br#"{"model":"poolside/laguna-xs-2.1:free","usage":{"prompt_tokens":80,"completion_tokens":20,"cost":0}}"#,
962        );
963        let u = s.finalize().expect("usage");
964        assert_eq!(u.provider_cost_usd, Some(0.0), "free is a price, not a gap");
965    }
966
967    #[test]
968    fn gemini_usage_metadata_with_url_model() {
969        let u = feed_lines(
970            Provider::Gemini,
971            Some("gemini-2.5-pro"),
972            &[
973                r#"data: {"candidates":[{"content":{"parts":[{"text":"hi"}]}}],"usageMetadata":{"promptTokenCount":25,"candidatesTokenCount":7,"thoughtsTokenCount":39,"totalTokenCount":71}}"#,
974            ],
975        )
976        .expect("usage");
977        assert_eq!(u.model, "gemini-2.5-pro");
978        assert_eq!(u.input_tokens, 25);
979        assert_eq!(u.output_tokens, 46); // candidates 7 + thoughts 39
980        assert_eq!(u.reasoning_tokens, 39);
981    }
982
983    #[test]
984    fn gemini_prefers_model_version_over_url() {
985        let u = feed_lines(
986            Provider::Gemini,
987            Some("gemini-2.5-pro"),
988            &[
989                r#"data: {"modelVersion":"gemini-2.5-pro-002","usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5,"cachedContentTokenCount":4,"totalTokenCount":15}}"#,
990            ],
991        )
992        .expect("usage");
993        assert_eq!(u.model, "gemini-2.5-pro-002");
994        assert_eq!(u.input_tokens, 6); // 10 - 4 cached
995        assert_eq!(u.cache_read_tokens, 4);
996        assert_eq!(u.output_tokens, 5);
997    }
998
999    #[test]
1000    fn split_chunks_reassemble_across_feed_calls() {
1001        let mut s = Scanner::new(Provider::Anthropic, None);
1002        let line = r#"data: {"type":"message_delta","delta":{},"usage":{"output_tokens":42}}"#;
1003        let bytes = format!("{line}\n");
1004        let (a, b) = bytes.as_bytes().split_at(20);
1005        s.feed(a);
1006        s.feed(b);
1007        let u = s.finalize().expect("usage");
1008        assert_eq!(u.output_tokens, 42);
1009    }
1010
1011    #[test]
1012    fn no_usage_yields_none() {
1013        let out = feed_lines(
1014            Provider::OpenAi,
1015            None,
1016            &[r#"data: {"choices":[{"delta":{"content":"hi"}}],"model":"gpt-5.4"}"#],
1017        );
1018        assert!(out.is_none(), "content-only stream reports no usage");
1019    }
1020
1021    #[test]
1022    fn final_event_without_trailing_newline() {
1023        let mut s = Scanner::new(Provider::Anthropic, None);
1024        s.feed(br#"data: {"type":"message_delta","delta":{},"usage":{"output_tokens":7}}"#);
1025        let u = s.finalize().expect("flushes trailing partial line");
1026        assert_eq!(u.output_tokens, 7);
1027    }
1028
1029    #[test]
1030    fn gemini_model_from_path_extracts() {
1031        assert_eq!(
1032            gemini_model_from_path("/v1beta/models/gemini-2.5-pro:streamGenerateContent")
1033                .as_deref(),
1034            Some("gemini-2.5-pro")
1035        );
1036        assert_eq!(
1037            gemini_model_from_path("/v1beta/models/gemini-2.5-flash:generateContent").as_deref(),
1038            Some("gemini-2.5-flash")
1039        );
1040        assert_eq!(gemini_model_from_path("/v1/chat/completions"), None);
1041    }
1042
1043    #[test]
1044    fn terminal_usage_requires_provider_completion_and_reported_totals() {
1045        for kind in [
1046            "response.completed",
1047            "response.incomplete",
1048            "response.failed",
1049        ] {
1050            let mut scanner = Scanner::new(Provider::OpenAi, None);
1051            scanner.feed_body(serde_json::json!({
1052                "type": kind,
1053                "response": {"model": "terminal", "usage": {"input_tokens": 5, "output_tokens": 2}}
1054            }).to_string().as_bytes());
1055            assert!(scanner.has_terminal_usage());
1056        }
1057        for (provider, event) in [
1058            (
1059                Provider::OpenAi,
1060                serde_json::json!({"type":"response.in_progress","response":{"usage":{"input_tokens":5,"output_tokens":2}}}),
1061            ),
1062            (
1063                Provider::OpenAi,
1064                serde_json::json!({"type":"response.completed","response":{"usage":{"input_tokens":5}}}),
1065            ),
1066            (
1067                Provider::OpenAi,
1068                serde_json::json!({"choices":[],"usage":null}),
1069            ),
1070            (
1071                Provider::Gemini,
1072                serde_json::json!({"candidates":[{"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":2}}),
1073            ),
1074        ] {
1075            let mut scanner = Scanner::new(provider, None);
1076            scanner.feed_body(event.to_string().as_bytes());
1077            assert!(!scanner.has_terminal_usage());
1078        }
1079        let mut chat = Scanner::new(Provider::OpenAi, None);
1080        chat.feed_body(
1081            br#"{"model":"chat","choices":[],"usage":{"prompt_tokens":5,"completion_tokens":2}}"#,
1082        );
1083        assert!(chat.has_terminal_usage());
1084        let mut anthropic = Scanner::new(Provider::Anthropic, None);
1085        anthropic.feed(b"data: {\"type\":\"message_start\",\"message\":{\"model\":\"anthropic\",\"usage\":{\"input_tokens\":5,\"output_tokens\":1}}}\n");
1086        anthropic.feed(b"data: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":2}}\n");
1087        assert!(!anthropic.has_terminal_usage());
1088        anthropic.feed(b"data: {\"type\":\"message_stop\"}\n");
1089        assert!(anthropic.has_terminal_usage());
1090    }
1091
1092    fn terminal_usage_frame(model: &str) -> Vec<u8> {
1093        format!(
1094            "data: {}\n\n",
1095            serde_json::json!({
1096                "type": "response.completed",
1097                "response": {
1098                    "model": model,
1099                    "usage": {
1100                        "input_tokens": 120,
1101                        "output_tokens": 7,
1102                        "input_tokens_details": {"cached_tokens": 20},
1103                        "cost": 0.0125
1104                    }
1105                }
1106            })
1107        )
1108        .into_bytes()
1109    }
1110
1111    fn measured_requests(model: &str) -> u64 {
1112        super::super::usage_meter::snapshot()
1113            .into_iter()
1114            .find(|usage| usage.model == model)
1115            .map_or(0, |usage| usage.requests)
1116    }
1117
1118    #[tokio::test]
1119    async fn terminal_usage_clean_eof_records_once() {
1120        let _isolation = crate::core::data_dir::isolated_data_dir();
1121        let model = "terminal-evidence-clean-eof";
1122        let before = measured_requests(model);
1123        let frame = terminal_usage_frame(model);
1124        let source = futures::stream::iter(vec![Ok::<_, ()>(frame.clone())]);
1125        let mut teed = Box::pin(tee_stream(source, Scanner::new(Provider::OpenAi, None)));
1126        assert_eq!(teed.next().await, Some(Ok(frame)));
1127        assert_eq!(teed.next().await, None);
1128        drop(teed);
1129        assert_eq!(measured_requests(model), before + 1);
1130    }
1131
1132    #[tokio::test]
1133    async fn terminal_usage_received_before_drop_is_recorded_once() {
1134        let _isolation = crate::core::data_dir::isolated_data_dir();
1135        let model = "terminal-evidence-client-drop";
1136        let before = measured_requests(model);
1137        let frame = terminal_usage_frame(model);
1138        let source = futures::stream::iter(vec![Ok::<_, ()>(frame.clone())]);
1139        let mut teed = Box::pin(tee_stream(source, Scanner::new(Provider::OpenAi, None)));
1140        assert_eq!(teed.next().await, Some(Ok(frame)));
1141        drop(teed);
1142        assert_eq!(measured_requests(model), before + 1);
1143    }
1144
1145    #[tokio::test]
1146    async fn terminal_usage_received_before_error_is_recorded_once() {
1147        let _isolation = crate::core::data_dir::isolated_data_dir();
1148        let model = "terminal-evidence-upstream-error";
1149        let before = measured_requests(model);
1150        let frame = terminal_usage_frame(model);
1151        let source = futures::stream::iter(vec![Ok(frame.clone()), Err(())]);
1152        let mut teed = Box::pin(tee_stream(source, Scanner::new(Provider::OpenAi, None)));
1153        assert_eq!(teed.next().await, Some(Ok(frame)));
1154        assert_eq!(teed.next().await, Some(Err(())));
1155        drop(teed);
1156        assert_eq!(measured_requests(model), before + 1);
1157    }
1158
1159    #[tokio::test]
1160    async fn terminal_usage_retains_header_cost_without_model_or_body_tokens() {
1161        let _isolation = crate::core::data_dir::isolated_data_dir();
1162        let before = super::super::usage_meter::snapshot()
1163            .into_iter()
1164            .find(|usage| usage.model == "unknown");
1165        let before_requests = before.as_ref().map_or(0, |usage| usage.requests);
1166        let before_cost = before.as_ref().map_or(0.0, |usage| usage.cost_usd);
1167        let frame = b"data: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":0,\"output_tokens\":0}}}\n".to_vec();
1168        let source = futures::stream::iter(vec![Ok::<_, ()>(frame.clone())]);
1169        let scanner = Scanner::new(Provider::OpenAi, None).with_header_cost(Some(0.0042));
1170        let mut teed = Box::pin(tee_stream(source, scanner));
1171        assert_eq!(teed.next().await, Some(Ok(frame)));
1172        drop(teed);
1173        let measured = super::super::usage_meter::snapshot()
1174            .into_iter()
1175            .find(|usage| usage.model == "unknown")
1176            .unwrap();
1177        assert_eq!(measured.requests, before_requests + 1);
1178        assert!((measured.cost_usd - before_cost - 0.0042).abs() < 1e-9);
1179    }
1180
1181    #[tokio::test]
1182    async fn terminal_usage_partial_input_does_not_become_completed_spend_on_drop() {
1183        let _isolation = crate::core::data_dir::isolated_data_dir();
1184        let model = "terminal-evidence-partial-input";
1185        let before = measured_requests(model);
1186        let frame = format!(
1187            "data: {}\n\n",
1188            serde_json::json!({
1189                "type": "message_start",
1190                "message": {
1191                    "model": model,
1192                    "usage": {"input_tokens": 5, "output_tokens": 1}
1193                }
1194            })
1195        )
1196        .into_bytes();
1197        let source = futures::stream::iter(vec![Ok::<_, ()>(frame.clone())]);
1198        let mut teed = Box::pin(tee_stream(source, Scanner::new(Provider::Anthropic, None)));
1199        assert_eq!(teed.next().await, Some(Ok(frame)));
1200        drop(teed);
1201        assert_eq!(measured_requests(model), before);
1202    }
1203
1204    #[tokio::test]
1205    async fn tee_stream_passes_bytes_through_and_records() {
1206        let chunks: Vec<Result<Vec<u8>, std::convert::Infallible>> = vec![
1207            Ok(b"data: {\"type\":\"message_start\",\"message\":{\"model\":\"claude-haiku-4.5\",\"usage\":{\"input_tokens\":5,\"output_tokens\":1}}}\n".to_vec()),
1208            Ok(b"data: {\"type\":\"message_delta\",\"delta\":{},\"usage\":{\"output_tokens\":9}}\n".to_vec()),
1209        ];
1210        let inner = futures::stream::iter(chunks);
1211        let scanner = Scanner::new(Provider::Anthropic, None);
1212        let teed = tee_stream(inner, scanner);
1213        let collected: Vec<_> = teed.collect().await;
1214        // Byte-for-byte passthrough preserved.
1215        assert_eq!(collected.len(), 2);
1216        assert!(collected.iter().all(std::result::Result::is_ok));
1217    }
1218}