Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 90 additions & 101 deletions rust/src/codex_costs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
#[cfg(test)]
use chrono::Local;
use chrono::{Duration, NaiveDate};
use std::collections::HashMap;
use std::path::Path;

use crate::core::{CostUsageDayRange, CostUsagePricing, JsonlScanner};
use crate::core::{CodexUsageRecord, CostUsageDayRange, CostUsagePricing, JsonlScanner};
use crate::cost_scanner::{CostSummary, ModelTokenCounts};

pub(crate) type CodexDays = HashMap<String, HashMap<String, Vec<i32>>>;

pub(crate) fn codex_period_start(today: NaiveDate, days: u32) -> NaiveDate {
today - Duration::days(days.saturating_sub(1) as i64)
}
Expand All @@ -30,47 +27,21 @@ pub(crate) fn codex_scan_dates(range: &CostUsageDayRange) -> Vec<NaiveDate> {
dates
}

pub(crate) fn add_codex_days_to_summary(
pub(crate) fn add_codex_records_to_summary(
summary: &mut CostSummary,
days: &CodexDays,
records: &[CodexUsageRecord],
range: &CostUsageDayRange,
) -> (f64, bool) {
let mut total_cost = 0.0;
let mut has_tokens = false;

for models in codex_days_in_range(days, range) {
for (model, packed) in models {
let tokens = CodexTokenCounts::from_packed(packed);
if tokens.is_empty() {
continue;
}

let cost = codex_cost_usd(model, tokens.input, tokens.cached, tokens.output);
for record in records.iter().filter(|record| {
CostUsageDayRange::is_in_range(&record.day_key, &range.since_key, &range.until_key)
}) {
let tokens = CodexTokenCounts::from_values(record.input, record.cached, record.output);
if let Some(cost) = add_codex_tokens_to_summary(summary, &record.model, tokens) {
total_cost += cost;
has_tokens = true;

summary.input_tokens += tokens.input;
summary.cached_tokens += tokens.cached;
summary.output_tokens += tokens.output;
*summary.by_model.entry(model.clone()).or_insert(0.0) += cost;

let speed_bucket = codex_speed_bucket(model);
*summary
.by_speed
.entry(speed_bucket.to_string())
.or_insert(0.0) += cost;

add_tokens(
summary.by_model_tokens.entry(model.clone()).or_default(),
tokens,
);
add_tokens(
summary
.by_speed_tokens
.entry(speed_bucket.to_string())
.or_default(),
tokens,
);
}
}

Expand All @@ -83,7 +54,7 @@ pub(crate) fn scan_codex_file_cost_for_range(path: &Path, range: &CostUsageDayRa
Err(_) => return 0.0,
};

codex_days_cost(&parse_result.days, range)
codex_records_cost(&parse_result.records, range)
}

#[cfg(test)]
Expand All @@ -101,12 +72,12 @@ struct CodexTokenCounts {
}

impl CodexTokenCounts {
fn from_packed(packed: &[i32]) -> Self {
let input = packed.first().copied().unwrap_or(0).max(0) as u64;
fn from_values(input: i32, cached: i32, output: i32) -> Self {
let input = input.max(0) as u64;
Self {
input,
cached: (packed.get(1).copied().unwrap_or(0).max(0) as u64).min(input),
output: packed.get(2).copied().unwrap_or(0).max(0) as u64,
cached: (cached.max(0) as u64).min(input),
output: output.max(0) as u64,
}
}

Expand All @@ -121,34 +92,58 @@ fn add_tokens(summary: &mut ModelTokenCounts, tokens: CodexTokenCounts) {
summary.cached_tokens += tokens.cached;
}

fn codex_days_cost(days: &CodexDays, range: &CostUsageDayRange) -> f64 {
let mut total_cost = 0.0;
fn add_codex_tokens_to_summary(
summary: &mut CostSummary,
model: &str,
tokens: CodexTokenCounts,
) -> Option<f64> {
if tokens.is_empty() {
return None;
}

for models in codex_days_in_range(days, range) {
for (model, packed) in models {
let tokens = CodexTokenCounts::from_packed(packed);
if tokens.is_empty() {
continue;
}
let cost = codex_cost_usd(model, tokens.input, tokens.cached, tokens.output);
summary.input_tokens += tokens.input;
summary.cached_tokens += tokens.cached;
summary.output_tokens += tokens.output;
*summary.by_model.entry(model.to_string()).or_insert(0.0) += cost;

let speed_bucket = codex_speed_bucket(model);
*summary
.by_speed
.entry(speed_bucket.to_string())
.or_insert(0.0) += cost;
add_tokens(
summary
.by_model_tokens
.entry(model.to_string())
.or_default(),
tokens,
);
add_tokens(
summary
.by_speed_tokens
.entry(speed_bucket.to_string())
.or_default(),
tokens,
);
Some(cost)
}

fn codex_records_cost(records: &[CodexUsageRecord], range: &CostUsageDayRange) -> f64 {
let mut total_cost = 0.0;

total_cost += codex_cost_usd(model, tokens.input, tokens.cached, tokens.output);
for record in records.iter().filter(|record| {
CostUsageDayRange::is_in_range(&record.day_key, &range.since_key, &range.until_key)
}) {
let tokens = CodexTokenCounts::from_values(record.input, record.cached, record.output);
if !tokens.is_empty() {
total_cost += codex_cost_usd(&record.model, tokens.input, tokens.cached, tokens.output);
}
}

total_cost
}

fn codex_days_in_range<'a>(
days: &'a CodexDays,
range: &'a CostUsageDayRange,
) -> impl Iterator<Item = &'a HashMap<String, Vec<i32>>> + 'a {
days.iter()
.filter(move |(day_key, _)| {
CostUsageDayRange::is_in_range(day_key, &range.since_key, &range.until_key)
})
.map(|(_, models)| models)
}

fn codex_speed_bucket(model: &str) -> &'static str {
let normalized = model.to_ascii_lowercase();
if normalized.contains("fast")
Expand Down Expand Up @@ -189,6 +184,7 @@ fn codex_cost_usd(model: &str, input: u64, cached: u64, output: u64) -> f64 {
#[cfg(test)]
mod tests {
use super::*;
use crate::core::CodexUsageRecord;

#[test]
fn test_codex_pricing() {
Expand All @@ -208,52 +204,45 @@ mod tests {
}

#[test]
fn test_codex_speed_bucket() {
assert_eq!(codex_speed_bucket("gpt-5.5-fast"), "fast");
assert_eq!(codex_speed_bucket("gpt-5.3-codex-spark"), "fast");
assert_eq!(codex_speed_bucket("gpt-5-codex"), "standard");
}

#[test]
fn codex_summary_filters_expanded_scan_days_to_requested_range() {
fn codex_summary_prices_gpt56_usage_records_individually() {
let target = NaiveDate::from_ymd_opt(2026, 5, 31).unwrap();
let range = CostUsageDayRange::new(target, target);
let mut days = CodexDays::new();
for (day, input) in [
("2026-05-30", 1_000),
("2026-05-31", 2_000),
("2026-06-01", 4_000),
] {
days.entry(day.to_string())
.or_default()
.insert("gpt-5".to_string(), vec![input, 0, 0]);
}

let records = vec![
CodexUsageRecord {
day_key: "2026-05-31".to_string(),
model: "gpt-5.6-sol".to_string(),
input: 200_000,
cached: 0,
output: 0,
},
CodexUsageRecord {
day_key: "2026-05-31".to_string(),
model: "gpt-5.6-sol".to_string(),
input: 200_000,
cached: 0,
output: 0,
},
CodexUsageRecord {
day_key: "2026-05-30".to_string(),
model: "gpt-5.6-sol".to_string(),
input: 200_000,
cached: 0,
output: 0,
},
];
let mut summary = CostSummary::default();
let (cost, has_tokens) = add_codex_days_to_summary(&mut summary, &days, &range);

let expected = codex_cost_usd("gpt-5", 2_000, 0, 0);
let (cost, has_tokens) = add_codex_records_to_summary(&mut summary, &records, &range);

assert!(has_tokens);
assert_eq!(summary.input_tokens, 2_000);
assert_eq!(summary.output_tokens, 0);
assert!((cost - expected).abs() < f64::EPSILON);
assert_eq!(summary.input_tokens, 400_000);
assert!((cost - 2.0).abs() < f64::EPSILON);
}

#[test]
fn codex_daily_cost_filters_adjacent_scan_padding_days() {
let target = NaiveDate::from_ymd_opt(2026, 5, 31).unwrap();
let range = CostUsageDayRange::new(target, target);
let mut days = CodexDays::new();
days.entry("2026-05-30".to_string())
.or_default()
.insert("gpt-5".to_string(), vec![1_000, 0, 0]);
days.entry("2026-05-31".to_string())
.or_default()
.insert("gpt-5".to_string(), vec![2_000, 0, 0]);

let cost = codex_days_cost(&days, &range);
let expected = codex_cost_usd("gpt-5", 2_000, 0, 0);

assert!((cost - expected).abs() < f64::EPSILON);
fn test_codex_speed_bucket() {
assert_eq!(codex_speed_bucket("gpt-5.5-fast"), "fast");
assert_eq!(codex_speed_bucket("gpt-5.3-codex-spark"), "fast");
assert_eq!(codex_speed_bucket("gpt-5-codex"), "standard");
}
}
Loading