nanocoder icon indicating copy to clipboard operation
nanocoder copied to clipboard

[Bug] The `read_file` cache has no byte limit and keeps expired entries: ten 20 MB files cost about 410 MB of RSS

Open addyCooks opened this issue 1 month ago • 2 comments

Description

getCachedFileContent keeps up to 50 files, and each entry stores the file as a string and again as a lines array. There is no byte limit, and entries past the 5 s TTL are only removed if that exact path is read again. A few big log or data files stay in memory for the rest of the session. read_file returns at most 1,500 lines (or a 250-line preview) but loads the whole file first.

Environment

  • OS: Windows 11 (10.0.26300)
  • Node version: 22.22.3
  • Nanocoder version: 1.31.0 (main at 5c2e6935)

Steps to Reproduce

  1. Create 10 text files of 20 MB each.
  2. In a script run with --expose-gc, call getCachedFileContent() from dist/utils/file-cache.js on each, then gc() and print process.memoryUsage().
  3. Wait 6 s (the TTL is 5 s) and print getCacheSize() and the heap again.

Evidence

  • Heap +320 MB, external +80 MB, RSS +410 MB (about 20x the file size).
  • Six seconds later the cache still holds all 10 entries and the heap is unchanged.
  • source/utils/file-cache.ts:14 (MAX_CACHE_SIZE = 50), source/constants.ts:34 (CACHE_FILE_TTL_MS = 5000), and readAndCacheFile (around lines 110-170). With 50 entries this is 50x worse by construction; I did not run that case.

Proposed Change

  • Add a total byte budget (for example 32 MB) with LRU eviction by bytes, and skip caching files above a size threshold.
  • Build lines lazily, or keep only content and split on demand.
  • Sweep expired entries on insert or with an unref'd timer.
  • For huge files, read only the requested range instead of the whole file.

Expected Behavior

  • The 10 x 20 MB case stays below the byte budget plus a few MB of RSS.
  • Entries older than the TTL are gone after the next insertion without being re-read.
  • Existing file-cache.spec.ts behaviour (dedupe of concurrent reads, mtime invalidation) is unchanged.

Additional Context

  • Effort: S. Start with source/utils/file-cache.ts and source/tools/read-file.tsx.
  • Earlier race fixes (#840, #735) live here, so keep the pending-read de-duplication. Specs: file-cache.spec.ts, read-file.spec.tsx.

addyCooks avatar Oct 15 '26 15:10 addyCooks

@addyCooks @bigattichouse kindly assign this issue to me

aakash-env avatar Oct 15 '26 16:10 aakash-env

go ahead @aakash-env !

addyCooks avatar Oct 15 '26 16:10 addyCooks