Skip to content

Commit 8d2d1ce

Browse files
committed
fix: sort unified sessions by descending cost
Restore the documented highest-cost-first session order, including session sections in combined reports. Use session ID and agent as deterministic tie breakers and preserve period report ordering. Cover JSON/table output, combined sections, ties, empty and single rows, and chronological period sorting. Fixes #1718
1 parent 1b4f423 commit 8d2d1ce

2 files changed

Lines changed: 140 additions & 1 deletion

File tree

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

Lines changed: 84 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,12 @@ fn finish_rows(kind: AgentReportKind, mut rows: Vec<AllRow>, shared: &SharedArgs
400400
for row in &mut rows {
401401
row.metadata_agents = None;
402402
}
403-
sort_rows(&mut rows, &shared.order);
403+
rows.sort_by(|a, b| {
404+
b.total_cost
405+
.total_cmp(&a.total_cost)
406+
.then_with(|| a.period.cmp(&b.period))
407+
.then_with(|| a.agent.cmp(b.agent))
408+
});
404409
return rows;
405410
}
406411

@@ -922,6 +927,84 @@ mod tests {
922927
}
923928
}
924929

930+
fn sorting_row(period: &str, agent: &'static str, cost: f64) -> AllRow {
931+
let mut summary = usage_summary(period, 10);
932+
summary.total_cost = cost;
933+
summary_rows(agent, vec![summary], false).pop().unwrap()
934+
}
935+
936+
#[test]
937+
fn session_cost_order_uses_id_then_agent_for_ties() {
938+
for order in [crate::cli::SortOrder::Asc, crate::cli::SortOrder::Desc] {
939+
let rows = vec![
940+
sorting_row("b-tie", "codex", 20.0),
941+
sorting_row("a-zero", "claude", 0.0),
942+
sorting_row("z-tie", "claude", 20.0),
943+
sorting_row("b-tie", "claude", 20.0),
944+
sorting_row("c-cheap", "codex", 1.0),
945+
];
946+
let shared = SharedArgs {
947+
order,
948+
..SharedArgs::default()
949+
};
950+
let sorted = finish_rows(AgentReportKind::Session, rows, &shared);
951+
let keys: Vec<_> = sorted
952+
.iter()
953+
.map(|row| (row.period.as_str(), row.agent))
954+
.collect();
955+
assert_eq!(
956+
keys,
957+
[
958+
("b-tie", "claude"),
959+
("b-tie", "codex"),
960+
("z-tie", "claude"),
961+
("c-cheap", "codex"),
962+
("a-zero", "claude"),
963+
]
964+
);
965+
}
966+
}
967+
968+
#[test]
969+
fn session_cost_order_handles_empty_and_single_row_reports() {
970+
let shared = SharedArgs::default();
971+
assert!(finish_rows(AgentReportKind::Session, Vec::new(), &shared).is_empty());
972+
let rows = finish_rows(
973+
AgentReportKind::Session,
974+
vec![sorting_row("only-session", "claude", 0.0)],
975+
&shared,
976+
);
977+
assert_eq!(rows.len(), 1);
978+
assert_eq!(rows[0].period, "only-session");
979+
}
980+
981+
#[test]
982+
fn period_reports_keep_chronological_order_regardless_of_cost() {
983+
for kind in [
984+
AgentReportKind::Daily,
985+
AgentReportKind::Weekly,
986+
AgentReportKind::Monthly,
987+
] {
988+
for (order, expected_costs) in [
989+
(crate::cli::SortOrder::Asc, [1.0, 20.0, 3.0]),
990+
(crate::cli::SortOrder::Desc, [3.0, 20.0, 1.0]),
991+
] {
992+
let rows = vec![
993+
sorting_row("2026-03-02", "claude", 3.0),
994+
sorting_row("2026-01-05", "claude", 1.0),
995+
sorting_row("2026-02-02", "claude", 20.0),
996+
];
997+
let shared = SharedArgs {
998+
order,
999+
..SharedArgs::default()
1000+
};
1001+
let sorted = finish_rows(kind, rows, &shared);
1002+
let costs: Vec<_> = sorted.iter().map(|row| row.total_cost).collect();
1003+
assert_eq!(costs, expected_costs, "{kind:?} {order:?}");
1004+
}
1005+
}
1006+
}
1007+
9251008
#[test]
9261009
fn filters_daily_summaries_with_compact_date_bounds() {
9271010
let mut rows = vec![

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

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,62 @@ fn renders_multi_section_json_keys_in_invoked_section_order_with_totals_last() {
538538
);
539539
}
540540

541+
#[test]
542+
fn unified_sessions_rank_highest_cost_first_in_json_and_table() {
543+
let fixture = fs_fixture!({});
544+
for (id, cost) in [("a-cheap", 1.0), ("m-medium", 3.0), ("z-expensive", 20.0)] {
545+
let _ = fixture.write_file(
546+
format!("projects/project-a/{id}.jsonl"),
547+
json!({
548+
"timestamp": "2099-01-02T00:00:00.000Z",
549+
"sessionId": id,
550+
"requestId": id,
551+
"costUSD": cost,
552+
"message": {
553+
"id": id,
554+
"model": "claude-sonnet-4-20250514",
555+
"usage": {"input_tokens": 100, "output_tokens": 50}
556+
}
557+
})
558+
.to_string(),
559+
);
560+
}
561+
let _env = isolated_agent_env(
562+
&fixture,
563+
"CLAUDE_CONFIG_DIR",
564+
fixture.root().as_os_str().into(),
565+
);
566+
let shared = SharedArgs {
567+
mode: CostMode::Display,
568+
..fixture_shared("20990101", "20990103")
569+
};
570+
571+
let result = load_rows(AgentReportKind::Session, &shared).unwrap();
572+
let report = report_json(&result.rows, AgentReportKind::Session);
573+
let ids: Vec<_> = report["session"]
574+
.as_array()
575+
.unwrap()
576+
.iter()
577+
.map(|row| row["period"].as_str().unwrap())
578+
.collect();
579+
assert_eq!(ids, ["z-expensive", "m-medium", "a-cheap"]);
580+
assert_eq!(report["totals"]["totalCost"], 24.0);
581+
582+
let table = table_snapshot(
583+
&result.rows,
584+
AgentReportKind::Session,
585+
&result.detected_agents,
586+
);
587+
let table_ids: Vec<_> = table["rows"]
588+
.as_array()
589+
.unwrap()
590+
.iter()
591+
.map(|row| row["cells"][0].as_str().unwrap())
592+
.collect();
593+
assert_eq!(table_ids, ["z-expensive", "m-medium", "a-cheap", "Total"]);
594+
assert_daily_family_and_session_sections_match_standalone(&shared);
595+
}
596+
541597
#[test]
542598
fn multi_section_claude_fixture_matches_standalone_sections_for_daily_and_session_invocations() {
543599
let fixture = fs_fixture!({

0 commit comments

Comments
 (0)