Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/Watcher.zig
Original file line number Diff line number Diff line change
Expand Up @@ -758,8 +758,19 @@
pub fn remove(this: *Watcher, hash: HashType) void {
this.mutex.lock();
defer this.mutex.unlock();
if (this.indexOf(hash)) |index| {
// `removeAtIndex` only queues the index into `evict_list`; the real
// removal happens in `flushEvictions()`, which is normally driven by
// `onFileUpdate()` on the watcher thread. `remove()` can be called
// many times without any fs events firing (e.g. `fs.watch()`
// followed by `.close()` in a tight loop), so the fixed-size
// `evict_list` can fill up and overflow. Drain it here when full —
// we already hold `this.mutex`, matching how `flushEvictions()` is
// invoked from the platform watch loops.
if (this.evict_list_i >= max_eviction_count) {
this.flushEvictions();
}
this.removeAtIndex(@truncate(index), hash, &[_]HashType{}, .file);

Check failure on line 773 in src/Watcher.zig

View check run for this annotation

Claude / Claude Code Review

Stale watchlist index used after flushEvictions() in remove()

The `index` is captured via `this.indexOf(hash)` *before* the new `flushEvictions()` call, but `flushEvictions()` mutates the watchlist via `swapRemove()`, which relocates entries and shrinks the list — so the index passed to `removeAtIndex()` may now point to a different entry or past the end. Move the `if (this.evict_list_i >= max_eviction_count) this.flushEvictions();` check to *before* `if (this.indexOf(hash)) |index|` so the lookup operates on the post-flush watchlist.
Comment thread
claude[bot] marked this conversation as resolved.
}
}

Expand Down
78 changes: 78 additions & 0 deletions test/js/node/watch/fs.watch.evict-list-overflow.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe, isMacOS, isWindows, tempDir } from "harness";

// Regression test for `Watcher.evict_list` overflow.
//
// `Watcher.remove()` appends the watchlist index to a fixed-size
// `evict_list[max_eviction_count = 8096]` buffer; the actual removal
// happens in `flushEvictions()`, which was only driven by `onFileUpdate()`
// on the watcher thread — i.e. only when a filesystem event arrives.
//
// `fs.watch(path).close()` reaches `_decrementPathRefNoLock()` →
// `main_watcher.remove(hash)` for the watched path. Repeating that
// without ever modifying the filesystem means `flushEvictions()` never
// runs, and once the cumulative remove count passes 8096,
// `removeAtIndex()` writes past the end of `evict_list`:
//
// panic(main thread): index out of bounds: index 8096, len 8096
// Watcher.removeAtIndex src/Watcher.zig
// Watcher.remove
// PathWatcherManager._decrementPathRefNoLock
//
// The fix drains `evict_list` inside `remove()` when it's full (the
// mutex is already held there, matching how `flushEvictions()` is
// invoked from the platform watch loops).
//
// Watching a single file (not a directory) keeps the test deterministic:
// file watches don't schedule a `DirectoryRegisterTask`, so `deinit()`
// runs to completion on every `close()` and exactly one `remove()` is
// issued per iteration; and the inotify file mask doesn't include
// IN_OPEN / IN_CLOSE so re-opening the fd each cycle doesn't generate
// events that would opportunistically flush.
//
// Windows uses win_watcher.zig (no evict_list); macOS directory watches
// use FSEvents. The overflow is reachable on Linux/FreeBSD only.
test.skipIf(isWindows || isMacOS)(

Check warning on line 35 in test/js/node/watch/fs.watch.evict-list-overflow.test.ts

View check run for this annotation

Claude / Claude Code Review

macOS skip rationale is incorrect for file watches

The skip rationale here is incorrect for a *file* watch: on macOS only **directory** watches use FSEvents — file watches go through `KEventWatcher` (same as FreeBSD) and reach `Watcher.remove()` → `evict_list`, so the overflow is reachable on macOS too. Consider dropping `isMacOS` from the `skipIf` to gain kqueue coverage of the new main-thread `flushEvictions()` path (including the `addFileDescriptorToKQueueWithoutChecks` re-registration), or update the comment to state the actual reason for sk
Comment thread
claude[bot] marked this conversation as resolved.
Outdated
"Watcher.remove() does not overflow evict_list when no fs events fire",
async () => {
using dir = tempDir("fswatch-evict-overflow", { "f.txt": "x" });

const fixture = /* js */ `
const fs = require("fs");
const path = require("path");
const target = path.join(process.argv[1], "f.txt");
// > max_eviction_count (8096): one remove() per cycle, no fs events,
// so without the fix evict_list_i hits 8096 and removeAtIndex panics.
const ITERS = 8200;
for (let i = 0; i < ITERS; i++) {
const w = fs.watch(target, { persistent: false }, () => {});
w.close();
}
console.log("ok " + ITERS);
`;

await using proc = Bun.spawn({
cmd: [bunExe(), "-e", fixture, String(dir)],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([
proc.stdout.text(),
proc.stderr.text(),
proc.exited,
]);

const filteredStderr = stderr
.split("\n")
.filter(l => l && !l.startsWith("WARNING: ASAN interferes"))
.join("\n");

expect({ stdout: stdout.trim(), stderr: filteredStderr, exitCode }).toEqual({
stdout: "ok 8200",
stderr: "",
exitCode: 0,
});
},
30000,
);
Loading