Skip to content

Commit c55aa0c

Browse files
unhappychoiceclaude
andcommitted
refactor(fetcher/codex_usage): use shared llm_pricing helper
Drops the per-family hardcoded `PRICE_TABLE` / `cost_usd` / `Price` from `codex/common.rs` and threads the shared `llm_pricing::PriceMap` through `build_snapshot` / `group_rows` / `UsageEvent::cost` instead. The pricing map is fetched once per `fetch()` call (which the daemon's 5-minute disk cache already throttles); cost math is identical for known models because the embedded floor mirrors the original hardcoded values. Module doc updated to reflect that the fetcher now makes one host-fixed HTTP GET for prices alongside its local JSONL reads. Safety::Safe class holds (host hardcoded; no token leaves the process). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent ad0978a commit c55aa0c

2 files changed

Lines changed: 45 additions & 163 deletions

File tree

‎src/fetcher/codex/common.rs‎

Lines changed: 4 additions & 147 deletions
Original file line numberDiff line numberDiff line change
@@ -1,107 +1,12 @@
1-
//! Shared helpers for the `codex_*` family — model pricing, cost math, and the date-tree
2-
//! discovery used by `codex_usage` and `codex_subscription`.
1+
//! Shared helpers for the `codex_*` family — formatting helpers, JSONL session discovery,
2+
//! and the small label-normalising bits used by `codex_usage` and `codex_subscription`.
33
//!
4-
//! Pricing lives in source rather than a vendored file because the OpenAI model surface is
5-
//! small enough to track by hand; bumping a constant is less error-prone than parsing an
6-
//! external table on every fetch. When a new family ships, add a [`PRICE_TABLE`] row matching
7-
//! the model-id prefix.
4+
//! Pricing has moved to the shared [`crate::fetcher::llm_pricing`] module so codex and
5+
//! claude consume the same snapshot. See its module doc for the fetch / fallback story.
86
97
use std::fs;
108
use std::path::PathBuf;
119

12-
/// USD per million tokens for a single OpenAI model family. `cached_input` covers the prompt
13-
/// cache discount (Codex CLI's `cached_input_tokens` lands here, billed at the discounted rate
14-
/// instead of the full `input` rate). Reasoning output is billed at the same rate as regular
15-
/// output today, so it folds into [`Price::output`].
16-
#[derive(Debug, Clone, Copy)]
17-
pub struct Price {
18-
pub input: f64,
19-
pub cached_input: f64,
20-
pub output: f64,
21-
}
22-
23-
const GPT_5: Price = Price {
24-
input: 1.25,
25-
cached_input: 0.125,
26-
output: 10.0,
27-
};
28-
29-
const GPT_5_MINI: Price = Price {
30-
input: 0.25,
31-
cached_input: 0.025,
32-
output: 2.0,
33-
};
34-
35-
const GPT_5_NANO: Price = Price {
36-
input: 0.05,
37-
cached_input: 0.005,
38-
output: 0.40,
39-
};
40-
41-
const GPT_4_1: Price = Price {
42-
input: 2.0,
43-
cached_input: 0.50,
44-
output: 8.0,
45-
};
46-
47-
const GPT_4_1_MINI: Price = Price {
48-
input: 0.40,
49-
cached_input: 0.10,
50-
output: 1.60,
51-
};
52-
53-
const O3: Price = Price {
54-
input: 2.0,
55-
cached_input: 0.50,
56-
output: 8.0,
57-
};
58-
59-
const O4_MINI: Price = Price {
60-
input: 1.10,
61-
cached_input: 0.275,
62-
output: 4.40,
63-
};
64-
65-
/// Prefix table — longest-prefix entries come first so `gpt-5-mini` doesn't get swallowed by
66-
/// `gpt-5`. Match is on the full lowercased model id.
67-
const PRICE_TABLE: &[(&str, Price)] = &[
68-
("gpt-5-nano", GPT_5_NANO),
69-
("gpt-5-mini", GPT_5_MINI),
70-
("gpt-5", GPT_5),
71-
("gpt-4.1-mini", GPT_4_1_MINI),
72-
("gpt-4.1", GPT_4_1),
73-
("o4-mini", O4_MINI),
74-
("o3", O3),
75-
];
76-
77-
pub fn price_for(model: &str) -> Option<Price> {
78-
let lower = model.to_lowercase();
79-
PRICE_TABLE
80-
.iter()
81-
.find(|(prefix, _)| lower.starts_with(prefix))
82-
.map(|(_, p)| *p)
83-
}
84-
85-
/// USD cost of a single turn given a model. Unknown models contribute 0 — surfacing them as
86-
/// "free" is friendlier than hiding the underlying token activity behind an error.
87-
pub fn cost_usd(
88-
model: &str,
89-
input_tokens: u64,
90-
cached_input_tokens: u64,
91-
output_tokens: u64,
92-
) -> f64 {
93-
let Some(p) = price_for(model) else {
94-
return 0.0;
95-
};
96-
let per_token = |rate_per_mt: f64, count: u64| (count as f64) * rate_per_mt / 1_000_000.0;
97-
// OpenAI reports `cached_input_tokens` as a subset of `input_tokens`; bill the cached chunk
98-
// at the discounted rate and the rest at the full input rate.
99-
let billable_input = input_tokens.saturating_sub(cached_input_tokens);
100-
per_token(p.input, billable_input)
101-
+ per_token(p.cached_input, cached_input_tokens)
102-
+ per_token(p.output, output_tokens)
103-
}
104-
10510
/// "$12.34" / "$0.05" / "$1.2k" — compact enough to fit a Badge or a Text headline.
10611
pub fn format_cost(usd: f64) -> String {
10712
if usd >= 1_000.0 {
@@ -215,54 +120,6 @@ fn strip_trailing_iso_date(s: &str) -> Option<String> {
215120
mod tests {
216121
use super::*;
217122

218-
#[test]
219-
fn price_for_matches_gpt_5_family_by_prefix() {
220-
assert!(price_for("gpt-5").is_some());
221-
assert!(price_for("gpt-5.5").is_some());
222-
assert!(price_for("gpt-5-mini").is_some());
223-
assert!(price_for("gpt-5-nano").is_some());
224-
assert!(price_for("o4-mini").is_some());
225-
}
226-
227-
#[test]
228-
fn price_for_unknown_model_returns_none() {
229-
assert!(price_for("claude-opus-4-7").is_none());
230-
assert!(price_for("").is_none());
231-
}
232-
233-
#[test]
234-
fn price_for_longer_prefix_wins_over_shorter() {
235-
// gpt-5-mini must resolve to GPT_5_MINI, not GPT_5 (it's listed before in PRICE_TABLE).
236-
let mini = price_for("gpt-5-mini").unwrap();
237-
assert!(
238-
(mini.input - 0.25).abs() < 1e-9,
239-
"expected gpt-5-mini rate, got {}",
240-
mini.input
241-
);
242-
}
243-
244-
#[test]
245-
fn cost_usd_zero_for_unknown_model_even_with_tokens() {
246-
assert_eq!(cost_usd("claude-opus-4-7", 1_000_000, 0, 1_000_000), 0.0);
247-
}
248-
249-
#[test]
250-
fn cost_usd_charges_cached_input_at_discounted_rate() {
251-
// gpt-5: 1M billable input @ $1.25 + 0M cached + 0M output = $1.25
252-
let full = cost_usd("gpt-5", 1_000_000, 0, 0);
253-
assert!((full - 1.25).abs() < 1e-9, "got {full}");
254-
// Same input but all cached → 1M @ $0.125 = $0.125
255-
let cached = cost_usd("gpt-5", 1_000_000, 1_000_000, 0);
256-
assert!((cached - 0.125).abs() < 1e-9, "got {cached}");
257-
}
258-
259-
#[test]
260-
fn cost_usd_splits_partial_cache_against_full_and_cached_rates() {
261-
// 1M input where 0.5M is cached → 0.5M @ $1.25 + 0.5M @ $0.125 = $0.625 + $0.0625 = $0.6875
262-
let c = cost_usd("gpt-5", 1_000_000, 500_000, 0);
263-
assert!((c - 0.6875).abs() < 1e-9, "got {c}");
264-
}
265-
266123
#[test]
267124
fn format_cost_picks_unit_by_magnitude() {
268125
assert_eq!(format_cost(0.0), "$0.00");

‎src/fetcher/codex/usage.rs‎

Lines changed: 41 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@
66
//! that precedes each turn carries the model id and `cwd`; we thread that state forward as
77
//! we parse so token_count events get attributed to the right turn.
88
//!
9-
//! `Safety::Safe` — every read is rooted at a `$HOME`-relative directory the user owns. No
10-
//! network, no token, no exec. Pricing is hardcoded in [`super::common`] so a stale price feed
11-
//! can't disrupt the fetch.
9+
//! `Safety::Safe` — every session read is rooted at a `$HOME`-relative directory the user
10+
//! owns. The fetcher *does* make a single HTTP GET for the LLM pricing snapshot (see
11+
//! [`crate::fetcher::llm_pricing`]) — the URL is hardcoded to splashboard's own GitHub repo,
12+
//! which keeps it under the host-fixed-URL Safe rule. On HTTP failure we fall back to the
13+
//! embedded floor so cost columns stay populated for the headline models.
1214
1315
use std::collections::HashMap;
1416
use std::fs;
@@ -20,10 +22,11 @@ use chrono::{DateTime, Duration, NaiveDate, Utc};
2022
use serde::Deserialize;
2123

2224
use crate::fetcher::codex::common::{
23-
cost_usd, discover_session_dirs, format_cost, format_tokens, list_session_files,
24-
project_name_from_cwd, short_model_name,
25+
discover_session_dirs, format_cost, format_tokens, list_session_files, project_name_from_cwd,
26+
short_model_name,
2527
};
2628
use crate::fetcher::github::common::{cache_key, parse_options, payload};
29+
use crate::fetcher::llm_pricing::{self, PriceMap};
2730
use crate::fetcher::{FetchContext, FetchError, Fetcher, Safety};
2831
use crate::options::OptionSchema;
2932
use crate::payload::{
@@ -119,11 +122,22 @@ impl Fetcher for CodexUsage {
119122
let group_by = parse_group_by(opts.group_by.as_deref())?;
120123
let shape = ctx.shape.unwrap_or(Shape::Text);
121124

122-
let snapshot = build_snapshot(&since, group_by, limit);
125+
let prices = llm_pricing::fetch_pricing(http()).await;
126+
let snapshot = build_snapshot(&since, group_by, limit, &prices);
123127
Ok(payload(render_body(&snapshot, shape)))
124128
}
125129
}
126130

131+
fn http() -> &'static reqwest::Client {
132+
static CLIENT: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
133+
CLIENT.get_or_init(|| {
134+
reqwest::Client::builder()
135+
.user_agent(concat!("splashboard/", env!("CARGO_PKG_VERSION")))
136+
.build()
137+
.expect("reqwest client should build with default config")
138+
})
139+
}
140+
127141
#[derive(Debug, Clone, Copy)]
128142
enum Since {
129143
Today,
@@ -220,21 +234,27 @@ impl UsageEvent {
220234
// count it. Reasoning tokens already roll into `output_tokens`.
221235
self.input_tokens + self.output_tokens
222236
}
223-
fn cost(&self) -> f64 {
224-
cost_usd(
237+
fn cost(&self, prices: &PriceMap) -> f64 {
238+
// OpenAI reports `cached_input_tokens` as a subset of `input_tokens`; pass the
239+
// non-cached chunk at the full input rate and the cached chunk at `cache_read`.
240+
let billable_input = self.input_tokens.saturating_sub(self.cached_input_tokens);
241+
llm_pricing::cost_usd(
242+
prices,
225243
&self.model,
226-
self.input_tokens,
227-
self.cached_input_tokens,
244+
billable_input,
228245
self.output_tokens,
246+
self.cached_input_tokens,
247+
0,
248+
0,
229249
)
230250
}
231251
}
232252

233-
fn build_snapshot(since: &Since, group_by: GroupBy, limit: usize) -> Snapshot {
253+
fn build_snapshot(since: &Since, group_by: GroupBy, limit: usize, prices: &PriceMap) -> Snapshot {
234254
let events = collect_events(&list_session_files(&discover_session_dirs()), since);
235255
let total_tokens = events.iter().map(UsageEvent::token_total).sum();
236-
let total_cost = events.iter().map(UsageEvent::cost).sum();
237-
let rows = group_rows(&events, group_by, limit);
256+
let total_cost: f64 = events.iter().map(|e| e.cost(prices)).sum();
257+
let rows = group_rows(&events, group_by, limit, prices);
238258
let daily_tokens = daily_series(&events, since);
239259
Snapshot {
240260
rows,
@@ -376,7 +396,12 @@ fn token_usage_from_event(payload: &RawPayload) -> Option<RawTokenUsage> {
376396
})
377397
}
378398

379-
fn group_rows(events: &[UsageEvent], group_by: GroupBy, limit: usize) -> Vec<UsageRow> {
399+
fn group_rows(
400+
events: &[UsageEvent],
401+
group_by: GroupBy,
402+
limit: usize,
403+
prices: &PriceMap,
404+
) -> Vec<UsageRow> {
380405
let mut by_key: HashMap<String, (u64, f64)> = HashMap::new();
381406
for e in events {
382407
let key = match group_by {
@@ -386,7 +411,7 @@ fn group_rows(events: &[UsageEvent], group_by: GroupBy, limit: usize) -> Vec<Usa
386411
};
387412
let entry = by_key.entry(key).or_insert((0, 0.0));
388413
entry.0 += e.token_total();
389-
entry.1 += e.cost();
414+
entry.1 += e.cost(prices);
390415
}
391416
let mut rows: Vec<UsageRow> = by_key
392417
.into_iter()
@@ -709,7 +734,7 @@ mod tests {
709734
output_tokens: output,
710735
};
711736
let events = vec![make("a", 1_000), make("b", 5_000), make("c", 100)];
712-
let rows = group_rows(&events, GroupBy::Project, 2);
737+
let rows = group_rows(&events, GroupBy::Project, 2, &llm_pricing::embedded_floor());
713738
assert_eq!(rows.len(), 2);
714739
assert_eq!(rows[0].label, "b");
715740
assert_eq!(rows[1].label, "a");

0 commit comments

Comments
 (0)