Skip to content

metro-file-map: Don't exit when a watcher reports an error - #2151

Closed
ramya-2196 wants to merge 1 commit into
react:mainfrom
ramya-2196:export-D129077567
Closed

ramya-2196 wants to merge 1 commit into
react:mainfrom
ramya-2196:export-D129077567

Conversation

@ramya-2196

Copy link
Copy Markdown
Contributor

Summary:

Motivation

When a metro-file-map watcher backend reports an error, the Metro server exits.

Example

Without Watchman, taking the permissions off a watched folder (chmod 000 watched) makes FallbackWatcher fail to lstat it, and the server dies with:

Error: EACCES: permission denied, lstat '…/watched/watched'
Emitted 'error' event at:
    at FallbackWatcher.emitError (…/metro-file-map/src/watchers/AbstractWatcher.js:77:19)

Watcher subscribes each backend with onFileEvent only. A backend reports errors by emitting 'error' on its own EventEmitter, and with no 'error' listener Node throws, so any error a backend reports (from FallbackWatcher, NativeWatcher, or a Watchman client error) ends the process. stopWatching() removes every listener, so an error reported by work still in flight while a backend shuts down throws the same way.

Fixes #2143

The fix

  • Watcher subscribes each backend's onError next to its onFileEvent, and logs the error to the file map's console with the watch root and the error's message. Watching continues. Errors reported after close() are ignored.
  • AbstractWatcher.emitError() does nothing once stopWatching() has been called, so late errors from in-flight work no longer throw.

More details

  • The error is logged rather than re-emitted as an 'error' event on Watcher, because a new event would crash the same way unless every consumer added a listener.
  • Subscribing inside createWatcherBackend covers both the initial roots and roots added later with watchRoot().
  • The backends already call emitError only for errors they cannot handle themselves (for example, FallbackWatcher ignores ENOENT), so this doesn't add noise for routine file churn.

Changelog: [Fix] metro-file-map: An error reported by a file watcher backend, such as a watched folder becoming unreadable, is now logged instead of ending the Metro server

Differential Revision: D129077567

Summary:
## Motivation

When a `metro-file-map` watcher backend reports an error, the Metro server exits. 
### Example

Without Watchman, taking the permissions off a watched folder (`chmod 000 watched`) makes `FallbackWatcher` fail to `lstat` it, and the server dies with:

```
Error: EACCES: permission denied, lstat '…/watched/watched'
Emitted 'error' event at:
    at FallbackWatcher.emitError (…/metro-file-map/src/watchers/AbstractWatcher.js:77:19)
```

`Watcher` subscribes each backend with `onFileEvent` only. A backend reports errors by emitting `'error'` on its own `EventEmitter`, and with no `'error'` listener Node throws, so any error a backend reports (from `FallbackWatcher`, `NativeWatcher`, or a Watchman client error) ends the process. `stopWatching()` removes every listener, so an error reported by work still in flight while a backend shuts down throws the same way.

Fixes react#2143

## The fix

- `Watcher` subscribes each backend's `onError` next to its `onFileEvent`, and logs the error to the file map's `console` with the watch root and the error's message. Watching continues. Errors reported after `close()` are ignored.
- `AbstractWatcher.emitError()` does nothing once `stopWatching()` has been called, so late errors from in-flight work no longer throw.

## More details

- The error is logged rather than re-emitted as an `'error'` event on `Watcher`, because a new event would crash the same way unless every consumer added a listener.
- Subscribing inside `createWatcherBackend` covers both the initial roots and roots added later with `watchRoot()`.
- The backends already call `emitError` only for errors they cannot handle themselves (for example, `FallbackWatcher` ignores `ENOENT`), so this doesn't add noise for routine file churn.

Changelog: [Fix] metro-file-map: An error reported by a file watcher backend, such as a watched folder becoming unreadable, is now logged instead of ending the Metro server

Differential Revision: D129077567
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 2, 2026
@meta-codesync

meta-codesync Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

@ramya-2196 has exported this pull request. If you are a Meta employee, you can view the originating Diff in D129077567.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Metro review: Needs discussion

Risk: medium · Commit: 0ca9160 · 13 commands run

Duplicate first: #2147 is also open for #2143 and also changes Watcher.js, Watcher-test.js and AbstractWatcher, and its file list adds WatchmanWatcher changes and reconnect tests that this PR lacks, so a maintainer should choose one. This PR does fix the reported crash: chmod 000 on a watched root now logs and keeps running, and its new tests fail on base. But errors that lose a watch now leave Metro running with stale results (an ENOSPC flood, a dead Watchman connection), and close() during a Watchman reconnect still crashes the process.

Findings

  • should fix · Hitting the watch limit logs once per directory, then starts normally with those directories unwatched — packages/metro-file-map/src/Watcher.js:419 · d489ba45

  • should fix · A failed Watchman reconnect now leaves a permanently dead watcher behind one log line — packages/metro-file-map/src/Watcher.js:332 · 324c2660

  • should fix · Late errors still throw when the Watchman client's connect is in flight at close — packages/metro-file-map/src/watchers/AbstractWatcher.js:91 · 9660d57d

  • nit · A Watchman connection failure during startup goes from an immediate exit to a long hang — packages/metro-file-map/src/Watcher.js:326 · ae8db360

    fb-watchman emits error for a socket failure without calling pending command callbacks, so #init's onError never fires and startWatching() doesn't settle. Base exits at once with the real error. Head logs it and then waits for MAX_WAIT_TIME (240s) before rejecting with the generic Failed to start watch mode.

    The window is narrow when the Watchman crawl has just succeeded. Rejecting startWatching on a client error received before it resolves would fix it, and keep the real error.

  • nit · NativeWatcher's own FSWatcher errors bypass this subscription and stay uncaught — packages/metro-file-map/src/Watcher.js:332 · ffffef3c

Verified
  • ✅ yarn jest --no-watchman packages/metro-file-map/src/__tests__/Watcher-test.js packages/metro-file-map/src/watchers/__tests__/AbstractWatcher-test.js — 21 tests pass on head.
  • ✅ Same two test files copied onto base source, then yarn jest (failed as expected) — All 3 new tests fail on base, so they exercise the fix. The other 18 pass.
  • ❌ yarn jest --no-watchman packages/metro-file-map — 13 of 803 fail, all in the crawler and watcher integration-test suites. The same two suites also fail 13 tests on base; the listed head failures are the Watchman variants.
  • ✅ yarn typecheck
  • ✅ yarn eslint on the 4 changed files — No lint output. The exit code was masked by a pipe to tail.
  • ✅ yarn verify-api-snapshots
  • ✅ node __repro__/native.js <checkout> chmodroot — The PR's scenario with a real NativeWatcher on macOS. Head logs EACCES and survives. Base: UNCAUGHT EACCES.
  • ✅ node __repro__/enospc.js <checkout> 1000 100 (failed as expected) — Head: 901 console.error calls, then watch() resolves. Base: unhandled rejection, exit 71.
  • ✅ node __repro__/watchman.js <checkout> reconnect (failed as expected) — Head: 0 connection attempts after Watchman returns. Base: uncaught ECONNREFUSED.
  • ✅ node __repro__/watchman.js <checkout> late (failed as expected) — Head: uncaught ECONNREFUSED after close. Base: unhandled rejection, The client was ended.
  • ✅ node __repro__/realclient.js <head> (failed as expected) — Real net socket: UNCAUGHT connect ENOENT after removeAllListeners and end.
  • ✅ node __repro__/watchman.js <checkout> startup (failed as expected) — Head: still pending after 3s. Base: uncaught ECONNREFUSED.
  • ✅ node __repro__/native.js <checkout> emit|rmroot|chmodsub (failed as expected) — emit: uncaught on both head and base. rmroot and chmodsub: survived on both.

Not run: Windows and Linux weren't run; ENOSPC is simulated on macOS by making fs.watch throw. No real Watchman: the sandbox blocks Unix socket listeners, so repros use the real client over a fake socket (only realclient.js uses real net). The 240s wait is from reading the code. #2147 couldn't be fetched, so only its file list was compared. Three shell commands were denied by permission checks; repros were rerun in simpler forms. The PR's tests remain copied into base. No benchmark: one boolean check on a rare error path.

Automated review by Claude. Advisory only: it never approves or blocks, and a maintainer makes the call.

debug('Ignoring an error reported after close for %s: %s', root, error);
return;
}
this.#options.console.error(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should fix · Hitting the watch limit logs once per directory, then starts normally with those directories unwatched

FallbackWatcher.#watchdir catches each fs.watch failure, reports it and continues, and #reportBackendError logs every report. On Linux at the inotify limit, a project gets one console.error per remaining directory, and then watch() resolves as if all were well.

Each message only says the watcher reported an error. Nothing tells the user that changes in those directories won't be picked up, so they get stale bundles after startup output that scrolled past. On base, the same case ends the process with the ENOSPC error, which is blunt but can't be missed.

The description's "this doesn't add noise for routine file churn" is true of churn, but not of this case.

Suggested fix: report resource-limit errors (ENOSPC, EMFILE) once per root and code, and say that changes in unwatched directories will be missed, with a pointer to raising the limit or installing Watchman.

Reproduced: __repro__/enospc.js: a real FallbackWatcher on 1,000 directories, with fs.watch throwing ENOSPC after 100 calls. Head: watch() resolved; console.error calls: 901. Base: UNHANDLED REJECTION: ENOSPC..., exit 71. · id d489ba45

MAX_WAIT_TIME,
);

watcher.onError(error => this.#reportBackendError(root, error));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should fix · A failed Watchman reconnect now leaves a permanently dead watcher behind one log line

WatchmanWatcher.#init reconnects once on end. If that connection fails, the error goes to emitError and nothing retries, because a failed connect never emits another end.

On base, this ended the process. With this subscription, Metro stays up and receives no more file events for that root for the rest of the session. That happens on any Watchman restart or upgrade where the socket isn't back in time for the single attempt. The log line doesn't say that changes are no longer being seen, and the health check that could expose it is opt-in.

Failure case: Watchman goes down, the reconnect gets ECONNREFUSED, and Watchman comes back. Metro makes no further attempts and keeps serving old code until restarted.

Suggested fix: retry with backoff in WatchmanWatcher. At a minimum, say in the message that watching has stopped. Watcher.js:348 rejects recrawl events under Watchman, so a recrawl on recovery would need more work.

Reproduced: __repro__/watchman.js reconnect (real fb-watchman client, fake in-process socket). Head: connection attempts after Watchman returned: 0 ; live connections: 0 ; errors logged: 1. Base: UNCAUGHT: connect ECONNREFUSED. · id 324c2660

emitError(error: Error) {
// Work still in flight after stopWatching() can report an error, when
// nothing listens any more and emitting 'error' would throw.
if (this.#stopped) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should fix · Late errors still throw when the Watchman client's connect is in flight at close

The description says late errors from in-flight work no longer throw, but this guard only covers the backend's own emitter. WatchmanWatcher.stopWatching calls removeAllListeners() on the fb-watchman client and then end(). The client's socket error handler re-emits on the client, which now has no error listener, so Node throws.

Failure case: Watchman drops, #init starts a reconnect, and close() runs before the connect fails (for example, Ctrl-C or a test teardown during a Watchman restart). The process dies with an uncaught connect error after close() has resolved.

The PR does fix a neighboring case. On base, the same sequence fails earlier, with an unhandled rejection of The client was ended.

Suggested fix: in stopWatching, leave a no-op error listener on the client after removing the others, and call end() after that. Add a WatchmanWatcher test for it.

Reproduced: __repro__/watchman.js late on head: closed, then UNCAUGHT: connect ECONNREFUSED. __repro__/realclient.js applies the same removeAllListeners() and end() to a real client with a real net socket: UNCAUGHT: connect ENOENT .../missing-socket. · id 9660d57d

MAX_WAIT_TIME,
);

watcher.onError(error => this.#reportBackendError(root, error));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit · NativeWatcher's own FSWatcher errors bypass this subscription and stay uncaught

The description names NativeWatcher among the backends that no longer end the process. That holds for errors it passes to emitError, such as the lstat path. But NativeWatcher.startWatching attaches no error listener to the FSWatcher it creates, unlike FallbackWatcher.js:216, so an error emitted on that object is still uncaught.

I couldn't trigger one with real filesystem operations on macOS, so this is a robustness gap and not a known user-facing crash. Forwarding it to emitError takes one line, because NativeWatcher.js already routes its other failures there.

Evidence: __repro__/native.js emit emits error on the captured FSWatcher, on head: UNCAUGHT: simulated FSWatcher failure. Real triggers produced no such error on head: rmroot gave a delete:root event, chmodsub gave recrawl:sub, and chmodroot went through emitError and was logged. · id ffffef3c

@vzaidman

vzaidman commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Please study #2147 and see if that fix is any better than yours.

c.c @robhogan- there seems to be a problem fixed in slightly different ways here.

@vzaidman
vzaidman requested review from robhogan and vzaidman November 3, 2026 10:46
@vzaidman

vzaidman commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Please link https://nodejs.org/api/events.html#error-events in the summary to help understand the issue


async stopWatching(): Promise<void> {
this.#stopped = true;
this.#emitter.removeAllListeners();

@vzaidman vzaidman Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe

    this.#emitter.removeAllListeners();
    this.#emitter.on('error', (err) => {
      logger.warn('Error reported after close', err, /** other args? **/);
    });

To keep the emitter from not having any listeners anymore?

@vzaidman

vzaidman commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Is there a way to prevent the error that is thrown after "stopListening" instead? So, to abort whatever throws the error? Even in that case, we probably wouldn't want the process to crash though.

@ramya-2196 ramya-2196 closed this Nov 3, 2026
@ramya-2196

Copy link
Copy Markdown
Contributor Author

Closing this in favour of #2147, which fixes the same crash and also covers the follow-ups raised in review here (de-duplicating ENOSPC/EMFILE, Watchman reconnects and late client errors). Thanks @vzaidman for the pointer and the review.

One gap that's still open in #2147 and that I hit while testing: NativeWatcher creates its recursive fs.watch handle without an 'error' listener (unlike FallbackWatcher), so an error emitted on that handle is still uncaught and ends the process. Forwarding it fixes it:

fsWatcher.on('error', error => {
  this.emitError(error);
});

It can be tested with the existing fs.watch mock in NativeWatcher-test.js by returning an EventEmitter as the handle and emitting 'error' on it. @sorinc03, happy to help there if useful.

@vzaidman

vzaidman commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Thanks @ramya-2196, please mention this on #2147 itself

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

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. meta-exported

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[metro-file-map] An error a watcher backend reports ends the server, since nothing listens for it

2 participants