Repository navigation
Conversation
libuv on Windows reports a deleted watched directory to its own handle as a rename naming the directory's absolute path, and re-arms that report until the handle is closed. FallbackWatcher joined the path onto the directory, found nothing and closed nothing, so the handle kept the process busy. When a parent reported a deletion, only the deleted directory's own handle was closed, and a nested handle left in #watched also stopped the path from being watched again. A self-report now closes the directory's handle and every handle beneath it, then processes the path as the parent's rename would. The deletion branch closes the whole subtree.
|
The measurement from the description, for anyone re-running it against a build of // node measure.js <path to metro-file-map> <deleted|recreated>
const fs = require('fs');
const os = require('os');
const path = require('path');
const [packageDir, mode = 'deleted'] = process.argv.slice(2);
const FallbackWatcher = require(path.join(packageDir, 'build/watchers/FallbackWatcher.js')).default;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
(async () => {
const root = fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), 'metro-fw-'));
const writeTree = () => {
for (let i = 0; i < 20; i += 1) {
const chunk = path.join(root, 'dist', 'static', `chunk-${i}`);
fs.mkdirSync(chunk, { recursive: true });
fs.writeFileSync(path.join(chunk, 'index.js'), 'module.exports = 1;\n');
}
};
writeTree();
const watcher = new FallbackWatcher(root, { dot: false, globs: ['**/*.js'], ignored: null, watchmanDeferStates: [] });
const touched = new Set();
watcher.onFileEvent((event) => {
if (event.event === 'touch') touched.add(event.relativePath);
});
await watcher.startWatching();
await sleep(500);
fs.rmSync(path.join(root, 'dist'), { recursive: true, force: true });
if (mode === 'recreated') writeTree();
const before = process.cpuUsage();
await sleep(4000);
const used = process.cpuUsage(before);
console.log(mode, 'CPU seconds in 4s:', ((used.user + used.system) / 1e6).toFixed(2), '| touched after delete:', touched.size);
await watcher.stopWatching();
fs.rmSync(root, { recursive: true, force: true });
})(); |
|
This is a really nice find - thanks for the PR! |
|
Some additional context: The self-report was added in libuv 1.49.0 (libuv/libuv#4376), and the endless repeat is nodejs/node#61398. NTFS can't finish a permanent delete while the handle is open, so it parks the directory under libuv 1.53.0 fixes the spin (libuv/libuv#5013) by following the "never an |
This comment has been minimized.
This comment has been minimized.
robhogan
left a comment
There was a problem hiding this comment.
Thanks again for the PR - the change looks good to me.
File watching and OS peculiarities is one area where some detailed code comments are useful so I've suggested a couple of additions re Linux impact, the likely mechanisms that trip this, and pointers to upstream changes.
This will be in Metro 0.87.2 / RN 0.87+ / Expo 58. Is it useful to you if this is backported to older versions?
| // libuv on Windows reports a deleted watched directory to its own | ||
| // handle as a rename naming the directory's absolute path, and repeats | ||
| // that report until the handle is closed. |
There was a problem hiding this comment.
| // libuv on Windows reports a deleted watched directory to its own | |
| // handle as a rename naming the directory's absolute path, and repeats | |
| // that report until the handle is closed. | |
| // libuv on Windows reports a deleted watched directory to its own | |
| // handle as a rename naming the directory's absolute path, and before | |
| // libuv 1.53 repeats that report until the handle is closed. If the | |
| // directory is recreated first, the open handle also stops it from | |
| // being watched again. Linux and macOS name the directory by its | |
| // basename instead, so this branch is Windows-only. |
| // A deleted directory takes its subtree with it, and a nested handle left | ||
| // open would also stop the path from being watched again once it is | ||
| // recreated. |
There was a problem hiding this comment.
| // A deleted directory takes its subtree with it, and a nested handle left | |
| // open would also stop the path from being watched again once it is | |
| // recreated. | |
| // Close every handle under a deleted directory. Left open, a handle stops | |
| // its path from being watched again once it is recreated. On Linux it | |
| // also follows the directory if it was moved (as npm moves a package | |
| // aside to update it), so it goes on watching the old copy. macOS | |
| // watches by path, so there an open handle is merely redundant. |
Co-authored-by: Rob Hogan <2590098+robhogan@users.noreply.github.com>
…eted-directory handles The wording follows Rob Hogan's review of the same change in Metro (react/metro#2004).
|
Thanks for the libuv history. Both suggestions are in (d942b0e), the description now scopes "never an |
Summary: Publish Metro 0.87.2 from `main`. Changelog: [Internal] Test plan: ``` node scripts/updateVersion.js 0.87.2 sl diff --stat ``` Only the 17 `packages/*/package.json` manifests change, and every `0.87.1` reference is replaced. Draft release notes (from the 95 commits in v0.87.1...main - internal-only changes omitted): ``` - **[Feature]**: Add a built-in `metro:runtime/*` specifier, resolvable from any importer, eg for `transformer.asyncRequireModulePath` (#2083 by @robhogan) - **[Feature]**: When `transformer.enableBabelRuntime` is `true`, pass Metro's own `@babel/runtime` (`metro:babel-runtime`) and its installed version to Babel presets via caller data (#1957 by @robhogan) - **[Fix]**: Resolver: Fix stale resolutions after adding a nearer `package.json` or retargeting a symlinked directory, which previously needed a restart (#1948 by @robhogan) - **[Fix]**: Resolver: Packages and directories named with an asset extension (eg `lodash.zip`) resolve as modules rather than failing as assets (#2055 by @robhogan) - **[Fix]**: Resolver: Fall through to parent conditions when a nested `"exports"` or `"imports"` condition has no matching target (#2074 by @maximilliangrand) - **[Fix]**: Resolver: An exact `"exports"` or `"imports"` subpath with a `null` or unmatched target no longer resolves through a less specific subpath pattern (#1987 by @kwy404) - **[Fix]**: Use indexed watch folder paths (`[metro-watchFolders]/N/`) for assets outside `projectRoot` (#1892 by @robhogan) - **[Fix]**: Fix `/[metro-project]/` and `/[metro-watchFolders]/` bundle serving on Windows (#2015 by @motiz88) - **[Fix]**: Prevent HMR crash on `[metro-watchFolders]` or `[metro-project]` URLs (#2017 by @motiz88) - **[Fix]**: Remove erroneous `[metro-project]` and `[metro-watchFolders]` resolution of entry points from the API and CLI (#2030 by @motiz88) - **[Fix]**: Fix backslashes in async bundle paths on Windows (`includeAsyncPaths`) (#1938 by @robhogan) - **[Fix]**: Fix stale modules on the client when a file is deleted and recreated during a build, or changes during a build that fails (#2007 by @YevheniiKotyrlo) - **[Fix]**: Fix files created or modified while Metro starts up being missed until restart (#2054 by @cpruijsen) - **[Fix]**: Fix watch mode losing files when a directory replaces a file or symlink, eg when unlinking a package (#2009 by @robhogan) - **[Fix]**: Fix the fallback (Linux/Windows) watcher hanging on stop, and missing changes in a replaced directory, after a watch error (#1967 by @robhogan) - **[Fix]**: Fix the fallback watcher missing changes when a directory changes faster than Windows can report (#1967 by @robhogan) - **[Fix]**: Close the watch handles of a deleted directory and every directory under it in `FallbackWatcher`, which kept the process busy on Windows (#2004 by @YevheniiKotyrlo) - **[Fix]**: `metro-file-map`: Fix removing a non-active duplicate mock changing which mock is active (#1756 by @durvesh1992) - **[Fix]**: Propagate transformer initialisation errors from `Bundler` (#1854 by @Boulea7) - **[Fix]**: Release transform workers and file watchers when Metro fails to initialise (#1963 by @robhogan) - **[Fix]**: Ignore hyphenated and namespaced SVG attributes (eg `stroke-width`) when reading SVG asset dimensions (#1972 by @GabrielDumbrava) - **[Fix]**: Fix generated positions when iterating the mappings of indexed source maps, eg in `composeSourceMaps` (#1976 by @kwy404) - **[Fix]**: `composeSourceMaps` keeps every mapping at a generated column that the last map maps more than once (#1981 by @robhogan) - **[Fix]**: Source maps no longer lose lines after a gap of more than about two million unmapped generated lines (#1983 by @robhogan) - **[Fix]**: `metro-symbolicate` no longer fails on stack frames with no source position, such as `[native code]:0:0` in crash reporter output (#1891 by @robhogan) - **[Fix]**: Fix `metro-symbolicate` parsing of stack frames with Windows absolute paths (#1939 by @robhogan) - **[Performance]**: `metro-source-map`: Faster `Consumer` decoding and position lookups, and `composeSourceMaps` encodes its output directly - 3.2x faster composition of a bundle map with its Hermes map, using 15% less memory (#1978, #1979, #1980, #1983 by @robhogan) - **[Performance]**: Resolver: Ask for the package of a directory once for all extension candidates, and check `hierarchicalLookup` candidates from their own file map nodes. First-pass resolution is 35% faster (172ms -> 113ms on a mid-size RN app), net of a ~3% first-build cost from dropping `PackageCache`'s closest-package memo, which also cuts the resolver's retained heap by 37% (#1945, #1946, #1948 by @robhogan) - **[Performance]**: 33% faster non-Watchman file system crawl on startup (#1677 by @kitten) - **[Deprecated]**: `server.enhanceMiddleware` logs a deprecation warning when set to anything other than its default. Use `server.unstable_middleware` or `server.unstable_priorityMiddleware` (#2031 by @vzaidman) - **[Deprecated]**: `runServer`'s `unstable_extraMiddleware` option. Use `unstable_priorityMiddleware`, which runs the same middleware in the same place (#2031 by @vzaidman) - **[Deprecated]**: String values of `transformer.enableBabelRuntime` (use `true`) (#1957 by @robhogan) - **[Types]**: Add TypeScript definitions for `metro-runtime` modules, and generate (rather than hand-maintain) types for `metro-file-map` workers (#1996 by @robhogan) > NOTE: Experimental features are not covered by semver and can change at any time. - **[Experimental]**: Add `server.unstable_middleware` and `server.unstable_priorityMiddleware` config options, and `runServer` options of the same names, to add middleware after and before Metro's own. `mergeConfig` combines them from both configs: a later config's `unstable_middleware` runs last and its `unstable_priorityMiddleware` runs first (#2031 by @vzaidman) - **[Experimental]**: Add `server.unstable_onServerCreated` config option and `runServer` option of the same name, called with Metro's server instance before the HTTP server listens (#2031 by @vzaidman) - **[Experimental]**: Fix mismatched asset paths in (release) builds under `unstable_serverRoot`, make them always relative to `projectRoot` (#1917 by @robhogan) **Full Changelog**: v0.87.1...v0.87.2 ```
Summary: Publish Metro 0.87.2 from `main`. Changelog: [Internal] Test plan: ``` node scripts/updateVersion.js 0.87.2 sl diff --stat ``` Only the 17 `packages/*/package.json` manifests change, and every `0.87.1` reference is replaced. Draft release notes (from the 95 commits in v0.87.1...main - internal-only changes omitted): ``` - **[Feature]**: Add a built-in `metro:runtime/*` specifier, resolvable from any importer, eg for `transformer.asyncRequireModulePath` (#2083 by @robhogan) - **[Feature]**: When `transformer.enableBabelRuntime` is `true`, pass Metro's own `@babel/runtime` (`metro:babel-runtime`) and its installed version to Babel presets via caller data (#1957 by @robhogan) - **[Fix]**: Resolver: Fix stale resolutions after adding a nearer `package.json` or retargeting a symlinked directory, which previously needed a restart (#1948 by @robhogan) - **[Fix]**: Resolver: Packages and directories named with an asset extension (eg `lodash.zip`) resolve as modules rather than failing as assets (#2055 by @robhogan) - **[Fix]**: Resolver: Fall through to parent conditions when a nested `"exports"` or `"imports"` condition has no matching target (#2074 by @maximilliangrand) - **[Fix]**: Resolver: An exact `"exports"` or `"imports"` subpath with a `null` or unmatched target no longer resolves through a less specific subpath pattern (#1987 by @kwy404) - **[Fix]**: Use indexed watch folder paths (`[metro-watchFolders]/N/`) for assets outside `projectRoot` (#1892 by @robhogan) - **[Fix]**: Fix `/[metro-project]/` and `/[metro-watchFolders]/` bundle serving on Windows (#2015 by @motiz88) - **[Fix]**: Prevent HMR crash on `[metro-watchFolders]` or `[metro-project]` URLs (#2017 by @motiz88) - **[Fix]**: Remove erroneous `[metro-project]` and `[metro-watchFolders]` resolution of entry points from the API and CLI (#2030 by @motiz88) - **[Fix]**: Fix backslashes in async bundle paths on Windows (`includeAsyncPaths`) (#1938 by @robhogan) - **[Fix]**: Fix stale modules on the client when a file is deleted and recreated during a build, or changes during a build that fails (#2007 by @YevheniiKotyrlo) - **[Fix]**: Fix files created or modified while Metro starts up being missed until restart (#2054 by @cpruijsen) - **[Fix]**: Fix watch mode losing files when a directory replaces a file or symlink, eg when unlinking a package (#2009 by @robhogan) - **[Fix]**: Fix the fallback (Linux/Windows) watcher hanging on stop, and missing changes in a replaced directory, after a watch error (#1967 by @robhogan) - **[Fix]**: Fix the fallback watcher missing changes when a directory changes faster than Windows can report (#1967 by @robhogan) - **[Fix]**: Close the watch handles of a deleted directory and every directory under it in `FallbackWatcher`, which kept the process busy on Windows (#2004 by @YevheniiKotyrlo) - **[Fix]**: `metro-file-map`: Fix removing a non-active duplicate mock changing which mock is active (#1756 by @durvesh1992) - **[Fix]**: Propagate transformer initialisation errors from `Bundler` (#1854 by @Boulea7) - **[Fix]**: Release transform workers and file watchers when Metro fails to initialise (#1963 by @robhogan) - **[Fix]**: Ignore hyphenated and namespaced SVG attributes (eg `stroke-width`) when reading SVG asset dimensions (#1972 by @GabrielDumbrava) - **[Fix]**: Fix generated positions when iterating the mappings of indexed source maps, eg in `composeSourceMaps` (#1976 by @kwy404) - **[Fix]**: `composeSourceMaps` keeps every mapping at a generated column that the last map maps more than once (#1981 by @robhogan) - **[Fix]**: Source maps no longer lose lines after a gap of more than about two million unmapped generated lines (#1983 by @robhogan) - **[Fix]**: `metro-symbolicate` no longer fails on stack frames with no source position, such as `[native code]:0:0` in crash reporter output (#1891 by @robhogan) - **[Fix]**: Fix `metro-symbolicate` parsing of stack frames with Windows absolute paths (#1939 by @robhogan) - **[Performance]**: `metro-source-map`: Faster `Consumer` decoding and position lookups, and `composeSourceMaps` encodes its output directly - ~3.2x faster composition of a bundle map with its Hermes map, using ~15% less memory (#1978, #1979, #1980, #1983 by @robhogan) - **[Performance]**: Resolver: Ask for the package of a directory once for all extension candidates, and check `hierarchicalLookup` candidates from their own file map nodes. First-pass resolution is ~35% faster, net of a ~3% first-build cost from dropping `PackageCache`'s closest-package memo, which also cuts the resolver's retained heap by ~37% (#1945, #1946, #1948 by @robhogan) - **[Performance]**: ~33% faster non-Watchman file system crawl on startup (#1677 by @kitten) - **[Deprecated]**: `server.enhanceMiddleware` logs a deprecation warning when set to anything other than its default. Use `server.unstable_middleware` or `server.unstable_priorityMiddleware` (#2031 by @vzaidman) - **[Deprecated]**: `runServer`'s `unstable_extraMiddleware` option. Use `unstable_priorityMiddleware`, which runs the same middleware in the same place (#2031 by @vzaidman) - **[Deprecated]**: String values of `transformer.enableBabelRuntime` (use `true`) (#1957 by @robhogan) - **[Types]**: Add TypeScript definitions for `metro-runtime` modules, and generate (rather than hand-maintain) types for `metro-file-map` workers (#1996 by @robhogan) > NOTE: Experimental features are not covered by semver and can change at any time. - **[Experimental]**: Add `server.unstable_middleware` and `server.unstable_priorityMiddleware` config options, and `runServer` options of the same names, to add middleware after and before Metro's own. `mergeConfig` combines them from both configs: a later config's `unstable_middleware` runs last and its `unstable_priorityMiddleware` runs first (#2031 by @vzaidman) - **[Experimental]**: Add `server.unstable_onServerCreated` config option and `runServer` option of the same name, called with Metro's server instance before the HTTP server listens (#2031 by @vzaidman) - **[Experimental]**: Fix mismatched asset paths in (release) builds under `unstable_serverRoot`, make them always relative to `projectRoot` (#1917 by @robhogan) **Full Changelog**: v0.87.1...v0.87.2 ```
# Why Expo's `FallbackWatcher`, which Metro uses on Linux and Windows while we default Watchman off, is upstream's from March, plus twins of two later upstream PRs. Upstream has since fixed several bugs in it, and made it start faster with less memory: | Upstream | What | Expo | |---|---|---| | react/metro#1906 | Drop `walker`, list directories from a bounded pool | - | | react/metro#1907 | Watch a directory before listing it | expo#49363 | | react/metro#1967 | Recrawl a directory when Windows doesn't name a change | - | | react/metro#2000 | Remove `micromatch` | expo#51093 | | react/metro#2004 | Close every watch under a deleted directory | - | | react/metro#2105 | Start without a stat per file | - | | react/metro#2106 | Remove the 1s startup delay on Windows | - | | react/metro#2107 | Track only directories and symlinks | - | The fixes matter most on Windows. A deleted watched directory reports its own deletion to its handle again and again until the handle is closed (before libuv 1.53), and the open handle stops the directory being watched again if it's recreated. When changes overflow a directory's buffer, Windows doesn't name what changed, and Expo's watcher reported one file it guessed had changed and missed the rest. Elsewhere, a handle on Linux follows a directory that's moved aside (as npm does to update a package), so it went on watching the old copy. And `walker` doesn't descend into a watch root that's a symlink, so nothing below one was watched. The faster startup also offsets the cost of reading symlinks at crawl since expo#53732, on Linux and Windows. # How This replaces `FallbackWatcher.ts` with a TypeScript port of upstream's `FallbackWatcher.js` at react/metro@82d957f, and drops `walker`. It leaves out `isLiveOnStart()` from react/metro#2003, which only upstream's `Watcher` calls, and react/metro#2108, which needs `Watcher` to start its backends before the crawl (react/metro#2054) first. The old file had nothing upstream lacks. Its extra handling of a watcher that errors does nothing, since Node closes the handle itself before emitting `error`. A directory replaced at the same path, a symlink replaced by a directory and a change Windows doesn't name now have the file map recrawl the path, which `FileMap` already handles. For the last, a gap remains until we port react/metro#2104: a recrawl doesn't stat a file the file map never has, so a change to one is still missed, as all but one were before. The tests are upstream's `FallbackWatcher-test.js`, plus the fork's two tests for expo#48950. ## Performance On a default Expo app, the watcher starts 2.6x faster on Linux (872ms -> 338ms) and 3.8x faster on Windows (1859ms -> 487ms, a second of which was the delay), with 53-66% less RSS. # Test Plan - Unit tests (786). - The `FallbackWatcher` tests three times each on Linux with Node 22.13.0 and 24, and on Windows 11 with Node 24, where it's the default watcher. - Checked that a watch root that's a symlink is now watched below the root. Benchmark (AI-driven), against `main`: starting the watcher on a default Expo SDK 58 app (6,013 directories, 34,274 files) with Metro's default source extensions, 16 interleaved rounds per platform, each run in a fresh process, with a byte-identical control whose medians are all within 0.5% of `main`. Heap and RSS are the growth while watching, after a GC. Linux Mint 22.3 on an i5-4278U, and Windows 11. | Platform | Metric | `main` | This PR [95% CI] | |---|---|---|---| | Linux | Startup | 871.6ms | -61.2% [-61.5, -60.8] | | Linux | Heap | 7.1MB | -30.1% [-30.1, -30.0] | | Linux | RSS | 89.2MB | -65.8% [-66.5, -65.5] | | Windows | Startup | 1859.3ms | -73.8% [-73.9, -73.6] | | Windows | Heap | 7.1MB | -30.0% [-30.0, -30.0] | | Windows | RSS | 116.4MB | -52.7% [-52.7, -52.4] |
# Why `FallbackWatcher` is used as Metro's file watcher in Linux and Windows while we default Watchman off. Upstream has since fixed several bugs in it, and made it start faster with less memory (offsetting eager symlinks: #53732): | Upstream | What | Expo | |---|---|---| | react/metro#1906 | Drop `walker`, list directories from a bounded pool | - | | react/metro#1907 | Watch a directory before listing it | #49363 | | react/metro#1967 | Recrawl a directory when Windows doesn't name a change | - | | react/metro#2000 | Remove `micromatch` | #51093 | | react/metro#2004 | Close every watch under a deleted directory | - | | react/metro#2105 | Start without a stat per file | - | | react/metro#2106 | Remove the 1s startup delay on Windows | - | | react/metro#2107 | Track only directories and symlinks | - | The most significant fixes are on Windows: - A deleted watched directory reports its own deletion to its handle again and again until the handle is closed (libuv/libuv#5013, nodejs/node#61398), and the open handle stops the directory being watched again if it's recreated. - When changes overflow a directory's buffer, Windows doesn't name what changed. The fork guessed at one file and missed the rest - there's now a `'recrawl'` event to catch up. On Linux, probably the most significant is we now correctly watch directory moves in/out of watches, typical in package installs (also using `recrawl`). # How This replaces `FallbackWatcher.ts` with a TypeScript port of upstream's `FallbackWatcher.js` at react/metro@82d957f, and drops `walker`. It leaves out `isLiveOnStart()` from react/metro#2003, which only upstream's `Watcher` calls, and react/metro#2108, which needs `Watcher` to start its backends before the crawl (react/metro#2054) first. The old file had nothing upstream lacks. Its extra handling of a watcher that errors does nothing, since Node closes the handle itself before emitting `error`. The tests are upstream's `FallbackWatcher-test.js`, plus the fork's two tests for #48950. ## Performance On a default Expo app, the watcher starts 2.6x faster on Linux (872ms -> 338ms) and 3.8x faster on Windows (1859ms -> 487ms, a second of which was the delay), with 53-66% less RSS. # Test Plan - Unit tests (786). - The `FallbackWatcher` tests three times each on Linux with Node 22.13.0 and 24, and on Windows 11 with Node 24, where it's the default watcher. - Checked that a watch root that's a symlink is now watched below the root. Benchmark (AI-driven), against `main`: starting the watcher on a default Expo SDK 58 app (6,013 directories, 34,274 files) with Metro's default source extensions, 16 interleaved rounds per platform, each run in a fresh process, with a byte-identical control whose medians are all within 0.5% of `main`. Heap and RSS are the growth while watching, after a GC. Linux Mint 22.3 on an i5-4278U, and Windows 11. | Platform | Metric | `main` | This PR [95% CI] | |---|---|---|---| | Linux | Startup | 871.6ms | -61.2% [-61.5, -60.8] | | Linux | Heap | 7.1MB | -30.1% [-30.1, -30.0] | | Linux | RSS | 89.2MB | -65.8% [-66.5, -65.5] | | Windows | Startup | 1859.3ms | -73.8% [-73.9, -73.6] | | Windows | Heap | 7.1MB | -30.0% [-30.0, -30.0] | | Windows | RSS | 116.4MB | -52.7% [-52.7, -52.4] |
# Why `FallbackWatcher` is used as Metro's file watcher in Linux and Windows while we default Watchman off. Upstream has since fixed several bugs in it, and made it start faster with less memory (offsetting eager symlinks: #53732): | Upstream | What | Expo | |---|---|---| | react/metro#1906 | Drop `walker`, list directories from a bounded pool | - | | react/metro#1907 | Watch a directory before listing it | #49363 | | react/metro#1967 | Recrawl a directory when Windows doesn't name a change | - | | react/metro#2000 | Remove `micromatch` | #51093 | | react/metro#2004 | Close every watch under a deleted directory | - | | react/metro#2105 | Start without a stat per file | - | | react/metro#2106 | Remove the 1s startup delay on Windows | - | | react/metro#2107 | Track only directories and symlinks | - | The most significant fixes are on Windows: - A deleted watched directory reports its own deletion to its handle again and again until the handle is closed (libuv/libuv#5013, nodejs/node#61398), and the open handle stops the directory being watched again if it's recreated. - When changes overflow a directory's buffer, Windows doesn't name what changed. The fork guessed at one file and missed the rest - there's now a `'recrawl'` event to catch up. On Linux, probably the most significant is we now correctly watch directory moves in/out of watches, typical in package installs (also using `recrawl`). # How This replaces `FallbackWatcher.ts` with a TypeScript port of upstream's `FallbackWatcher.js` at react/metro@82d957f, and drops `walker`. It leaves out `isLiveOnStart()` from react/metro#2003, which only upstream's `Watcher` calls, and react/metro#2108, which needs `Watcher` to start its backends before the crawl (react/metro#2054) first. The old file had nothing upstream lacks. Its extra handling of a watcher that errors does nothing, since Node closes the handle itself before emitting `error`. The tests are upstream's `FallbackWatcher-test.js`, plus the fork's two tests for #48950. ## Performance On a default Expo app, the watcher starts 2.6x faster on Linux (872ms -> 338ms) and 3.8x faster on Windows (1859ms -> 487ms, a second of which was the delay), with 53-66% less RSS. # Test Plan - Unit tests (786). - The `FallbackWatcher` tests three times each on Linux with Node 22.13.0 and 24, and on Windows 11 with Node 24, where it's the default watcher. - Checked that a watch root that's a symlink is now watched below the root. Benchmark (AI-driven), against `main`: starting the watcher on a default Expo SDK 58 app (6,013 directories, 34,274 files) with Metro's default source extensions, 16 interleaved rounds per platform, each run in a fresh process, with a byte-identical control whose medians are all within 0.5% of `main`. Heap and RSS are the growth while watching, after a GC. Linux Mint 22.3 on an i5-4278U, and Windows 11. | Platform | Metric | `main` | This PR [95% CI] | |---|---|---|---| | Linux | Startup | 871.6ms | -61.2% [-61.5, -60.8] | | Linux | Heap | 7.1MB | -30.1% [-30.1, -30.0] | | Linux | RSS | 89.2MB | -65.8% [-66.5, -65.5] | | Windows | Startup | 1859.3ms | -73.8% [-73.9, -73.6] | | Windows | Heap | 7.1MB | -30.0% [-30.0, -30.0] | | Windows | RSS | 116.4MB | -52.7% [-52.7, -52.4] | (cherry picked from commit 5ed1f80)
Summary
Deleting a directory that
FallbackWatcherwatches leaves watch handles open, and on Windows each of them keeps the process busy until it restarts.renamewhose filename is the directory's own absolute path, and before 1.53 it re-arms the read for as long as the handle is open (uv__process_fs_event_reqinsrc/win/fs-event.c; nodejs/node#61398). On libuv 1.49 to 1.52, which Node bundles from 22.12, 23.1 and 24 through 26.10.0, no'error'follows, so the error handler never runs.#normalizeChangejoins the absolute path onto the directory, finds nothing there and closes nothing.#dirRegistrythrough#unregisterDir, but closes only#watched[fullPath]. A nested handle left in#watchedalso stops#watchdirfrom watching that path again once it is recreated.A recursive delete reaches both: the parent's pending read is torn down with its own deletion, so the nested deletions it had queued are never delivered.
libuv 1.53 (libuv/libuv#5013) follows the
renamewith anENOENTerror and stops re-arming. No Node release bundles it yet; reading itsuv__process_fs_event_req, therenamestill arrives first, and a handle closed inside its listener gets neither the error nor another read.Windows 11, Node 26.5.0,
FallbackWatcheroverdist/static/chunk-{0..19}/index.js, CPU seconds in 4 s of idle afterdistis deleted (script in the first comment):distdeleteddistdeleted and recreatedmainWith the change the recreated tree is also watched afresh: the watcher reports the 20 files and the 22 recreated directories, where
mainreports only the 20 files because the old handles still occupy#watched.How it works
#reconcileWatchedDirectory. If that handle is still the current one, it closes the handle and every handle beneath it, then processes the path the way the parent'srenamewould: a missing directory takes the deletion branch, and a recreated one is walked afresh and recrawled, as metro-file-map: Fix missed changes and a stop hang in FallbackWatcher #1967 does for a replaced directory. A stale handle's later reports are ignored, and the root only closes.#stopWatchingTree, matched ondirpath + path.sepso thatdist-cachesurvivesdist. It runs only for a path the watcher knew as a directory, so a deleted file costs nothing extra.expo/expo#50906 closes the same two gaps in Expo's fork of this watcher.
Changelog: [Fix] Close the watch handles of a deleted directory and every directory under it in
FallbackWatcher, which kept the process busy on WindowsTest plan
New
FallbackWatcher-test.jscases point everyfs.watchhandle at a quiet directory, so each test decides which report reaches which listener and sees which handles were closed:Against
main'sFallbackWatcher.jsthe first four fail (Tests: 4 failed, 10 passed), and all pass with the change. Each also fails under a mutation of the behaviour it names: a self-report that closes nothing, a parent's report that closes only the deleted directory, a stale handle's report that is processed, and a root self-report that closes the whole tree.yarn typecheck,yarn typecheck-ts,yarn lint,yarn format-check,yarn buildandyarn test-smokepass.yarn jest: 151 suites, 2756 passed and 26 skipped;packages/metro-file-maphas 660 passed against 655 onmain.The table above, measured on Windows 11 with Node 26.5.0. On Linux and macOS libuv names a watched directory's own event by its basename, so the self-report branch runs only on Windows; the subtree close on a parent's report is platform-neutral, and the tests drive every path on every platform.