Skip to content

Commit 65e8005

Browse files
committed
fix(usage): account for recorded speed tiers
Recent rollouts persist explicit Fast and Standard settings. Preserve those transitions during parsing so mixed-mode reports apply published rates only to matching requests. Reconcile copied records before attributing tier buckets so file order and worker scheduling cannot change cost estimates. Command-line overrides remain authoritative, with config used only for unclassified usage.
1 parent b9cd694 commit 65e8005

16 files changed

Lines changed: 1168 additions & 116 deletions

File tree

‎docs/guide/codex/index.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ These views support `--json`, `--compact`, `--offline`, and `--speed auto|standa
4848
- **Token deltas** – Each `event_msg` with `payload.type === "token_count"` reports cumulative totals and, when available, the latest request delta. Current MultiAgent V2 subagent rollouts can persist a replayed parent-history prefix; the CLI uses the final inherited snapshot as the child baseline, then counts only advancing usage from the child turn. Older Codex replay formats retain timestamp-based compatibility handling.
4949
- **Per-model grouping** – The active `turn_context` specifies the model for newly counted usage. Replayed parent contexts in current MultiAgent V2 subagent prefixes remain inherited history and do not add model usage to the child. We aggregate tokens per day/month and per model. Sessions lacking model metadata (seen in early September 2025 builds) are skipped.
5050
- **Pricing** – Rates come from LiteLLM's pricing dataset via the shared `LiteLLMPricingFetcher`. Codex's internal review label is resolved to the newest known model for the log date before pricing is calculated.
51-
- **Speed pricing** – `--speed auto` is the default. It reads `config.toml` from each `CODEX_HOME` root and applies fast pricing when any Codex config has `service_tier = "priority"` or legacy `service_tier = "fast"` configured. Fast mode applies a model-specific multiplier only when one is available; when the rate is unknown, ccusage reports standard pricing rather than assuming a multiplier, which may underestimate actual Fast usage. Pass `--speed fast` or `--speed standard` to override config-based detection.
51+
- **Speed pricing** – `--speed auto` is the default. For rollouts written by Codex CLI 0.144.0 and later, ccusage applies recorded `thread_settings_applied` tier changes chronologically: `priority` and legacy `fast` use Fast pricing, while `default` uses Standard pricing. Unmarked usage falls back to `config.toml` detection. Pass `--speed fast` or `--speed standard` to override every recorded tier. Fast pricing uses a model-specific multiplier only when one is available; otherwise, ccusage keeps standard pricing rather than inventing a rate.
5252
- **Legacy fallback** – Early September 2025 logs that never recorded `turn_context` metadata are still included; the CLI assumes `gpt-5` for pricing so you can review the tokens even though the model tag is missing (the JSON output also marks these rows with `"isFallback": true`).
5353
- **Cost formula** – Non-cached input uses the standard input price; cached input uses the cache-read price (falling back to the input price when missing); and output tokens are billed at the output price. All prices are per million tokens. Reasoning tokens may be shown for reference, but they are part of the output charge and are not billed separately.
5454
- **Totals and reports** – Daily, monthly, and session views display per-model breakdowns, overall totals, and optional JSON for automation.
@@ -64,10 +64,14 @@ When Codex emits a model alias, the CLI automatically resolves it through the Li
6464

6565
## Speed Pricing
6666

67-
Codex logs usually do not include whether a turn used fast mode. By default, `ccusage codex` uses `--speed auto`, reads `config.toml` from each `CODEX_HOME` root, and treats `service_tier = "priority"` or legacy `service_tier = "fast"` as fast pricing when any configured root opts into it. Fast mode applies a model-specific multiplier only when one is available; when the rate is unknown, ccusage reports standard pricing rather than assuming a multiplier, which may underestimate actual Fast usage.
67+
By default, `ccusage codex` uses `--speed auto`. Codex CLI 0.144.0 and later can persist `thread_settings_applied` events in session rollouts. ccusage associates each token event with the most recent recognized setting: `service_tier = "priority"` or legacy `"fast"` is Fast, and `"default"` is Standard. This supports sessions that switch modes over time instead of applying one multiplier to the entire day or session.
68+
69+
Some usage remains unclassified, including older rollouts, saved headless `codex exec --json` output, and startup usage before the first persisted settings event. For only that unclassified portion, auto mode reads `config.toml` from each `CODEX_HOME` root and uses Fast when any root has `service_tier = "priority"` or legacy `service_tier = "fast"`; otherwise it uses Standard. An unsupported recorded tier is also left unclassified rather than inheriting a stale Fast value. Explicit `--speed fast` and `--speed standard` override all recorded and fallback tiers.
70+
71+
Fast pricing uses a model-specific multiplier only when one is published. GPT-5.6 Sol, Terra, and Luna use the [documented 2× API Priority rate](https://learn.chatgpt.com/docs/agent-configuration/speed#fast-mode). This is distinct from the 2.5× ChatGPT credit-consumption rate shown for GPT-5.6 Fast mode: ccusage's `costUSD` is an API-equivalent estimate, not a ChatGPT credit balance. When a model's Fast rate is unknown, ccusage reports standard pricing rather than assuming a multiplier, which may underestimate actual Fast usage.
6872

6973
```bash
70-
# Default: read Codex config.toml
74+
# Default: use recorded tiers, then config.toml for unmarked usage
7175
ccusage codex daily --speed auto
7276

7377
# Force fast pricing

‎rust/crates/ccusage-cli/src/cli-help.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@
185185
},
186186
{
187187
"flags": "--speed [speed]",
188-
"description": "Cost speed tier: auto reads Codex config.toml service_tier; use standard or fast to override",
188+
"description": "Cost speed tier: auto uses recorded settings, then Codex config.toml; use standard or fast to override",
189189
"default": "auto",
190190
"choices": ["auto", "standard", "fast"]
191191
},

‎rust/crates/ccusage-cli/src/snapshots/ccusage_cli__tests__codex_daily_help.snap‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ OPTIONS:
1414
-z, --timezone <timezone> Timezone for date grouping (IANA)
1515
-O, --offline Use cached pricing data instead of fetching from LiteLLM (default: false)
1616
--no-offline Negatable of -O, --offline
17-
--speed [speed] Cost speed tier: auto reads Codex config.toml service_tier; use standard or fast to override (default: auto, choices: auto | standard | fast)
17+
--speed [speed] Cost speed tier: auto uses recorded settings, then Codex config.toml; use standard or fast to override (default: auto, choices: auto | standard | fast)
1818
--compact Force compact table layout for narrow terminals (default: false)
1919
--no-cost Hide cost information in table and JSON output (default: false)
2020
--color Enable colored output. FORCE_COLOR=1 has the same effect. (default: auto)

‎rust/crates/ccusage/src/adapter/all/loader.rs‎

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -767,12 +767,16 @@ fn summary_metadata(summary: &UsageSummary, include_project_path: bool) -> Optio
767767
}
768768
}
769769

770-
pub(super) fn codex_group_row(
770+
pub(super) fn codex_group_row<S>(
771771
period: &str,
772772
group: &CodexGroup,
773773
pricing: &PricingMap,
774-
speed: CodexSpeed,
775-
) -> AllRow {
774+
speed: S,
775+
) -> AllRow
776+
where
777+
S: Into<codex::CodexSpeedPolicy> + Copy,
778+
{
779+
let speed = speed.into();
776780
let mut model_breakdowns: Vec<ModelBreakdown> = group
777781
.models
778782
.iter()
@@ -884,6 +888,47 @@ mod tests {
884888
assert_eq!(rows[0].input_tokens, 20);
885889
}
886890

891+
#[test]
892+
fn unified_row_matches_focused_cost_for_mixed_recorded_tiers() {
893+
let mut pricing = PricingMap::default();
894+
pricing.load_json(
895+
r#"{
896+
"gpt-test": {
897+
"input_cost_per_token": 0.000001,
898+
"output_cost_per_token": 0.000002,
899+
"provider_specific_entry": { "fast": 2 }
900+
}
901+
}"#,
902+
);
903+
let usage = crate::CodexModelUsage {
904+
input_tokens: 30,
905+
total_tokens: 30,
906+
recorded_standard_usage: crate::CodexUsageBucket {
907+
input_tokens: 10,
908+
..crate::CodexUsageBucket::default()
909+
},
910+
recorded_fast_usage: crate::CodexUsageBucket {
911+
input_tokens: 10,
912+
..crate::CodexUsageBucket::default()
913+
},
914+
..crate::CodexModelUsage::default()
915+
};
916+
let mut group = CodexGroup {
917+
input_tokens: 30,
918+
total_tokens: 30,
919+
..CodexGroup::default()
920+
};
921+
group.models.insert("gpt-test".to_string(), usage);
922+
let speed = codex::CodexSpeedPolicy::Auto(crate::CodexServiceTier::Standard);
923+
924+
let focused_cost = codex::calculate_group_cost(&group, &pricing, speed);
925+
let unified = codex_group_row("2026-07-22", &group, &pricing, speed);
926+
927+
assert!((focused_cost - 40e-6).abs() < f64::EPSILON);
928+
assert!((unified.total_cost - focused_cost).abs() < f64::EPSILON);
929+
assert!((unified.model_breakdowns[0].cost - focused_cost).abs() < f64::EPSILON);
930+
}
931+
887932
fn pi_path_subcommand_rows(
888933
store_path: &str,
889934
kind: AgentReportKind,

‎rust/crates/ccusage/src/adapter/codex/README.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,14 @@ Relevant JSONL event:
1818
- `payload.info.last_token_usage` is the current turn delta.
1919
- If only cumulative totals exist, subtract prior totals to recover deltas.
2020

21+
Relevant speed-setting event in Codex CLI 0.144.0 and later:
22+
23+
- `type === "event_msg"`
24+
- `payload.type === "thread_settings_applied"`
25+
- `payload.thread_settings.service_tier === "priority"` (or legacy `"fast"`) selects Fast.
26+
- `payload.thread_settings.service_tier === "default"` selects Standard.
27+
- Token usage inherits the latest recognized setting in the rollout. Missing or unsupported settings remain unclassified so report policy can apply its documented fallback.
28+
2129
Token mapping:
2230

2331
- `input_tokens` - total input tokens.

0 commit comments

Comments
 (0)