Skip to content

feat: add cache hit rate column to all usage report commands#918

Open
BuluBulugege wants to merge 1 commit intoryoppippi:mainfrom
BuluBulugege:feat/cache-hit-rate
Open

feat: add cache hit rate column to all usage report commands#918
BuluBulugege wants to merge 1 commit intoryoppippi:mainfrom
BuluBulugege:feat/cache-hit-rate

Conversation

@BuluBulugege
Copy link
Copy Markdown

@BuluBulugege BuluBulugege commented Mar 31, 2026

Summary

  • Add Hit Rate as a first-class metric column in daily, monthly, weekly, and session reports
  • Formula: CacheRead / (Input + CacheCreate + CacheRead), color-coded: green (>=70%), yellow (>=40%), red (<40%)
  • Hit Rate is shown in both full and compact mode (as a core metric)
  • JSON output includes cacheHitRate field for programmatic access
  • Model breakdown (-b) also displays per-model hit rate

Test plan

  • ccusage daily — verify Hit Rate column appears
  • ccusage session — verify Hit Rate column with Last Activity
  • ccusage daily --json — verify cacheHitRate in JSON output
  • ccusage daily --compact — verify Hit Rate in compact mode
  • ccusage daily -b — verify per-model hit rate in breakdown rows

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

New Features

  • Added cache hit rate metrics to all usage reports (daily, weekly, monthly, and session views), displayed as percentages with color-coded indicators: green for optimal performance (≥70%), yellow for adequate (≥40%), and red for lower rates.
  • Cache hit rate data is now included in both visual reports and JSON output formats.

Add Hit Rate as a first-class metric alongside Input/Output/Cache columns
in daily, monthly, weekly, and session reports. The hit rate is calculated
as CacheRead / (Input + CacheCreate + CacheRead), color-coded green (>=70%),
yellow (>=40%), or red (<40%). Also included in compact mode and JSON output.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 31, 2026

📝 Walkthrough

Walkthrough

This pull request adds cache hit rate computation and visualization across multiple usage reporting commands. A new calculateCacheHitRate function computes cache efficiency as a percentage, with a corresponding formatting function that applies color-coding based on performance thresholds. The metric is integrated into JSON outputs for daily, monthly, session, and weekly reports, with table layouts adjusted to accommodate the new column.

Changes

Cohort / File(s) Summary
Core Table Utilities
packages/terminal/src/table.ts
Added calculateCacheHitRate() helper and formatCacheHitRate() function with color-coded thresholds (green ≥70%, yellow ≥40%, red otherwise). Integrated "Hit Rate" column into usage breakdown and report rows.
Command Reporting Updates
apps/ccusage/src/commands/daily.ts, apps/ccusage/src/commands/monthly.ts, apps/ccusage/src/commands/session.ts, apps/ccusage/src/commands/weekly.ts
Added cache hit rate computation to JSON output for each command via calculateCacheHitRate(data). Adjusted table separator row indices (8→9 or 9→10) to align with expanded column count.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • Add weekly usage command #378: Introduces the weekly command aggregation structure that is now enhanced in this PR with cache hit rate computation and column adjustments.

Suggested reviewers

  • ryoppippi

Poem

🐰 A cache hit rate so fine,
Green, yellow, red—colors align!
Five commands now shine with metrics bright,
Efficiency tracked with delight!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately and concisely summarizes the main change: adding a cache hit rate column across all usage report commands (daily, monthly, weekly, session).
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/ccusage/src/commands/daily.ts (1)

102-125: ⚠️ Potential issue | 🟠 Major

Add cacheHitRate to grouped project JSON output.

The --instances --json path omits cacheHitRate while the non-grouped --json path includes it, creating inconsistent JSON schemas. Add cacheHitRate: calculateCacheHitRate(data) to the object pushed in groupByProject() (line 30 of _daily-grouping.ts), and update the DailyProjectOutput type in _json-output-types.ts to include the field.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/ccusage/src/commands/daily.ts` around lines 102 - 125, The grouped JSON
path is missing cacheHitRate: add cacheHitRate: calculateCacheHitRate(data) to
the object that groupByProject pushes for each day in _daily-grouping.ts (ensure
calculateCacheHitRate is imported/accessible there), and update the
DailyProjectOutput type in _json-output-types.ts to include cacheHitRate (number
or nullable number consistent with other fields) so the grouped (--instances
--json) schema matches the non-grouped JSON output.
🧹 Nitpick comments (1)
packages/terminal/src/table.ts (1)

523-552: Avoid formula duplication between formatCacheHitRate and calculateCacheHitRate.

Keep one source of truth for the formula to prevent future drift.

♻️ Suggested refactor
 export function formatCacheHitRate(data: {
 	inputTokens: number;
 	cacheCreationTokens: number;
 	cacheReadTokens: number;
 }): string {
-	const totalInput = data.inputTokens + data.cacheCreationTokens + data.cacheReadTokens;
-	const rate = totalInput > 0 ? data.cacheReadTokens / totalInput : 0;
+	const rate = calculateCacheHitRate(data);
 	const pct = `${(rate * 100).toFixed(1)}%`;
 	if (rate >= 0.7) {
 		return pc.green(pct);
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/terminal/src/table.ts` around lines 523 - 552, The cache-hit
calculation logic is duplicated between formatCacheHitRate and
calculateCacheHitRate; change formatCacheHitRate to call
calculateCacheHitRate(data) to obtain the rate and then perform
formatting/threshold checks (pct string and color selection) so the numeric
formula lives only in calculateCacheHitRate; update any variable names
accordingly and remove the duplicated arithmetic in formatCacheHitRate so
calculateCacheHitRate is the single source of truth for the rate.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@apps/ccusage/src/commands/daily.ts`:
- Around line 102-125: The grouped JSON path is missing cacheHitRate: add
cacheHitRate: calculateCacheHitRate(data) to the object that groupByProject
pushes for each day in _daily-grouping.ts (ensure calculateCacheHitRate is
imported/accessible there), and update the DailyProjectOutput type in
_json-output-types.ts to include cacheHitRate (number or nullable number
consistent with other fields) so the grouped (--instances --json) schema matches
the non-grouped JSON output.

---

Nitpick comments:
In `@packages/terminal/src/table.ts`:
- Around line 523-552: The cache-hit calculation logic is duplicated between
formatCacheHitRate and calculateCacheHitRate; change formatCacheHitRate to call
calculateCacheHitRate(data) to obtain the rate and then perform
formatting/threshold checks (pct string and color selection) so the numeric
formula lives only in calculateCacheHitRate; update any variable names
accordingly and remove the duplicated arithmetic in formatCacheHitRate so
calculateCacheHitRate is the single source of truth for the rate.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a0bfdabf-9d95-4731-955e-17c465e9627c

📥 Commits

Reviewing files that changed from the base of the PR and between 61ee04d and f09fa94.

📒 Files selected for processing (5)
  • apps/ccusage/src/commands/daily.ts
  • apps/ccusage/src/commands/monthly.ts
  • apps/ccusage/src/commands/session.ts
  • apps/ccusage/src/commands/weekly.ts
  • packages/terminal/src/table.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant