Skip to content

Commit 73f6808

Browse files
unhappychoiceclaude
andcommitted
fix(fetcher/claude_code_usage): address coderabbit review findings
Three nits surfaced by the bot review: 1. `Since::Days(n).includes()` was a rolling `now - n days` timestamp cutoff while `daily_series` bucketed by calendar day. Near the n-day boundary, partial-day events were counted in the totals but never appeared in the per-day series. Swap to a calendar-day comparison (`today .. today-(n-1)`) so both views agree on the window. 2. Dropped the brittle `line.contains("\"type\":\"assistant\"")` pre-filter. `parse_event` already gates on `raw.kind == "assistant"` — the substring guard was only a perf hack and would silently miss records if Claude Code's JSONL formatter ever emitted `"type": "assistant"` with whitespace. Cost is ~5% more parsing per refresh, absorbed by the 5-min cache TTL. 3. Empty-ID dedup collision: serde fills missing `message.id` / `requestId` with `""`, so two unrelated assistant turns lacking those fields collapsed into a single `("", "")` bucket and one would be discarded. Records with either ID missing now pass through unmodified instead. Two new tests pin the new invariants: - `since_days_window_uses_calendar_day_boundary_not_rolling_timestamp` - `dedup_passes_through_events_with_empty_ids_instead_of_collapsing_them` Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 59e3fdc commit 73f6808

1 file changed

Lines changed: 64 additions & 3 deletions

File tree

‎src/fetcher/claude/code_usage.rs‎

Lines changed: 64 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,15 @@ impl Since {
143143
match self {
144144
Since::All => true,
145145
Since::Today => ts.date_naive() == Utc::now().date_naive(),
146-
Since::Days(n) => Utc::now() - Duration::days(*n) <= ts,
146+
// Calendar-day comparison so this matches `daily_series`'s bucket window exactly
147+
// (today .. today-(n-1)). A rolling `now - n days` cutoff would leak partial-day
148+
// events into the totals that never show up in the per-day series.
149+
Since::Days(n) => {
150+
let today = Utc::now().date_naive();
151+
let start = today - Duration::days((*n - 1).max(0));
152+
let day = ts.date_naive();
153+
day >= start && day <= today
154+
}
147155
}
148156
}
149157
}
@@ -273,10 +281,12 @@ fn read_session_file(path: &PathBuf, since: &Since) -> Vec<UsageEvent> {
273281
let Ok(file) = fs::File::open(path) else {
274282
return Vec::new();
275283
};
284+
// Let `parse_event` do the type-filter — its internal `kind != "assistant"` check is the
285+
// authoritative one. A substring pre-filter here would silently drop valid records if Claude
286+
// Code's JSONL formatter ever switches to `"type": "assistant"` with whitespace.
276287
BufReader::new(file)
277288
.lines()
278289
.map_while(Result::ok)
279-
.filter(|line| line.contains("\"type\":\"assistant\""))
280290
.filter_map(|line| parse_event(&line))
281291
.filter(|e| since.includes(e.timestamp))
282292
.collect()
@@ -359,7 +369,15 @@ fn parse_event(line: &str) -> Option<UsageEvent> {
359369

360370
fn dedup(events: Vec<UsageEvent>) -> Vec<UsageEvent> {
361371
let mut by_key: HashMap<(String, String), UsageEvent> = HashMap::new();
372+
let mut passthrough: Vec<UsageEvent> = Vec::new();
362373
for e in events {
374+
// serde `#[default]` fills missing IDs with `""`. Collapsing every empty-ID record into
375+
// one dedup bucket would silently drop unrelated assistant turns — fall through to the
376+
// passthrough list instead so usage stays accurate even if a future schema omits an ID.
377+
if e.message_id.is_empty() || e.request_id.is_empty() {
378+
passthrough.push(e);
379+
continue;
380+
}
363381
let key = (e.message_id.clone(), e.request_id.clone());
364382
// ccusage gotcha: a `(message.id, requestId)` can repeat across files when a session
365383
// resumes. Keep the row with the higher total — that's the canonical final usage.
@@ -372,7 +390,9 @@ fn dedup(events: Vec<UsageEvent>) -> Vec<UsageEvent> {
372390
})
373391
.or_insert(e);
374392
}
375-
by_key.into_values().collect()
393+
let mut out: Vec<UsageEvent> = by_key.into_values().collect();
394+
out.extend(passthrough);
395+
out
376396
}
377397

378398
fn group_rows(events: &[UsageEvent], group_by: GroupBy, limit: usize) -> Vec<UsageRow> {
@@ -755,6 +775,47 @@ mod tests {
755775
assert!(Since::All.includes(old));
756776
}
757777

778+
#[test]
779+
fn since_days_window_uses_calendar_day_boundary_not_rolling_timestamp() {
780+
// For Days(7) the inclusive window is `today .. today-6` (matching daily_series's 7
781+
// bucket span). The boundary day (today-6) at midnight must be included, and the day
782+
// before (today-7) at 23:59 must be excluded — even though the rolling
783+
// `now - 7 days` cutoff would put both on the same side.
784+
use chrono::TimeZone;
785+
let today = Utc::now().date_naive();
786+
let boundary_in =
787+
Utc.from_utc_datetime(&(today - Duration::days(6)).and_hms_opt(0, 0, 0).unwrap());
788+
let just_out =
789+
Utc.from_utc_datetime(&(today - Duration::days(7)).and_hms_opt(23, 59, 0).unwrap());
790+
assert!(Since::Days(7).includes(boundary_in));
791+
assert!(!Since::Days(7).includes(just_out));
792+
}
793+
794+
#[test]
795+
fn dedup_passes_through_events_with_empty_ids_instead_of_collapsing_them() {
796+
// serde fills missing IDs with `""`; two unrelated assistant turns with empty IDs must
797+
// not collide into a single dedup bucket — that would silently lose usage.
798+
let make = |suffix: u64| UsageEvent {
799+
timestamp: Utc::now(),
800+
model: "claude-sonnet-4-6".into(),
801+
project: "x".into(),
802+
message_id: String::new(),
803+
request_id: String::new(),
804+
input_tokens: suffix,
805+
output_tokens: 0,
806+
cache_write_5m: 0,
807+
cache_write_1h: 0,
808+
cache_read: 0,
809+
};
810+
let kept = dedup(vec![make(1), make(2)]);
811+
assert_eq!(kept.len(), 2);
812+
assert_eq!(
813+
kept.iter().map(|e| e.input_tokens).sum::<u64>(),
814+
3,
815+
"both events must survive when ids are empty"
816+
);
817+
}
818+
758819
#[test]
759820
fn daily_series_length_matches_window() {
760821
let series = daily_series(&[], &Since::Days(7));

0 commit comments

Comments
 (0)