Skip to content

Commit e39ed83

Browse files
authored
fix(claude): keep the cache TTL split when deduping equal copies (ccusage#2060)
* fix(claude): keep the cache TTL split when deduping equal copies Both Claude dedup comparators (daily and the session loader) settle a tie between duplicates with equal token totals, and in daily also equal cost, by preferring the copy that reports `speed`. Otherwise the first copy seen survives. When one copy of a message reports the 5m/1h `cache_creation` split and the other only the flat `cache_creation_input_tokens`, the split was dropped whenever the flat copy was read first, so `cacheCreation1hTokens` went missing or was undercounted in `modelBreakdowns`. Move the tie-break into one shared `carries_more_usage_detail` helper that ranks the speed tier first (it changes cost) and the TTL split second, and use it from both comparators. Sidechain, token-total and daily cost priorities are unchanged, and inputs without such a pair produce the same output. In calculate mode the split copy never costs less than the flat one for equal tokens, because 1h writes are priced above 5m ones. Daily's cost comparison therefore already kept it whenever 1h tokens were non-zero. The session loader does not compare cost and kept the flat copy, so the same data reported a lower session cost than daily. Preferring the split resolves that tie in the same direction as the cost order. * fix(claude): rank Fast above Standard when deduping equal copies `carries_more_usage_detail` ranked the speed tier with `speed.is_some()`, the same check the comparators used on main. That treats `Standard` and `Fast` as equal, so a Standard copy that also carried the cache TTL split could replace a Fast copy, or a Standard copy seen first could survive a later Fast one. Only `Fast` carries the fast-mode price multiplier, so the session loader (which does not compare cost) could undercount the request's cost. Rank the tiers explicitly as None < Standard < Fast, before the TTL split tie-break. Reported by Cubic on ccusage#2060. * test(claude): cover the TTL split of equal duplicates in CLI JSON Assert `cacheCreation1hTokens` and `totalCost` for `claude daily` and `claude session` in calculate mode when one copy of a message carries the 5m/1h split and the other does not, in both orders. On main, daily already kept the split through its cost comparison while session kept the unsplit copy, so session reported no 1h tokens and a lower cost. Requested by Cubic on ccusage#2060.
1 parent c17c591 commit e39ed83

3 files changed

Lines changed: 161 additions & 5 deletions

File tree

‎rust/adapters/claude/src/daily.rs‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ use crate::{
2121

2222
use super::{
2323
DailySummaries, DedupeIndexVec, SessionDays, advisor_usages_from_line,
24-
chunk_file_indexes_by_size, deserialize_usage_line, is_anthropic_message_id, is_semver_prefix,
25-
main_thread_session_days,
24+
carries_more_usage_detail, chunk_file_indexes_by_size, deserialize_usage_line,
25+
is_anthropic_message_id, is_semver_prefix, main_thread_session_days,
2626
paths::{SinceFiles, claude_paths, extract_project, split_files_before_since, usage_files},
2727
push_deduped_index, push_deduped_session_alias, push_new_deduped_index,
2828
sidechain_entry_replay_dedupe_hash, sidechain_replay_dedupe_hash, usage_dedupe_hash,
@@ -652,7 +652,7 @@ fn should_replace_deduped_daily_entry(
652652
if candidate.cost != existing.cost {
653653
return candidate.cost > existing.cost;
654654
}
655-
candidate.usage.speed.is_some() && existing.usage.speed.is_none()
655+
carries_more_usage_detail(&candidate.usage, &existing.usage)
656656
}
657657

658658
fn is_sidechain_daily_entry(entry: &DailyLoadedEntry) -> bool {
@@ -992,6 +992,40 @@ mod tests {
992992
);
993993
}
994994

995+
#[test]
996+
fn keeps_the_cache_ttl_split_from_an_otherwise_equal_daily_duplicate() {
997+
for lines in [
998+
[
999+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100}}}"#,
1000+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":40,"ephemeral_1h_input_tokens":60}}}}"#,
1001+
],
1002+
[
1003+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":40,"ephemeral_1h_input_tokens":60}}}}"#,
1004+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100}}}"#,
1005+
],
1006+
] {
1007+
let fixture = fs_fixture!({
1008+
"projects/project-a/session-a.jsonl": lines.join("\n"),
1009+
});
1010+
let _env = EnvVarsGuard::set_many([(
1011+
"CLAUDE_CONFIG_DIR",
1012+
Some(fixture.root().as_os_str().to_os_string()),
1013+
)]);
1014+
let shared = SharedArgs {
1015+
mode: CostMode::Display,
1016+
timezone: Some("UTC".to_string()),
1017+
single_thread: true,
1018+
..SharedArgs::default()
1019+
};
1020+
1021+
let daily = load_daily_summaries_inner(&shared, None, false, session_days).unwrap();
1022+
1023+
let breakdown = &daily.summaries[0].model_breakdowns[0];
1024+
assert_eq!(breakdown.cache_creation_tokens, 100);
1025+
assert_eq!(breakdown.cache_creation_1h_tokens, Some(60));
1026+
}
1027+
}
1028+
9951029
#[test]
9961030
fn dedupes_anthropic_message_id_from_same_session_at_distinct_timestamps() {
9971031
let mut deduped_indexes = Default::default();

‎rust/adapters/claude/src/lib.rs‎

Lines changed: 90 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,23 @@ fn should_replace_deduped_entry(candidate: &UsageEntry, existing: &UsageEntry) -
294294
return candidate_total > existing_total;
295295
}
296296

297-
candidate.message.usage.speed.is_some() && existing.message.usage.speed.is_none()
297+
carries_more_usage_detail(&candidate.message.usage, &existing.message.usage)
298+
}
299+
300+
/// Breaks a tie between duplicates with equal token totals by keeping the copy
301+
/// that reports more of the request: the speed tier, with `Fast` above
302+
/// `Standard` because only `Fast` carries the fast-mode price multiplier, then
303+
/// the cache-write TTL split.
304+
fn carries_more_usage_detail(candidate: &TokenUsageRaw, existing: &TokenUsageRaw) -> bool {
305+
let detail = |usage: &TokenUsageRaw| {
306+
let speed_rank = match usage.speed {
307+
None => 0,
308+
Some(Speed::Standard) => 1,
309+
Some(Speed::Fast) => 2,
310+
};
311+
(speed_rank, usage.cache_creation.is_some())
312+
};
313+
detail(candidate) > detail(existing)
298314
}
299315

300316
fn push_deduped_entry(
@@ -990,7 +1006,8 @@ mod tests {
9901006
push_deduped_entry, read_usage_file, usage_files,
9911007
};
9921008
use crate::{
993-
LoadedEntry, PricingMap, TimestampMs, TokenUsageRaw, UsageEntry, UsageMessage,
1009+
LoadedEntry, ModelBreakdown, PricingMap, Speed, TimestampMs, TokenUsageRaw, UsageEntry,
1010+
UsageMessage,
9941011
cli::{CostMode, SharedArgs},
9951012
};
9961013
use ccusage_test_support::{EnvVarsGuard, fs_fixture};
@@ -1347,6 +1364,77 @@ null,"usage":{"input_tokens":1}}}"#
13471364
);
13481365
}
13491366

1367+
#[test]
1368+
fn keeps_the_cache_ttl_split_from_an_otherwise_equal_duplicate() {
1369+
for lines in [
1370+
[
1371+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100}}}"#,
1372+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":40,"ephemeral_1h_input_tokens":60}}}}"#,
1373+
],
1374+
[
1375+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":40,"ephemeral_1h_input_tokens":60}}}}"#,
1376+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100}}}"#,
1377+
],
1378+
] {
1379+
let fixture = fs_fixture!({
1380+
"projects/project-a/session-a.jsonl": lines.join("\n"),
1381+
});
1382+
let _env = EnvVarsGuard::set_many([(
1383+
"CLAUDE_CONFIG_DIR",
1384+
Some(fixture.root().as_os_str().to_os_string()),
1385+
)]);
1386+
let shared = SharedArgs {
1387+
mode: CostMode::Display,
1388+
single_thread: true,
1389+
..SharedArgs::default()
1390+
};
1391+
1392+
let deduped = load_deduped_entries(&shared, None).unwrap();
1393+
1394+
assert_eq!(deduped.entries.len(), 1);
1395+
let mut breakdown = ModelBreakdown::default();
1396+
breakdown.add_usage(&deduped.entries[0].data.message.usage);
1397+
assert_eq!(breakdown.cache_creation_tokens, 100);
1398+
assert_eq!(breakdown.cache_creation_1h_tokens, Some(60));
1399+
}
1400+
}
1401+
1402+
#[test]
1403+
fn keeps_the_fast_tier_from_an_otherwise_equal_duplicate() {
1404+
for lines in [
1405+
[
1406+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100,"speed":"standard","cache_creation":{"ephemeral_5m_input_tokens":40,"ephemeral_1h_input_tokens":60}}}}"#,
1407+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100,"speed":"fast"}}}"#,
1408+
],
1409+
[
1410+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100,"speed":"fast"}}}"#,
1411+
r#"{"timestamp":"2026-05-22T02:34:40.000Z","sessionId":"session-a","requestId":"req-a","message":{"id":"msg_a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":5,"cache_creation_input_tokens":100,"speed":"standard","cache_creation":{"ephemeral_5m_input_tokens":40,"ephemeral_1h_input_tokens":60}}}}"#,
1412+
],
1413+
] {
1414+
let fixture = fs_fixture!({
1415+
"projects/project-a/session-a.jsonl": lines.join("\n"),
1416+
});
1417+
let mut deduped_indexes = Default::default();
1418+
let mut deduped = Vec::new();
1419+
1420+
let loaded = read_usage_file(
1421+
&fixture.path("projects/project-a/session-a.jsonl"),
1422+
None,
1423+
CostMode::Display,
1424+
None,
1425+
);
1426+
for entry in loaded.entries {
1427+
push_deduped_entry(entry, &mut deduped_indexes, &mut deduped);
1428+
}
1429+
1430+
assert_eq!(deduped.len(), 1);
1431+
assert!(matches!(
1432+
deduped[0].data.message.usage.speed,
1433+
Some(Speed::Fast)
1434+
));
1435+
}
1436+
}
1437+
13501438
#[test]
13511439
fn dedupes_anthropic_message_id_from_same_session_at_distinct_timestamps() {
13521440
let fixture = fs_fixture!({

‎rust/crates/ccusage/tests/claude_cli.rs‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1127,3 +1127,37 @@ fn breakdowns_report_one_hour_cache_creation_tokens_only_for_models_with_a_split
11271127
);
11281128
}
11291129
}
1130+
1131+
#[test]
1132+
fn breakdowns_keep_the_one_hour_split_from_an_otherwise_equal_duplicate() {
1133+
let unsplit = r#"{"timestamp":"2026-09-15T12:00:00.000Z","sessionId":"session-a","requestId":"request-a","message":{"id":"message-a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":2,"cache_creation_input_tokens":400}}}"#;
1134+
let split = r#"{"timestamp":"2026-09-15T12:00:00.000Z","sessionId":"session-a","requestId":"request-a","message":{"id":"message-a","model":"claude-sonnet-4-20250514","usage":{"input_tokens":10,"output_tokens":2,"cache_creation_input_tokens":400,"cache_creation":{"ephemeral_5m_input_tokens":100,"ephemeral_1h_input_tokens":300}}}}"#;
1135+
1136+
for lines in [[unsplit, split], [split, unsplit]] {
1137+
let fixture = Fixture::new();
1138+
let _ = fixture.write_file("projects/project-a/session-a/chat.jsonl", lines.join("\n"));
1139+
1140+
let mut costs = Vec::new();
1141+
for (report, pointer) in [("daily", "/daily/0"), ("session", "/sessions/0")] {
1142+
let args = [
1143+
"claude",
1144+
report,
1145+
"--json",
1146+
"--offline",
1147+
"--mode",
1148+
"calculate",
1149+
"--timezone",
1150+
"UTC",
1151+
];
1152+
let json: serde_json::Value =
1153+
serde_json::from_str(&run_ccusage(&fixture, &args, None)).unwrap();
1154+
let row = json.pointer(pointer).unwrap();
1155+
let breakdown = &row["modelBreakdowns"][0];
1156+
1157+
assert_eq!(breakdown["cacheCreationTokens"], 400, "{args:?}: {row}");
1158+
assert_eq!(breakdown["cacheCreation1hTokens"], 300, "{args:?}: {row}");
1159+
costs.push(row["totalCost"].as_f64().unwrap());
1160+
}
1161+
assert_eq!(costs[0], costs[1], "daily and session cost: {costs:?}");
1162+
}
1163+
}

0 commit comments

Comments
 (0)