Skip to content

Commit 5f31039

Browse files
ryoppippiigorovh
andauthored
fix(all): count only in-window Claude usage in unified session reports (ccusage#2052)
* fix(all): count only in-window Claude usage in unified session reports The unified session report built each Claude session from every entry and then kept it only when its last activity fell inside the window. A session that continued past `--until` vanished with its in-window usage, and a session started before `--since` brought its earlier usage along, so `ccusage session` disagreed with `ccusage claude session` and the focused reports no longer added up to the unified one. Claude entries are now filtered by date before sessions are built, like `ccusage claude session` and the other unified sources. OpenCode `claude-agent` rows still match by whole session, so a turn crossing midnight is counted once, but only sessions with in-window usage count and a row must fall inside the Claude source's date range. `DedupedEntries` keeps the survivor index of each merged copy, so a copy's session counts on the day of the kept entry, as in the daily loader. Fixes ccusage#2016 * docs(all): describe in-window Claude session totals in unified reports Refs ccusage#2016 * test(all): assert which source keeps a session that runs past --until The regression test only checked the 100-token total. The old logic also reached 100: it dropped the Claude session whose last activity fell after --until and kept the OpenCode claude-agent copy of the same turn instead. The test now asserts each row's source and session, so it fails on the old behavior (an OpenCode `ses-agent` row) and passes only when the Claude session `claude-native-a` keeps the turn. Refs ccusage#2016 * test(claude): cover cross-session copy attribution on a different day The unified tests used the same date for a turn and its copy in another session, so they could not tell whether a copy's session is dated by the survivor or skipped when the survivor is not counted. A direct test of DedupedEntries::main_thread_session_days now repeats a turn a day earlier in another session and asserts that the copy's session lands on the survivor's day and drops out when is_counted rejects the survivor. Refs ccusage#2016 --------- Co-authored-by: igorovh <[email protected]>
1 parent e4f0ea9 commit 5f31039

7 files changed

Lines changed: 201 additions & 69 deletions

File tree

‎docs/guide/opencode/index.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ The `claude-agent` provider runs Claude Code under the hood, so each turn is als
8383
ccusage matches OpenCode rows to Claude usage by Claude Code session, not by individual turn:
8484

8585
- **Daily, weekly, and monthly reports** skip an OpenCode `claude-agent` row when the Claude source counted usage from the same Claude Code session on the row's date, in the Claude source's timezone. Rows still count when the Claude Code log is gone, holds no usage for that day, holds only subagent usage, or falls outside the Claude source's date range.
86-
- **Session reports** match whole Claude Code sessions, because a Claude session row holds all of its usage, including days outside the Claude source's date range. Resumed and forked transcripts repeat earlier turns, and ccusage keeps one copy of each repeated turn. The OpenCode rows of a session whose own main-thread turns survive are skipped when every transcript holding them is included. The rows of a session whose turns all survive under other sessions are skipped only when every transcript holding those copies is included. When all transcripts are included, which one keeps a repeated turn does not affect the total. When the Claude window includes only some of them, a repeated turn can be left out, if a session's rows are skipped while its kept copy is in an excluded transcript, or counted twice, if the turns that decide whether a session's rows are skipped (its own surviving main-thread turns, or its kept copies when it has none) span included and excluded transcripts, since its rows are then kept.
86+
- **Session reports** count only the usage of each Claude Code session inside the Claude source's date range. They skip an OpenCode `claude-agent` row when the Claude source counted main-thread usage from the same session in that range and the row's date is in the range too. Resumed and forked transcripts repeat earlier turns, and ccusage keeps one copy of each repeated turn; the session of a dropped copy counts on the day of the kept one, as in daily reports.
8787

8888
Because OpenCode dates a turn by when it started and Claude Code dates each model call, a turn that runs across midnight can be off in the daily family. It is counted twice when Claude has no usage from that session on the day the turn started. With `--until` on that day, the calls Claude logs after midnight are left out, even though OpenCode dates the whole turn on the earlier day.
8989

‎docs/guide/session-reports.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ ccusage claude session --since 20260501 --until 20260516
139139
ccusage claude session --since $(date -d '7 days ago' +%Y%m%d)
140140
```
141141

142-
For `ccusage claude session`, date filters are applied before session totals are calculated, so token and cost totals represent only the entries inside the selected window. Both bounds are inclusive, and `--timezone` determines the local date used for filtering.
142+
For `ccusage claude session` and the Claude rows of `ccusage session`, date filters are applied before session totals are calculated, so token and cost totals represent only the entries inside the selected window. A session that continues past `--until` still shows its usage from inside the window. Both bounds are inclusive, and `--timezone` determines the local date used for filtering.
143143

144144
### Cost Calculation Modes
145145

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

Lines changed: 68 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -70,57 +70,30 @@ pub fn load_deduped_entries(
7070
#[derive(Default)]
7171
pub struct DedupedEntries {
7272
pub entries: Vec<LoadedEntry>,
73-
/// `(session row the usage is counted under, recorded session of the
74-
/// copy)` pairs.
75-
copies: Vec<(Arc<str>, Arc<str>)>,
73+
/// `(survivor index, recorded session of the copy)` pairs.
74+
copies: Vec<(usize, Arc<str>)>,
7675
}
7776

7877
impl DedupedEntries {
79-
/// Recorded session IDs whose wrapper rows the Claude source already
80-
/// counts when it reports the session rows `is_counted` accepts. Session
81-
/// rows are keyed by the transcript path while a wrapper such as OpenCode
82-
/// links the session ID Claude Code recorded, so the two are kept apart. A
83-
/// session with its own surviving main-thread usage is covered exactly when
84-
/// the rows holding it are reported, because its own turns count only
85-
/// there. A session whose usage dedup kept entirely under other sessions is
86-
/// covered only when every one of those is reported.
87-
pub fn main_thread_sessions(&self, is_counted: impl Fn(&str) -> bool) -> HashSet<Arc<str>> {
88-
let (own_counted, own_uncounted): (Vec<_>, Vec<_>) = self
89-
.entries
78+
/// Main-thread days of the entries `is_counted` keeps, by recorded session ID. As in
79+
/// the daily loader, a merged copy's session counts on the day its survivor does.
80+
pub fn main_thread_session_days(
81+
&self,
82+
is_counted: impl Fn(&LoadedEntry) -> bool,
83+
) -> SessionDays {
84+
self.entries
9085
.iter()
91-
.filter(|entry| entry.data.is_sidechain != Some(true))
92-
.map(|entry| {
93-
(
94-
is_counted(&entry.session_id),
95-
loaded_entry_session_id(entry),
96-
)
97-
})
98-
.partition(|(counted, _)| *counted);
99-
let own_uncounted = own_uncounted
100-
.into_iter()
101-
.map(|(_, session_id)| session_id)
102-
.collect::<HashSet<_>>();
103-
let own = own_counted
104-
.into_iter()
105-
.map(|(_, session_id)| session_id)
106-
.chain(own_uncounted.iter().copied())
107-
.collect::<HashSet<_>>();
108-
let held_by_uncounted = self
109-
.copies
110-
.iter()
111-
.filter(|(survivor, _)| !is_counted(survivor))
112-
.map(|(_, copy)| copy.as_ref())
113-
.collect::<HashSet<_>>();
114-
own.iter()
115-
.copied()
116-
.filter(|session_id| !own_uncounted.contains(session_id))
86+
.map(|entry| (loaded_entry_session_id(entry), entry))
11787
.chain(
11888
self.copies
11989
.iter()
120-
.map(|(_, copy)| copy.as_ref())
121-
.filter(|copy| !own.contains(copy) && !held_by_uncounted.contains(copy)),
90+
.map(|(index, session_id)| (session_id.as_ref(), &self.entries[*index])),
12291
)
123-
.map(Arc::from)
92+
.filter(|(_, entry)| entry.data.is_sidechain != Some(true) && is_counted(entry))
93+
.map(|(session_id, entry)| (session_id, entry.date.as_str()))
94+
.collect::<HashSet<_>>()
95+
.into_iter()
96+
.map(|(session_id, date)| (Arc::from(session_id), date.to_owned()))
12497
.collect()
12598
}
12699
}
@@ -297,11 +270,6 @@ fn load_entries_inner(
297270
shared,
298271
format!("Kept {} usage entries after deduplication", deduped.len()),
299272
);
300-
let copies = copies
301-
.into_iter()
302-
.filter(|(index, _)| deduped[*index].data.is_sidechain != Some(true))
303-
.map(|(index, session_id)| (Arc::clone(&deduped[index].session_id), session_id))
304-
.collect();
305273
Ok(DedupedEntries {
306274
entries: deduped,
307275
copies,
@@ -1077,13 +1045,14 @@ mod tests {
10771045

10781046
use super::{
10791047
deserialize_usage_line, extract_session_parts, has_unsupported_null_field,
1080-
paths::is_project_path_segment, push_deduped_entry, read_usage_file, usage_files,
1048+
load_deduped_entries, paths::is_project_path_segment, push_deduped_entry, read_usage_file,
1049+
usage_files,
10811050
};
10821051
use crate::{
10831052
LoadedEntry, PricingMap, TimestampMs, TokenUsageRaw, UsageEntry, UsageMessage,
1084-
cli::CostMode,
1053+
cli::{CostMode, SharedArgs},
10851054
};
1086-
use ccusage_test_support::fs_fixture;
1055+
use ccusage_test_support::{EnvVarsGuard, fs_fixture};
10871056

10881057
#[test]
10891058
fn limits_usage_file_discovery_to_requested_project() {
@@ -1538,6 +1507,54 @@ mod tests {
15381507
assert_eq!(deduped[0].session_id.as_ref(), "session-b");
15391508
}
15401509

1510+
#[test]
1511+
fn attributes_a_cross_session_copy_to_the_survivor_day() {
1512+
let fixture = fs_fixture!({
1513+
"projects/project-a/session-a.jsonl": r#"{"timestamp":"2026-01-02T10:00:00.000Z","sessionId":"session-a","requestId":"req-shared","message":{"id":"msg-shared","model":"claude-sonnet-4-20250514","usage":{"input_tokens":200,"output_tokens":1}}}"#,
1514+
"projects/project-a/session-b.jsonl": [
1515+
r#"{"timestamp":"2026-01-01T10:00:00.000Z","sessionId":"session-b","requestId":"req-shared","message":{"id":"msg-shared","model":"claude-sonnet-4-20250514","usage":{"input_tokens":100,"output_tokens":1}}}"#,
1516+
r#"{"timestamp":"2026-01-03T10:00:00.000Z","sessionId":"session-b","requestId":"req-own","message":{"id":"msg-own","model":"claude-sonnet-4-20250514","usage":{"input_tokens":7,"output_tokens":1}}}"#,
1517+
]
1518+
.join("\n"),
1519+
});
1520+
let _env = EnvVarsGuard::set_many([(
1521+
"CLAUDE_CONFIG_DIR",
1522+
Some(fixture.root().as_os_str().to_os_string()),
1523+
)]);
1524+
let shared = SharedArgs {
1525+
mode: CostMode::Display,
1526+
timezone: Some("UTC".to_string()),
1527+
single_thread: true,
1528+
json: true,
1529+
..SharedArgs::default()
1530+
};
1531+
let deduped = load_deduped_entries(&shared, None).unwrap();
1532+
let sorted_days = |is_counted: &dyn Fn(&LoadedEntry) -> bool| {
1533+
let mut days: Vec<_> = deduped
1534+
.main_thread_session_days(is_counted)
1535+
.into_iter()
1536+
.map(|(session, date)| (session.to_string(), date))
1537+
.collect();
1538+
days.sort();
1539+
days
1540+
};
1541+
let day = |session: &str, date: &str| (session.to_string(), date.to_string());
1542+
1543+
assert_eq!(deduped.entries.len(), 2);
1544+
assert_eq!(
1545+
sorted_days(&|_| true),
1546+
[
1547+
day("session-a", "2026-01-02"),
1548+
day("session-b", "2026-01-02"),
1549+
day("session-b", "2026-01-03"),
1550+
]
1551+
);
1552+
assert_eq!(
1553+
sorted_days(&|entry| entry.date != "2026-01-02"),
1554+
[day("session-b", "2026-01-03")]
1555+
);
1556+
}
1557+
15411558
#[test]
15421559
fn dedupes_sidechain_replay_after_an_equal_copy_from_another_session() {
15431560
let mut deduped_indexes = Default::default();

‎rust/adapters/opencode/src/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ SQLite databases are the primary source. Legacy JSON messages under `storage/mes
1616

1717
OpenCode v2 forks copy the parent's `session_message` rows with new ids but the same `seq`. When `session_v2.fork_session_id` and `fork_boundary` resolve against the parent's rows, fork rows at or below the last copied `seq` (the boundary for `through`, the parent's last row before it for `before`) are skipped as inherited history. The fork's `session_v2` counters start at zero and hold only fork-local usage, so they remain a valid session fallback. Unresolvable boundaries and pre-`seq` schemas keep every row.
1818

19-
The Claude Agent provider (`claude-agent`) runs Claude Code, which also writes its own transcript. Its v2 rows record that Claude Code session as `content[].native.sessionID`, which `load_entries_with_native_sessions` returns with each entry. Unified daily-family reports drop a row when the Claude source counted main-thread usage of that session on the row's date, in the Claude source's timezone and date range; session reports match whole sessions, since a Claude session row holds all of its usage, using the session ID the transcript records rather than its file name. A resumed or forked transcript repeats earlier turns, sometimes under the original session ID, and Claude's dedup keeps one copy of each. `should_replace_deduped_entry` prefers main-thread copies, then more tokens, then a copy with speed metadata over one without (the daily loader's `should_replace_deduped_daily_entry` compares cost before speed); only among copies equal on all of these does the first read win, with files sorted by path and named by UUID, so which transcript keeps a turn is effectively arbitrary; when all of them are reported, the choice does not affect the total. A session with surviving main-thread usage under its own recorded ID counts as included when the report includes every transcript holding that usage; copies it lost to other sessions are not consulted. A session with no surviving main-thread usage of its own counts as included when every transcript holding its kept copies is included. When a Claude date window includes only some of the transcripts involved, a repeated turn can go either way: a skipped session's rows for it are dropped although its kept copy is in an excluded transcript, or a session keeps its rows when the usage that decides it (its own surviving main-thread usage, or its kept copies when it has none) spans included and excluded transcripts, so the turns Claude counts in the included transcript are counted twice. The usage is then priced by the resolved model ID rather than the `opus`/`sonnet` alias OpenCode stores. The match is per session or session day, not per turn: `native.messageID` is the transcript line `uuid`, and one OpenCode row sums several API calls, so rows do not map one-to-one to Claude entries. This relies on the transcript holding every main-thread turn OpenCode records for that session; it also holds turns OpenCode drops, such as interrupted steps saved with `tokens: null`. A row is dated by its turn's start while Claude dates each call, so in daily-family reports a turn that crosses midnight in the Claude source's timezone is counted by both sources when Claude has no usage of that session on the earlier day, and with `--until` on that day the calls Claude logs after midnight are left out although OpenCode dates the whole turn on the earlier day. Only v2 `session_message` rows can carry the link: OpenCode added the provider after moving to SQLite v2, so legacy JSON messages and the v1 `message` table hold no `claude-agent` rows. `ccusage opencode` runs through `ccusage_adapter_all::run_opencode`, which matches by session day in every report kind, as `ccusage claude session` counts only in-window days, so focused reports add up to the unified daily one; it reads Claude only when a loaded row carries a native session, treats an unreadable Claude source as counting nothing, and `--include-claude-agent` keeps every row. `opencode::run` keeps every row.
19+
The Claude Agent provider (`claude-agent`) runs Claude Code, which also writes its own transcript. Its v2 rows record that Claude Code session as `content[].native.sessionID`, which `load_entries_with_native_sessions` returns with each entry. Unified daily-family reports drop a row when the Claude source counted main-thread usage of that session on the row's date, in the Claude source's timezone and date range; session reports drop a row when the Claude source counted in-window main-thread usage of that session and the row's date is in the Claude source's date range, since a Claude session row holds only its in-window usage. Both match the session ID the transcript records rather than its file name. A resumed or forked transcript repeats earlier turns, sometimes under the original session ID, and Claude's dedup keeps one copy of each; as in the daily loader, the session of a dropped copy counts on the day of the kept one. The usage is then priced by the resolved model ID rather than the `opus`/`sonnet` alias OpenCode stores. The match is per session or session day, not per turn: `native.messageID` is the transcript line `uuid`, and one OpenCode row sums several API calls, so rows do not map one-to-one to Claude entries. This relies on the transcript holding every main-thread turn OpenCode records for that session; it also holds turns OpenCode drops, such as interrupted steps saved with `tokens: null`. A row is dated by its turn's start while Claude dates each call, so in daily-family reports a turn that crosses midnight in the Claude source's timezone is counted by both sources when Claude has no usage of that session on the earlier day, and with `--until` on that day the calls Claude logs after midnight are left out although OpenCode dates the whole turn on the earlier day. Only v2 `session_message` rows can carry the link: OpenCode added the provider after moving to SQLite v2, so legacy JSON messages and the v1 `message` table hold no `claude-agent` rows. `ccusage opencode` runs through `ccusage_adapter_all::run_opencode`, which matches by session day in every report kind, as `ccusage claude session` counts only in-window days, so focused reports add up to the unified daily one; it reads Claude only when a loaded row carries a native session, treats an unreadable Claude source as counting nothing, and `--include-claude-agent` keeps every row. `opencode::run` keeps every row.
2020

2121
Token mapping:
2222

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

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -840,15 +840,24 @@ fn filtered_pi_format_agent_rows(
840840
enum ClaudeCounted {
841841
/// Daily-family reports count usage on the day Claude logged it.
842842
SessionDays(claude::SessionDays),
843-
/// A session report counts a session whole, every day included.
843+
/// A session report counts every session with in-window usage.
844844
Sessions(HashSet<Arc<str>>),
845845
}
846846

847847
impl ClaudeCounted {
848-
fn covers(&self, session: &Arc<str>, date: impl FnOnce() -> String) -> bool {
848+
fn covers(
849+
&self,
850+
session: &Arc<str>,
851+
date: impl FnOnce() -> String,
852+
claude: &SharedArgs,
853+
) -> bool {
849854
match self {
850855
Self::SessionDays(days) => days.contains(&(Arc::clone(session), date())),
851-
Self::Sessions(sessions) => sessions.contains(session),
856+
// Claude counts only the session's in-window days, so a row outside them stays.
857+
Self::Sessions(sessions) => {
858+
sessions.contains(session)
859+
&& date_within_range(&date(), claude.since.as_deref(), claude.until.as_deref())
860+
}
852861
}
853862
}
854863
}
@@ -887,15 +896,27 @@ fn load_claude_rows(
887896
project_filter: Option<&str>,
888897
) -> Result<(AgentRows, ClaudeCounted)> {
889898
if kind == AgentReportKind::Session {
899+
// Like `ccusage claude session`, a session counts only its in-window usage.
890900
let deduped = claude::load_deduped_entries(shared, project_filter)?;
891901
let detected = !deduped.entries.is_empty();
892-
let mut summaries = summarize_entry_sessions(&deduped.entries)?;
893-
filter_session_summaries_by_last_activity(&mut summaries, shared);
894-
let counted_sessions = summaries
895-
.iter()
896-
.filter_map(|summary| summary.session_id.as_deref())
897-
.collect::<BTreeSet<_>>();
898-
let sessions = deduped.main_thread_sessions(|session| counted_sessions.contains(session));
902+
let in_window = |entry: &LoadedEntry| {
903+
date_within_range(
904+
&entry.date,
905+
shared.since.as_deref(),
906+
shared.until.as_deref(),
907+
)
908+
};
909+
let sessions = deduped
910+
.main_thread_session_days(in_window)
911+
.into_iter()
912+
.map(|(session, _)| session)
913+
.collect();
914+
let entries = deduped
915+
.entries
916+
.into_iter()
917+
.filter(|entry| in_window(entry))
918+
.collect::<Vec<_>>();
919+
let summaries = summarize_entry_sessions(&entries)?;
899920
return Ok((
900921
AgentRows {
901922
rows: summary_rows("claude", summaries, false),
@@ -945,9 +966,11 @@ fn without_turns_counted_by_claude(
945966
.into_iter()
946967
.filter(|(entry, native_session)| {
947968
native_session.as_ref().is_none_or(|session| {
948-
!claude_counted.covers(session, || {
949-
format_date_tz(entry.timestamp, claude_tz.as_ref())
950-
})
969+
!claude_counted.covers(
970+
session,
971+
|| format_date_tz(entry.timestamp, claude_tz.as_ref()),
972+
claude_shared,
973+
)
951974
})
952975
})
953976
.map(|(entry, _)| entry)

0 commit comments

Comments
 (0)