fix(workspace-fs): prune a new gitignored dir as soon as chokidar sees it

Merged
SA
7d ago
+377-30

What & why

#9896 made host-service stop watching a gitignored directory that appears after a watch attaches (Linux / chokidar). On a real bun install on a cloud box, that fix removed the watches but did not give the memory back. The live host-service stayed at 1,444 MB RSS (heapUsed 109 MB) 6 min after the install. On an 8 GB box that is what drives it into swap.

This PR stops chokidar from creating those watches at all: the manager asks git about each new directory when chokidar reports it, and chokidar's ignored callback uses the answer. With the same real install, peak RSS goes from 1,350–1,525 MB to 506 MB, and RSS at +6 min is 244 MB, below the attached baseline (377 MB).

Follows #9896 and #9868 (plans/20261117-host-service-memory.md, fix 1).

Diagnosis: where the 1.3 GB was

Measured on the live host-service of a 4 vCPU / 8 GB cloud box (released bundle 2.0.9+81d68fcd, node v24.22.3), after #9896's run B (watch attached, then node_modules deleted and a real bun install run). The watch count was already back to 22,332.

/proc/<pid>/smaps, grouped by mapping:

GroupRSSMappings
Anonymous 256 KB mappings (V8 heap page size)1,153 MB4,645
Other anonymous (64 MB-aligned glibc arenas, stacks, …)64 MB80
[heap] (glibc brk arena)143 MB1
File-backed (node binary, libs)41 MB55
Total (smaps_rollup Rss)1,434 MB

The same process reported rss 1444 / heapTotal 122 / heapUsed 109 / external 18 / arrayBuffers 1 MB, and later heapTotal 50.5 / heapUsed 41. It has 12 threads, one of them a WorkerThread.

  • glibc share: small. malloc_trim(0) through gdb -p took RSS from 1,434 to 1,307 MB. All of it came from [heap] (143 → 27 MB) and the arenas (64 → 55 MB). The 256 KB pages did not change (1,153 → 1,153 MB).
  • Not a leak. heapUsed is 41–109 MB, which is about the normal attached heap. No objects are still referenced. The count of watches (inotify wd: lines) is back to the baseline, and none of them is under node_modules.
  • V8 keeps freed pages. On the live instance, V8 holds 1.1 GB of resident 256 KB pages while its main-isolate heapTotal is 50 MB. The live inspector cannot bind (port 9229 belongs to workerd), so I reproduced on a second instance with --inspect:
    • During the install the garbage sits in the main isolate. At install end: heapUsed 954 MB, heapTotal 1,049 MB, 1,049 MB of V8 pages. The host-worker isolates hold only 13–69 MB (read through the inspector's NodeWorker domain).
    • An idle isolate gives it back. Allocate 700 MB, drop it, gc(): heapTotal falls to 240 MB, but 727 MB of pages stay resident. When the isolate is idle, V8 unmaps them within 20 s (pages 727 → 103 MB). In run B the second instance was idle and came back to 359 MB about 2 min after the install.
    • A busy isolate does not. Same test, but a light allocation loop runs after the gc(): pages stay at 749 MB (heapTotal 243) for 60 s, and stay there after the loop stops (741 MB more than a minute later). V8's memory reducer runs at most two GCs per activation (--memory-reducer-gc-count=2), so it did not come back. The live host-service is never idle, because it serves the box's chat session, terminals and git status, so the 1.1 GB stays there.

Conclusion: this is V8 keeping freed heap pages on a busy isolate, not glibc and not a leak. Node has no production API that makes V8 release them on demand, and allocator settings (option b) only reach the ~130 MB glibc share. The way to fix it is to never make the garbage: never create the 170k–220k watches.

Also found: with #9896 the growth re-attach came 45–59 s into the install, not after 5 s. git-watcher's refresh rides on emitted git:changed events, and those were delayed by the full event throttler (throttler buffer full — dropping events hundreds of times).

What changed

  • chokidar-backend.ts: events carry isDirectory (addDir/unlinkDir). The ignored callback also asks a new optional request.isPruned(path).
  • FsWatcherManager (only when backend.watchesEachEntry, so only chokidar):
    • On a native create of a directory that is not under a pruned dir, and not under a dir already queued, it queues the root-relative path.
    • After 10 ms it makes one listGitIgnoredDirs(root, signal, under) call for the batch (at most 64 dirs, one call in flight per root).
    • Dirs that git reports as fully ignored are added to prunedRelPrefixes and filteredRelPrefixes. One root overflow is emitted, and the existing rate-limited growth re-attach is scheduled.
    • isPruned reads filteredRelPrefixes, so chokidar stops watching new entries under those dirs at once.
  • refreshIgnores:
    • On chokidar, a dir that is only filtered and becomes un-ignored now re-attaches, like a native shrink. chokidar skipped its entries, so a filter change alone would leave it deaf.
    • Calls are now serialized per root. A call that arrives while one runs waits for one follow-up run and gets its result. Before, a call during a re-attach swap returned false and the change was lost. I hit this on the box: a .gitignore deleted while a growth re-attach was crawling left the dir unwatched. Existing behaviour on main, but this PR makes re-attaches more frequent.
  • host-service listGitIgnoredDirs(rootPath, under?): git --literal-pathspecs ls-files --others --ignored --exclude-standard --directory -z -- <under…>. These are the same rules as the attach-time listing, and literal pathspecs so app/[id] is not a glob. The under list goes through the existing worker task.

The earlier objection to pruning in the callback (#9896) was that a basename guess is wrong for a tracked dist. Here git gives the answer, and --directory collapses a dir only when nothing inside it is tracked.

Pseudocode

on native event batch (chokidar):
  for e in batch where e.type == create and e.isDirectory:
    rel = relative(root, e.path)
    if rel not under pruned and not under queued: queued.add(rel)   // ≤ 64
  if queued and no timer and no check running: timer(10 ms) → check()

check():
  dirs = queued not under pruned; queued.clear()
  ignored = git ls-files --others --ignored --exclude-standard --directory -- dirs
  if ignored - pruned:
    pruned += new; filtered += new            // chokidar's ignored() now true below them
    emit overflow
    scheduleGrowthReattach(max(0, lastGrowthReattach + 30 s - now))
  if queued: schedule next check

refreshIgnores(root):            // serialized: one run + at most one queued follow-up
  fresh = nested repos + git ignored dirs
  reattach = native shrank || (chokidar && filtered shrank)
  growth re-attach as before (≤ 1 per 30 s)

Before / after: real bun install, watch attached before node_modules exists

Second host-service instance on port 4979 (SUPERSET_HOST_RUN_MODE=local, its own HOME, run dir and copy of host.db, SUPERSET_API_URL pointed at a closed port, --inspect for heap numbers), on this box's released runtime node:

  • main = the released bundle in /opt/superset/host/current (2.0.9+81d68fcd, contains #9896).
  • branch = bun run build.ts from this branch, the same runtime with host-service.js/host-worker.js swapped.

The live host-service was not replaced. The workspace is /workspace (this repo, 22,3xx watches attached). Procedure: delete every node_modules, attach a WebSocket client on /events (git:watch + fs:watch), wait 45 s, run bun install (2,778 packages), sample every 5 s. Watches = inotify wd: lines in /proc/<pid>/fdinfo. heapUsed is the main isolate's process.memoryUsage() through the inspector.

Stepmain watchesmain RSSmain heapUsedbranch watchesbranch RSSbranch heapUsed
Before attach0176 MB36 MB0176 MB36 MB
Attached, no node_modules22,352377 MB139 MB22,335377 MB140 MB
Peak during install (5 s samples)169,1841,350 MB954 MB22,335506 MB209 MB
Install end22,3521,327 MB954 MB22,335450 MB209 MB
+45 s22,3521,292 MB956 MB22,352288 MB97 MB
+3 min22,352359 MB102 MB22,352259 MB97 MB
+6 min22,352353 MB102 MB22,352244 MB96 MB
  • Install took 89.2 s on main and 78.6 s on the branch.
  • An earlier main run without worker sampling peaked at 220,264 watches, 1,525 MB RSS and 1,002 MB heapUsed; it was at 525 MB at +6 min.
  • An earlier branch build without the serialization change peaked at 22,335 watches and 571 MB.
  • On main, RSS comes back here only because this second instance goes idle after the install. The live host-service in the same scenario stayed at 1,444 MB (see the diagnosis). On the branch, the peak heap is about 210 MB, so that is all V8 can keep.
  • 0 watches under any node_modules at the end on the branch (inodes mapped back to paths, 39 node_modules dirs on disk). The +17 watches after the install are .git objects and refs from a commit, held by git-watcher's .git watcher.

overflow events the /events client got (excluding the one at attach):

  • main: 1 during the install, the growth re-attach at 44.9 s (59.1 s in the earlier run); 0 after in this run, 1 in the earlier run.
  • branch: 4 during the install, at 0.2, 0.4 and 0.5 s (three early-prune batches) and 6.6 s (the re-attach); 0 after.

Event checks on the branch instance, with the same client attached:

  • Non-ignored new dir and file: create:/workspace/wvprobe-…/probe.ts delivered, and the dir is watched.
  • Ignored dir created after attach (wvgi-…/.gitignore = gen/, then gen/a.ts): 2 overflow events (filter, then re-attach). gen is not watched, and a later write in it is not delivered.
  • Un-ignore (delete that .gitignore): 1 overflow (re-attach). gen is watched again, and create:/workspace/wvgi-…/gen/b.ts is delivered. Before the serialization change this step failed on the box: no event and gen stayed unwatched, from the race above.

Product implications

  • Linux (cloud boxes and local Linux hosts): a new gitignored dir is pruned about 0.2–0.5 s after it appears, not up to a minute later. Clients get one root overflow per check batch that finds new ignored dirs, plus one per re-attach: 4 instead of 1 for a bun install of this repo. Each one makes the file tree and open documents refetch and git-watcher do a broad refresh.
  • Extra git calls: one scoped git ls-files per batch of new directories that are not under a pruned dir. At most one runs at a time per watch root, with ≤ 64 dirs each. A checkout that creates many tracked dirs causes a short series of these calls. They run on the host-worker pool, as the attach-time listing does.
  • macOS / Windows: parcel sets neither watchesEachEntry nor isDirectory, so the new-dir check and the filtered-shrink re-attach never run there. #9896's parity test passes unchanged. The one shared change: concurrent refreshIgnores calls now coalesce into one follow-up run, not false.
  • Not addressed: V8 still keeps freed pages on a busy host-service after any other large heap churn. This PR only removes the largest known source. Allocator variables (MALLOC_ARENA_MAX, MALLOC_TRIM_THRESHOLD_) would reach only the glibc share (~130 MB on the live box), so I did not add them.

How I tested it

Ran:

  • bun test in packages/workspace-fs: 201 pass, 2 skip, 0 fail. This includes the new watch-new-dir-prune.test.ts: 3 cases on a fake chokidar-mode backend, no real waiting (~70 ms):

    • a new ignored dir is pruned by isPruned before any refreshIgnores, then re-attached;
    • an un-ignore while only filtered re-attaches;
    • an un-ignore during a re-attach swap is not lost.

    With queueNewDirIgnoreChecks disabled, the first two time out. With filteredShrunk removed, the second fails. Without the serialization, the third fails.

  • bun test in packages/host-service: 2,910 pass, 23 fail. These are the same 23 that #9896 reported on main in a full-suite run: 22 session: tests in background-naming.integration.test.ts and health.check › serialises the current boot's stamps…. background-naming alone: 56/56 pass. health.test.ts alone fails the same way on main with this change stashed. The full suite also writes test worktrees into packages/host-service/undefined/ (existing, not committed).

  • bun run lint:fix: two files reformatted, no remaining issues.

  • tsc --noEmit (bun run typecheck) in packages/workspace-fs and packages/host-service: both pass. No other package uses the changed types (git grep).

  • The real-install measurements and event checks above, on this box.

Not run:

  • The full turbo typecheck over all packages (only the two affected packages).
  • macOS / Windows with the real parcel backend (unchanged code path there; parity test only).
  • Replacing the live host-service with the branch build. All branch numbers are from a second instance.
  • Allocator variables in superset-boot (not measured; see the diagnosis for why not).

Checklist

  • PR title follows conventional commits (type(scope): subject)
  • bun run lint and bun run typecheck pass for the affected packages (full turbo typecheck not run)
  • "Allow edits from maintainers" is checked on fork PRs (not a fork)
  • I have signed the CLA (not verified by the agent)

Summary by cubic

Fixes host-service memory growth on Linux by pruning a newly created gitignored directory (like node_modules during a bun install) as soon as chokidar reports it, instead of waiting until git-watcher's next refresh.

Previously chokidar watched the new directory file by file until a refresh re-attached up to a minute later, creating 170k–220k watches and ~1 GB of V8 heap that a busy host-service never released; RSS stayed around 1.4 GB. Now the manager batches new directories and asks git whether each is ignored (git ls-files --ignored --directory, with --literal-pathspecs), and chokidar's ignored callback consults the answer so it stops descending within milliseconds. Peak RSS during a real install drops from 1,350–1,525 MB to 506 MB, settling at 244 MB after 6 minutes.

Side effects

  • A directory that becomes un-ignored while only filtered now re-attaches, since chokidar skipped its entries.
  • refreshIgnores calls are serialized per root; one arriving mid-run waits for a follow-up run instead of returning false and losing the change.
  • One scoped git ls-files runs per batch of new directories (≤ 64, one in flight per root), on the host-worker pool.
  • macOS/Windows (parcel) are unaffected — the check only runs on watchesEachEntry backends with isDirectory events.
  • V8 keeping freed pages on a busy isolate is not addressed; this only removes the largest known source.

Summary by CodeRabbit

  • Bug Fixes
    • Newly created directories that are Git-ignored are now excluded from filesystem watching more reliably, including when ignore rules change during watcher setup.
    • Directories that are no longer ignored can be watched again after the watcher refreshes.
    • Ignore-rule refreshes are handled in sequence to avoid losing changes during an active refresh.