Skip to content

Commit d83ae43

Browse files
committed
Resolver: Collect file system observations per resolution under unstable_incrementalResolution
Stacked on #1948. The first consumer of the `Observations` API from #1944. When `resolver.unstable_incrementalResolution` is enabled, `ModuleResolver.resolveDependency` creates an observations record at the start of each resolution, and everything that resolution looks up in the file map is recorded into it. The record is returned on the `BundlerResolution` as `unstable_observations`. Nothing reads it yet - invalidating from it is the next step - so there's no behaviour change, and with the flag off nothing is allocated. The resolution context given to `metro-resolver` doesn't change. `ModuleResolver` already builds a context per resolution, so when the flag is on it binds the file system capabilities to that resolution's record (`fileSystemLookup: p => fileSystemLookup(p, observations)`), and when it's off it passes the same functions as before. That means a custom `resolveRequest` records whatever it looks up through the context, without knowing about any of this. The observations parameter only appears on Metro's internal option types. What's recorded: - `fileSystemLookup`, and `resolveAsset` through it. - `getPackageForModule`, down to `hierarchicalLookup`. There's no memo in the way since #1948. - `doesFileExist`. `FileSystem.exists` can't record, so when recording this is answered by `lookup`, which agrees with it - true for exactly the paths found to be a file. Putting the record on the `BundlerResolution` means `DependencyGraph`'s whole-resolution cache replays it for free - every origin given a cached resolution gets its observations too. The one other memo is the empty module, which is resolved once and cached, so a resolution that lands on it returns a copy with the union of what led there and what resolving the empty module observed. Not included, to follow: - The contents of `package.json`. `getPackage` reads with `fs` outside the file map, and Metro has no way to turn an absolute path into a canonical one. The file is recorded in `existence` by `hierarchicalLookup`, so adding or removing one is covered, but editing one isn't. - Haste lookups, which have no bucket yet. - Failed resolutions. They throw, so there's nowhere to put what they observed. Resolution time in isolation, replaying every `DependencyGraph.resolveDependency` call made by one iOS dev build of the benchmark app (described in the test plan), through the whole-resolution cache. Nothing is transformed or serialised, so these are percentages of resolution, not of a build. 7 interleaved rounds. Resolutions are identical with the flag on and off. | scenario | #1948 | this diff, flag off | this diff, flag on | |---|---|---|---| | first build (ms) | 95.9 | 95.8 (−0.1%) | 111.6 (+16.5%) | | rebuild, nothing changed (ms) | 7.61 | 7.64 (+0.4%) | 7.80 (+2.1%) | | after a source edit, re-resolving the edited module's dependencies (µs) | 153 | 159 (+4.1%) | 180 (+13.2%) | | after a `package.json` change, re-resolving everything (ms) | 79.8 | 80.1 (+0.4%) | 93.1 (+16.2%) | | heap retained after resolving (MB) | | 5.3 | 18.8 (3.5x) | Flag off is within noise of #1948. (The source edit row is 8 resolutions, so that's under a microsecond each, and the runs overlap.) Flag on costs about 16% of resolution time wherever everything is resolved, which is ~2µs per resolution, and 3.5x the retained heap. On the benchmark app that's 100k entries across 6.9k distinct resolutions - a median of 14 each, 90th percentile 27 - naming 28k distinct paths. Nearly all of it is `existence`, and most of that is extension and platform candidates that missed (`a.ios.js`, `a.native.js`, ...), which can't collapse because the directory they're in exists. That's the memory to go after before this is worth turning on, e.g. by recording the directory once instead. ``` yarn jest packages/metro-file-map packages/metro-resolver packages/metro/src/node-haste packages/metro/src/DeltaBundler packages/metro/src/integration_tests yarn flow check yarn typecheck-ts yarn verify-api-snapshots ``` New tests in `resolver-test.js` assert the exact sets recorded for a relative import's candidates, each level probed for a package, a symlink (recorded as `content`, with lookups recorded by real path), asset variants, and a resolution that lands on the empty module. They also check that there's no `unstable_observations` by default, and that origins sharing a cached resolution share its observations. **Benchmark app** - a synthetic mid-size RN 0.87 app: 23 common dependencies (Reanimated, React Navigation, TanStack Query, lodash, etc.) and ~1,000 generated first-party modules, 60% of them in a workspace package outside `projectRoot` with its own `node_modules`. The iOS dev bundle is 2.8k modules, from a file map of 34k files. Timings replay the `resolveDependency` calls a real build of it makes against a fresh `DependencyGraph` per process, in interleaved rounds, with source and `package.json` edits made on disk and picked up by the watcher. A real build of this app takes around 4s even with a warm transform cache, so resolution is about 2% of it. Changelog: Internal
1 parent 4c23982 commit d83ae43

6 files changed

Lines changed: 326 additions & 26 deletions

File tree

‎packages/metro/src/DeltaBundler/__tests__/resolver-test.js‎

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3008,6 +3008,185 @@ function dep(name: string): TransformResultDependency {
30083008
});
30093009
});
30103010

3011+
describe('unstable_incrementalResolution', () => {
3012+
const incremental: InputConfigT = {
3013+
resolver: {unstable_incrementalResolution: true},
3014+
};
3015+
// Observed paths are canonical: relative to the root, with system
3016+
// separators.
3017+
const canonical = (...posixPaths: Array<string>) =>
3018+
new Set(posixPaths.map(posixPath => joinPath(...posixPath.split('/'))));
3019+
3020+
test('resolutions carry no observations by default', async () => {
3021+
setMockFileSystem({'index.js': '', 'a.js': ''});
3022+
resolver = await createResolver();
3023+
expect(
3024+
resolver.resolve(p('/root/index.js'), dep('./a')),
3025+
).not.toHaveProperty('unstable_observations');
3026+
});
3027+
3028+
test('records every candidate probed for a relative import', async () => {
3029+
setMockFileSystem({'index.js': '', 'a.js': ''});
3030+
resolver = await createResolver(incremental, 'ios');
3031+
expect(resolver.resolve(p('/root/index.js'), dep('./a'))).toEqual({
3032+
type: 'sourceFile',
3033+
filePath: p('/root/a.js'),
3034+
unstable_observations: {
3035+
// A more specific candidate appearing changes the result
3036+
existence: canonical(
3037+
'a',
3038+
'a.ios.js',
3039+
'a.native.js',
3040+
'a.js',
3041+
'package.json',
3042+
),
3043+
content: new Set(),
3044+
},
3045+
});
3046+
});
3047+
3048+
test('records each level probed for a package', async () => {
3049+
setMockFileSystem({
3050+
deep: {dir: {'index.js': ''}},
3051+
node_modules: {
3052+
pkg: {
3053+
'package.json': JSON.stringify({name: 'pkg', main: 'main.js'}),
3054+
'main.js': '',
3055+
},
3056+
},
3057+
});
3058+
resolver = await createResolver(incremental, 'ios');
3059+
expect(
3060+
resolver.resolve(p('/root/deep/dir/index.js'), dep('pkg')),
3061+
).toEqual({
3062+
type: 'sourceFile',
3063+
filePath: p('/root/node_modules/pkg/main.js'),
3064+
unstable_observations: {
3065+
existence: canonical(
3066+
// The closest package to the origin
3067+
'deep/dir/index.js',
3068+
'deep/dir/package.json',
3069+
'deep/package.json',
3070+
'package.json',
3071+
// Each node_modules on the way up. A missing one is one entry,
3072+
// however many packages are looked up beneath it.
3073+
'deep/dir/node_modules',
3074+
'deep/node_modules',
3075+
'node_modules',
3076+
// The package scope of the files directly in node_modules
3077+
'node_modules/package.json',
3078+
// A file is preferred to a package of the same name
3079+
'node_modules/pkg.ios.js',
3080+
'node_modules/pkg.native.js',
3081+
'node_modules/pkg.js',
3082+
'node_modules/pkg.ios.json',
3083+
'node_modules/pkg.native.json',
3084+
'node_modules/pkg.json',
3085+
'node_modules/pkg',
3086+
'node_modules/pkg/package.json',
3087+
'node_modules/pkg/main.js',
3088+
),
3089+
content: new Set(),
3090+
},
3091+
});
3092+
});
3093+
3094+
test('records a traversed symlink as content, and lookups by real path', async () => {
3095+
setMockFileSystem({'index.js': '', real: {'x.js': ''}});
3096+
fs.symlinkSync(p('/root/real'), p('/root/link'));
3097+
resolver = await createResolver(incremental, 'ios');
3098+
expect(resolver.resolve(p('/root/index.js'), dep('./link/x'))).toEqual({
3099+
type: 'sourceFile',
3100+
filePath: p('/root/real/x.js'),
3101+
unstable_observations: {
3102+
existence: canonical(
3103+
'real/x',
3104+
'real/x.ios.js',
3105+
'real/x.native.js',
3106+
'real/x.js',
3107+
'real/package.json',
3108+
'package.json',
3109+
),
3110+
// Retargeting the link changes what every path through it means
3111+
content: canonical('link'),
3112+
},
3113+
});
3114+
});
3115+
3116+
test('records every asset variant probed', async () => {
3117+
setMockFileSystem({
3118+
'index.js': '',
3119+
'asset.png': '',
3120+
'asset@2x.png': '',
3121+
});
3122+
resolver = await createResolver(incremental, 'ios');
3123+
expect(
3124+
resolver.resolve(p('/root/index.js'), dep('./asset.png'))
3125+
.unstable_observations,
3126+
).toEqual({
3127+
existence: canonical(
3128+
'asset.png',
3129+
'asset@1x.png',
3130+
'asset@1.5x.png',
3131+
'asset@2x.png',
3132+
'asset@3x.png',
3133+
'asset@4x.png',
3134+
'package.json',
3135+
),
3136+
content: new Set(),
3137+
});
3138+
});
3139+
3140+
test('a resolution landing on the empty module includes what resolving the empty module observed', async () => {
3141+
setMockFileSystem({
3142+
'empty.js': '',
3143+
withBrowser: {
3144+
'package.json': JSON.stringify({
3145+
name: 'with-browser',
3146+
browser: {'./gone.js': false},
3147+
}),
3148+
'index.js': '',
3149+
'gone.js': '',
3150+
},
3151+
});
3152+
resolver = await createResolver(
3153+
{
3154+
resolver: {
3155+
emptyModulePath: p('/root/empty.js'),
3156+
unstable_incrementalResolution: true,
3157+
},
3158+
},
3159+
'ios',
3160+
);
3161+
expect(
3162+
resolver.resolve(p('/root/withBrowser/index.js'), dep('./gone')),
3163+
).toEqual({
3164+
type: 'sourceFile',
3165+
filePath: p('/root/empty.js'),
3166+
unstable_observations: {
3167+
existence: canonical(
3168+
// What led to the empty module
3169+
'withBrowser/gone',
3170+
'withBrowser/package.json',
3171+
// What resolving the empty module observed
3172+
'empty.js',
3173+
'package.json',
3174+
),
3175+
content: new Set(),
3176+
},
3177+
});
3178+
});
3179+
3180+
test('origins sharing a cached resolution share its observations', async () => {
3181+
setMockFileSystem({'index.js': '', 'other.js': '', 'a.js': ''});
3182+
resolver = await createResolver(incremental, 'ios');
3183+
const first = resolver.resolve(p('/root/index.js'), dep('./a'));
3184+
const second = resolver.resolve(p('/root/other.js'), dep('./a'));
3185+
expect(second).toBe(first);
3186+
expect(second.unstable_observations?.existence.size).toBeGreaterThan(0);
3187+
});
3188+
});
3189+
30113190
describe('schemeResolvers', () => {
30123191
test('config schemeResolvers are applied to scheme-prefixed specifiers', async () => {
30133192
setMockFileSystem({'index.js': '', 'a.js': ''});

‎packages/metro/src/DeltaBundler/types.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,9 +162,21 @@ export type AllowOptionalDependenciesWithOptions = {
162162
export type AllowOptionalDependencies =
163163
boolean | AllowOptionalDependenciesWithOptions;
164164

165+
// What a resolution observed of the file system: canonical paths whose
166+
// addition or removal can change its result, and those whose modification
167+
// can too. Satisfies `metro-file-map`'s `Observations`, which populates it.
168+
export type ResolutionObservations = Readonly<{
169+
existence: Set<string>,
170+
content: Set<string>,
171+
}>;
172+
165173
export type BundlerResolution = Readonly<{
166174
type: 'sourceFile',
167175
filePath: string,
176+
// What this resolution observed of the file system, if
177+
// `resolver.unstable_incrementalResolution` is enabled. It is shared by
178+
// every caller given this resolution, so must not be mutated.
179+
unstable_observations?: ResolutionObservations,
168180
}>;
169181

170182
export type Options<T = MixedOutput> = Readonly<{

‎packages/metro/src/node-haste/DependencyGraph.js‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import type {
1313
BundlerResolution,
14+
ResolutionObservations,
1415
TransformResultDependency,
1516
} from '../DeltaBundler/types';
1617
import type {DynamicRoot} from '../lib/dynamicRoots';
@@ -138,8 +139,8 @@ export default class DependencyGraph extends EventEmitter {
138139
);
139140
this._resolutionCache = new Map();
140141
this.#packageCache = new PackageCache({
141-
getClosestPackage: absoluteModulePath =>
142-
this._getClosestPackage(absoluteModulePath),
142+
getClosestPackage: (absoluteModulePath, observations) =>
143+
this._getClosestPackage(absoluteModulePath, observations),
143144
});
144145
this._createModuleResolver();
145146
});
@@ -219,6 +220,7 @@ export default class DependencyGraph extends EventEmitter {
219220

220221
_getClosestPackage(
221222
absoluteModulePath: string,
223+
observations?: ?ResolutionObservations,
222224
): ?{packageJsonPath: string, packageRelativePath: string} {
223225
const result = this._fileSystem.hierarchicalLookup(
224226
absoluteModulePath,
@@ -227,6 +229,7 @@ export default class DependencyGraph extends EventEmitter {
227229
breakOnSegment: 'node_modules',
228230
subpathType: 'f',
229231
},
232+
observations,
230233
);
231234
return result
232235
? {

0 commit comments

Comments
 (0)