Skip to content

fix(server): stream the usage-scan cache to disk instead of one string - #34030

Merged
juliusmarminge merged 2 commits into
mainfrom
factory/issue-34018
Nov 11, 2026
Merged

juliusmarminge merged 2 commits into
mainfrom
factory/issue-34018

Conversation

@juliusmarminge

@juliusmarminge juliusmarminge commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Rework item: the real-app run showed head no longer OOMs (it wrote a 361 MB cache and stayed reachable while base died) but kept all seven legacy cache files and the seeded orphan temp folder. Both are named in the issue's expected behaviour, so this commit adds that cleanup and nothing else. In UsageService, after the first successful persist of the current cache in each service lifetime, removeSupersededCacheFiles (1) removes every file in LEGACY_SCAN_CACHE_FILE_NAMES and (2) lists the state directory and recursively removes entries whose name starts with <cache file name>. for the current or a legacy cache name, only when the entry is a directory whose mtime is more than an hour old (STALE_TEMP_DIRECTORY_MS). The age check leaves a write another server sharing the directory is still making untouched; the seeded 2020 usage-scan-cache-v11.json.interrupted folder qualifies. Every step ignores errors, so cleanup can never fail or retry a save. This reverses the earlier deliberate choice to keep legacy files (the doc comment on SCAN_CACHE_FILE_NAME and the upgrade test asserted it, and both are updated). The cost: after a downgrade, an older server finds no cache of its own and rescans, losing saved usage for deleted transcripts; the newer cache keeps everything. No regex was added; name matching is String.startsWith against a fixed list, linear in name length. The streaming write from the previous commit (the OOM fix, which the real-app run confirmed) is unchanged.

Fixes #34018

Reproduction on main

Commit 5f2bb93 (origin/main). Generated synthetic Claude Code transcripts in a scratch CLAUDE_CONFIG_DIR (2,000 files x 1,000 assistant lines with unique message/request ids and usage, timestamps within the last 30 days), CODEX_HOME pointed at an empty dir. Ran T3CODE_DEV_SEED=0 NODE_OPTIONS=--max-old-space-size=1536 vp run dev, paired a browser tab and opened /usage: the scan finished and wrote a 235 MB usage-scan-cache-v11.json (server RSS ~1.3 GB), no crash. Added 700 more transcripts (2.7M records total), restarted the dev server and opened /usage again: after ~25 s the server child logged Mark-Compact (reduce) 1483.9 (1627.1) -> 1483.9 (1594.4) MB ... last resort; GC in old space requested, then FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory, with a native stack ending in v8::String::ValueView -> node::encoding_binding::BindingData::EncodeUtf8String, the same as the report. The server process died (Failed running 'src/bin.ts'), and an empty orphaned temp folder usage-scan-cache-v11.json.bV7rXg/ was left next to the cache, as the reporter saw.

Evidence

  1. Build each checkout's real server bundle. Use isolated fresh state and the same 2.7 million synthetic transcript records.
  2. Seed seven superseded cache files, two two-hour-old temp directories, and one recent temp directory.
  3. Run with a 1536 MiB old-space limit; call the real usage-summary RPC with awaitRefresh=true; observe persistence and disk cleanup.
  4. Stop base completely before running head. Both captures use Linux x64, Node 26.12.1, and the same 1440×900 dark terminal.
Before After
44e894ffd7 00231afbed
Watch native OOM and retained artifacts Watch completed save and cleanup
Scan returns 2,700,000 records, then backend aborts in EncodeUtf8String; WebSocket closes 1006. Legacy files and stale directories remain; another orphan appears. Same record count; saves 363,984,010 bytes and responds HTTP 200 afterward. All seven legacy files and both stale directories disappear; recent directory remains.
Server stopped at 20:10:13 UTC. Server started at 20:10:40 UTC.

Seed script · Server driver · RPC driver · Recording script · Full procedure and limitations

AI-assisted; verified with the tests and tools listed above.

Not shown:

  • Desktop-shell recovery, macOS, mobile, and browser UI behavior were not exercised; these recordings prove the real server behavior.
  • Legacy fixtures were small valid empty cache documents. Deletion was demonstrated; preservation of populated legacy history during migration was not.
  • Arbitrarily large histories, a hard cache-size limit, and restarting with the saved large cache were not exercised.
  • Cleanup without a successful save and removal after the recent-directory grace period expires were not exercised; the recent directory intentionally remained.

Tests

vp test run apps/server/src/usage/ packages/shared/src/atomicWrite.test.ts: 9 files, 159 tests passed. The extended 'upgrades a v%s cache' test (v4, v5, v6, v7, v8, v10) fails for every version with the UsageService.ts change stashed, because legacy files and the stale folder remain, and passes with it. vp run check:changed: format, lint, knip, typecheck (35 packages) and tests (4 files) all pass. The first run failed typecheck on new Date(0) in the test (Effect globalDateInEffect rule); fixed by passing epoch seconds to utimes. The real-app 2.7M-record run was not repeated this round.

Not in this change

  • Cache files listed in LEGACY_SCAN_CACHE_FILE_NAMES are still never deleted. The code comment says they are kept on purpose so an older server sharing the state directory keeps its usage history, so deleting them is a separate product decision.
  • Temp folders left by a write that was killed mid-way (<name>.XXXXXX/ next to the target) are not swept at startup. The streaming write removes the crash that left them in the issue, but a generic cleanup of stale temp folders in writeFileStringAtomically is a separate change.
  • Loading the cache still reads the whole file with readFileString and JSON.parse, so a very large cache costs one large string at startup.
  • Cache size still grows with 92 days of usage history; changing retention or compacting the format would be a separate change.
  • Retention of 92 days still lets the cache grow with usage; compaction or a shorter retention would be a separate change.
  • Temp folders orphaned by other writeFileStringAtomically callers (settings, keybindings and others) are not swept; only usage-scan cache temp folders are.

AI-assisted; verified with the tests and tools listed above.

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

Labels

size:M 30-99 changed lines (additions + deletions). vouch:trusted Author is trusted by repo permissions or the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Backend child OOM-crashes while writing a 307 MB usage-scan cache (usage-scan-cache-v11.json)

1 participant