Skip to content

fix(usage): never overwrite a corrupt usage rollup file - #2512

Merged
kevincodex1 merged 1 commit into
Twigpine:mainfrom
kevincodex1:fix/usage-rollup-corrupt-overwrite
Nov 13, 2026
Merged

kevincodex1 merged 1 commit into
Twigpine:mainfrom
kevincodex1:fix/usage-rollup-corrupt-overwrite

Conversation

@kevincodex1

@kevincodex1 kevincodex1 commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Fixes the GitHub Code Quality AI finding in saveUsageDayRollups (src/services/usage/rollups.ts). Saving rollups re-reads the month's file under the lock with "strict" parsing, but strict mode only threw for a file of another version. Malformed JSON, or JSON that is not an object, parsed to null and fell back to an empty file. That empty file was written over the existing rollup, which dropped archived days whose raw event files had already been pruned. This contradicted the comment above the read ("if the file cannot be read, rewriting it would drop days whose event files are already gone, so the save fails instead").
  • parseRollupFile now throws for every file it cannot use (malformed JSON, not an object, or another version), and the strict flag is removed:
    • readRollupFileChecked catches the error and reports the month as unreadable, as before.
    • saveUsageDayRollups fails instead of overwriting the file. getUsageDayRollups already catches save errors, so the totals it returns are unchanged.
    • appendToPrunedUsageDay still fails on an unreadable or missing file, with the same outcome as before; only the error message differs for a corrupt file.

Impact

  • user-facing impact: a damaged or hand-edited usage rollup file (~/.openclaude/usage/rollups/<YYYY-MM>.json) is no longer replaced, so archived usage for that month is kept and can still be recovered. /usage keeps showing "Could not read saved usage for " until the file is fixed or removed, instead of showing it once and then silently dropping those days. While the file is unreadable, rollups for that month are not saved and its event files are not pruned. This matches the existing behavior for rollup files from another version or without read permission.
  • developer/maintainer impact: parseRollupFile loses its strict parameter and always returns a UsageRollupFile or throws. Its three callers now handle errors through try/catch instead of null checks.

Testing

  • I followed Validation, including applicable lint/static/type checks and regression tests.
  • affected surfaces and selected checks: shared source and root tests (src/services/usage/), so the core checks, the compile-cache-disabled launcher check, focused regression tests for the usage service and its callers, and the PR intent scan.
  • for follow-ups, prior validated revision and unaffected results reused: none; this is the initial revision.
  • exact commands and results (Bun 1.4.4, Node 24.22.2, after bun install --frozen-lockfile):
    • bun run check:static: passed
    • bun run typecheck:fast: no type errors in 3,359 files
    • bun run typecheck:type-tests: passed (11 files)
    • node bin/openclaude --version and NODE_DISABLE_COMPILE_CACHE=1 node bin/openclaude --version: 0.36.0 (OpenClaude)
    • git diff --check: clean
    • bun run security:pr-scan -- --base FETCH_HEAD --head HEAD: no suspicious additions found
  • focused tests:
    • bun test src/services/usage/ src/components/Usage/: 104 pass, 0 fail
    • bun run test ./src/services/usage/rollups.test.ts ./src/services/usage/ledger.test.ts ./src/services/usage/query.test.ts: 65 pass, 0 fail
    • The test "never overwrites a rollup file written by another version" now runs three cases: another version, corrupt JSON, and JSON that is not an object. Each case also runs cleanup, then checks that the event file survives and the rollup file is unchanged byte for byte. Against the unfixed rollups.ts, the corrupt-JSON and non-object cases fail; with the fix all three pass.
  • inapplicable checks and reasons; blocked checks, platform limits, or verified pre-existing failures:
    • The full unit suite was not run locally because this is a focused fix in one module; CI runs all shards.
    • Website checks were not run because no site inputs changed.
    • VS Code extension checks were not run because the extension was not touched.
  • CI and CodeRabbit status (update before requesting maintainer review; link any justified declines or maintainer-approved exceptions): pending; to be updated once CI and CodeRabbit have run.

Notes

  • provider/model path tested: none; local usage storage only, no provider or model path involved.
  • screenshots attached (if UI changed): none; no UI change.
  • follow-up work or known limitations: the /usage note names the unreadable month but not the file path. Adding the path would help users fix it and could be a small follow-up.

Summary by CodeRabbit

  • Bug Fixes
    • Usage summaries can now be rebuilt from recorded events when saved summary data is unreadable or from an unsupported version.
    • Cleanup preserves recorded events in these cases, and unreadable summary files are left unchanged rather than being overwritten.
    • Attempts to save or append to missing or unreadable summary files are now rejected, helping prevent accidental loss of usage data.

Saving rollups re-reads the month's file under the lock in strict mode,
but strict parsing only threw for another version. Malformed JSON or
JSON that is not an object parsed to null, fell back to an empty file and
was written over the existing rollup, dropping archived days whose event
files had already been pruned.

parseRollupFile now throws for every file it cannot use, and the reader
catches that to report the month as unreadable, so the strict flag goes
away. The save fails instead, and cleanup keeps the event files because
their totals were never saved.

Co-Authored-By: OpenClaude <openclaude@gitlawb.com>
@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Rollup parsing now throws for malformed JSON, non-object JSON, and unsupported versions. Checked reads return an empty unreadable rollup on read or parse errors. Save and append paths use the throwing parser, and tests cover preservation of invalid rollup files.

Changes: Rollup handling

Layer / File(s) Summary
Parse and read rollups
src/services/usage/rollups.ts
parseRollupFile throws for malformed JSON, non-object values, and unsupported versions. readRollupFileChecked logs read or parse errors and returns an empty unreadable rollup.
Save, append, and test invalid rollups
src/services/usage/rollups.ts, src/services/usage/rollups.test.ts
Save and append paths parse existing rollups directly. Tests cover newer-version, truncated, and non-object files; they verify that usage is rebuilt from events, cleanup removes no events, and rollup contents remain unchanged.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: jatmn

Merge Risk: Minimal · up to e8e17

This change stops a corrupt or newer-version usage rollup file from being overwritten with an empty one, so archived usage days are no longer lost. Regression tests cover the main invalid-file cases. No merge-blocking risk was found; CI results were still pending.

Pre-merge checks: Passed 6

Check name Status Explanation
Title check Passed The title "fix(usage): never overwrite a corrupt usage rollup file" matches the main change. parseRollupFile now throws for malformed JSON, non-object JSON, and other versions, and saves fail instead …
Description check Passed The description follows the template. It has Summary, Impact, Testing, and Notes sections, and each is filled in with specific content. The Testing section lists exact commands, results, focused tests…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Risk Surface Disclosed Passed The check applies only when a PR touches auth, provider routing, permissions, outbound network behavior, background execution, startup/config-home behavior, skills/plugins/MCP, CI permissions, or rele…
No Hidden Policy Change Passed The PR changes two files: src/services/usage/rollups.ts and src/services/usage/rollups.test.ts. The diff is a focused parser fix. parseRollupFile now throws for malformed JSON, non-object JSON, …
Full details: Title check

Explanation

The title "fix(usage): never overwrite a corrupt usage rollup file" matches the main change. parseRollupFile now throws for malformed JSON, non-object JSON, and other versions, and saves fail instead of overwriting an unreadable rollup file. The title is concise, scoped to the usage module, and reflects the diff.

Full details: Description check

Explanation

The description follows the template. It has Summary, Impact, Testing, and Notes sections, and each is filled in with specific content. The Testing section lists exact commands, results, focused tests, and reasons for skipped checks. CI and CodeRabbit status is marked pending, which the template allows before maintainer review. Non-blocking: the description says the test runs three cases, but the summary does not mention the test rename or its scope change. The provider/model path field is filled as 'none' with a reason.

Full details: Risk Surface Disclosed

Explanation

The check applies only when a PR touches auth, provider routing, permissions, outbound network behavior, background execution, startup/config-home behavior, skills/plugins/MCP, CI permissions, or release scripts. The complete PR range (git diff --name-status against the review base) changes two files: src/services/usage/rollups.ts and src/services/usage/rollups.test.ts. None of the listed surfaces is touched. The rollups.ts diff changes only local usage-rollup parsing. parseRollupFile now throws instead of returning null. saveUsageDayRollups and appendToPrunedUsageDay now fail on unreadable files. The rollup file lives under the ~/.openclaude/usage/rollups/ config-home directory. The diff does not change how the config home is resolved, read at startup, or initialized, so this is not startup/config-home behavior. It adds no network calls, permission changes, provider or auth logic, skill/plugin/MCP code, CI workflow, or release-script edits. The behavior change is that saves and appends now fail on corrupt files, so pruning is skipped for that month until the file is repaired. The PR description discloses this. It is a data-retention effect, not one of the listed risk surfaces. The current review reports zero actionable findings, which is consistent with this scope. Because no listed surface changed, no risk-surface callout is required, and no blocker arises under this check.

Full details: No Hidden Policy Change

Explanation

The PR changes two files: src/services/usage/rollups.ts and src/services/usage/rollups.test.ts. The diff is a focused parser fix. parseRollupFile now throws for malformed JSON, non-object JSON, and other-version files, and the strict flag is removed. No product, trust-model, routing-default, telemetry/network, or permission-policy code is touched. No network, telemetry, or permission code appears in the diff. The behavior change is that saves and appends now fail on corrupt rollup files instead of overwriting them. The PR description discloses this under "Impact". The change also matches the behavior the code already had for other-version files, and the existing comment in saveUsageDayRollups already states that saves should fail when a file cannot be read. This is a disclosed bug fix, not a policy change hidden in cleanup. Blocking issues: none. Non-blocking note: the change extends an existing retention effect to corrupt files. While a month's rollup file is unreadable, its event files are not pruned. The PR description states this explicitly. A maintainer may still want to confirm that this retention behavior is the intended product outcome.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between f3e16ab and e8e17a4.

Files selected for processing: 2

  • src/services/usage/rollups.test.ts
  • src/services/usage/rollups.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Recent review details

Context from checks skipped due to timeout: 8

  • GitHub Check: CodeRabbit
  • GitHub Check: unit-tests (5)
  • GitHub Check: unit-tests (4)
  • GitHub Check: unit-tests (1)
  • GitHub Check: unit-tests (7)
  • GitHub Check: unit-tests (6)
  • GitHub Check: unit-tests (2)
  • GitHub Check: CodeQL (javascript-typescript)
Additional context used

Path-based instructions: 3

Review tests for meaningful coverage of the changed behavior, isolation of global/env/config state, async cleanup, fake timers, provider profile leaks, and Windows-compatible assumptions.

CodeRabbit configuration file

Files:

  • src/services/usage/rollups.test.ts
Apply the OpenClaude maintainer review rubric from AGENTS.md.

CodeRabbit configuration file

Files:

  • src/services/usage/rollups.test.ts
  • src/services/usage/rollups.ts
Source excerpt: No hidden policy change: Verify that product, trust-model, routing-default, telemetry/network, and permission-policy changes are not hidden inside unrelated cleanup.

CodeRabbit inference engine (Custom checks)

Files:

  • src/services/usage/rollups.test.ts
  • src/services/usage/rollups.ts
Learnings: 1

Common learnings

Learnt from: CR
Repo: Twigpine/openclaude PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-10-29T17:48:03.316Z
Learning: Source excerpt:
# AGENTS.md - AI Agent Coding Guide

## Work Style

- Add or update tests when behavior changes.
Additional comments: 2

src/services/usage/rollups.ts: 1

120-123: LGTM!

Also applies to: 125-128, 132-132, 152-154, 287-287, 329-330

src/services/usage/rollups.test.ts: 1

280-284: LGTM!

Also applies to: 287-287, 291-297, 299-299

@kevincodex1
kevincodex1 merged commit 520c6fa into Twigpine:main Nov 13, 2026
28 checks passed
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