Skip to content

fix(arborist): use a set for bundled-dependency traversal - #10127

Merged
martinrrm merged 1 commit into
npm:latestfrom
jeffwidman:perf/bundler-visited-set
Nov 6, 2026
Merged

martinrrm merged 1 commit into
npm:latestfrom
jeffwidman:perf/bundler-visited-set

Conversation

@jeffwidman

Copy link
Copy Markdown
Member

Use a traversal-local Set to track visited nodes in Arborist’s getBundler(), while retaining the existing behavior for explicitly supplied arrays.

Why this should reduce work

The existing path array is a visited collection, not a stack: nodes are appended and never popped. Each includes() searches the growing collection again. A dependency shared by many packages can therefore require substantial repeated scanning even though the traversal already avoids revisiting nodes.

A set expresses the same visited-node membership test without those linear searches. This does not change traversal order, bundle selection, or the dependency graph, and does not introduce a persistent cache or invalidation rules.

Compatibility

The optional traversal argument is exposed as an array in the public TypeScript declarations. Explicit arrays therefore continue through the original array operations, including mutation order, existing duplicates, and already-visited behavior. Only normal calls that omit the argument start with a set.

The added regression test covers those array behaviors and verifies that separate default calls have independent traversal state.

Local measurements

I applied this same method change directly to an isolated npm 11.17.0 installation, using Node 24.22.0. These final measurements do not use a preload hook or a CPU profiler.

For a large workspace snapshot with 5,405 original lockfile entries, I updated prettier to 3.9.10 with:

node <npm-installation>/bin/npm-cli.js install prettier@3.9.10 \
  --package-lock-only --ignore-scripts --audit=false --fund=false \
  --timing --force --offline

Each sample started from the same manifests and lockfile, in a fresh directory, with a warmed metadata cache. After one warmup per variant, three measured pairs alternated execution order.

Median Original Patched Change
Child-process user + system CPU 9.468 s 8.310 s 12.2% lower
Wall time 8.280 s 7.128 s 13.9% lower

Every resulting lockfile was byte-identical across variants.

A tiny-project control with one local dependency used seven measured alternating pairs, excluding warmups:

Median Original Patched
CPU 0.360330 s 0.360057 s
Wall time 0.286228 s 0.286556 s

Those control differences are effectively noise. These are local native-command measurements, not a claim about every project or complete dependency-update jobs. The large workspace fixture is not included; the public synthetic example below reproduces the eliminated membership-search work without relying on that fixture.

Validation

On this PR’s upstream checkout, using Node 24.22.0:

  • node bin/npm-cli.js test --workspace=@npmcli/arborist --ignore-scripts -- --jobs=4 — passed: 59 test files; 100% statements, branches, functions, and lines.
  • node node_modules/eslint/bin/eslint.js workspaces/arborist/lib/node.js workspaces/arborist/test/node.js — passed.
  • Separate generated-graph differential checks — passed: 300 graphs, 15,000 default-call comparisons, and 15,000 explicit-array comparisons, including node relocation and comparison of the populated arrays.
  • The npm CLI-wide test suite was not run.
Public synthetic reproduction of the avoided work

Run this from the patched repository root after installing its development dependencies. It constructs 512 packages sharing one dependency and compares the retained array path with the set path.

The counts are logical membership-search work, not a timing benchmark or an estimate of overall speedup.

node <<'JS'
const assert = require('node:assert/strict')
const Node = require('./workspaces/arborist/lib/node.js')

class VisitedArray extends Array {
  lookups = 0
  entriesSearched = 0

  includes (node) {
    const index = super.indexOf(node)
    this.lookups++
    this.entriesSearched += index < 0 ? this.length : index + 1
    return index >= 0
  }
}

class VisitedSet extends Set {
  lookups = 0

  has (node) {
    this.lookups++
    return super.has(node)
  }
}

const names = Array.from({length: 512}, (_, i) => `provider-${i}`)
const root = new Node({
  path: '/synthetic',
  pkg: {
    name: 'root',
    version: '1.0.0',
    dependencies: Object.fromEntries(names.map(name => [name, '*'])),
  },
})
const shared = new Node({
  parent: root,
  pkg: {name: 'shared', version: '1.0.0'},
})
for (const name of names) {
  new Node({
    parent: root,
    pkg: {name, version: '1.0.0', dependencies: {shared: '*'}},
  })
}

const array = new VisitedArray()
const set = new VisitedSet()
assert.equal(shared.getBundler(array), null)
assert.equal(shared.getBundler(set), null)
assert.equal(array.lookups, 1538)
assert.equal(array.entriesSearched, 133889)
assert.equal(set.lookups, 1538)
console.log({
  arrayLookups: array.lookups,
  arrayEntriesSearched: array.entriesSearched,
  setLookups: set.lookups,
})
JS

The same 1,538 membership checks search 133,889 array entries in total; the set performs 1,538 membership lookups. Both return the same result.

Prepared with assistance from GitHub Copilot. The validation results above were obtained locally.

References

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@jeffwidman

jeffwidman commented Oct 15, 2026 •

Copy link
Copy Markdown
Member Author

Compatibility question for maintainers: is the optional traversal-state argument to Node#getBundler() supported public API, or internal recursion bookkeeping?

This determines whether we can simplify the patch:

  • Arborist exports Node, and DefinitelyTyped declares getBundler(path?: Node[]): Node | null. However, those are third-party declarations; the Arborist README does not document this method or argument. I don’t want to infer an upstream compatibility guarantee from the types alone.
  • In the Arborist production callers I checked, only recursive calls pass the argument explicitly; other callers omit it. The collection tracks visited-node membership rather than acting as a stack, so a Set fits its purpose directly.
  • This patch conservatively preserves explicit-array behavior, including mutation of the supplied array, while using a Set for default calls. The reported performance gains already include that compatibility path.

If the argument is supported API, dropping array support would break callers passing arrays and should follow the appropriate semver policy. If it is internal, I would prefer removing the compatibility branch and keeping the traversal Set-only. Simply converting incoming arrays to Sets would not preserve the existing array-mutation behavior.

Would you prefer retaining array compatibility for a patch release, or treating the argument as internal and simplifying this PR to Set-only?

I haven’t identified an external caller depending on the array argument; the compatibility handling is precautionary, not evidence of known downstream usage.

EDIT:
Further simplification PR here:

nkolev92 pushed a commit that referenced this pull request Nov 6, 2026
)

<!-- What / Why -->
<!-- Describe the request in detail. What it does and why it's being
changed. -->

Move the existing no-applicable-override return in `Edge.satisfiedBy()`
ahead of the bundle-membership check.

### Why this removes work

Bundle membership determines whether dependency validation should use an
overridden spec or the original spec. Without an applicable override,
that distinction cannot affect the result, but the current ordering
still asks `node.inDepBundle`, potentially traversing the dependency
graph.

Checking the existing cheap condition first avoids that irrelevant
traversal. This is a guard reorder, not a new cache, a skipped
dependency-validation step, or a public API change. When an override
applies, the existing bundle handling and validation logic are
unchanged.

The regression test covers both absent override state and an inherited
override set with no applicable rule. It checks both satisfying and
unsatisfying versions and fails if bundle membership is queried.

### Local measurements

I applied only this guard reorder to an isolated npm 11.17.0
installation using Node 24.22.0, then compared it with an unmodified
installation. Neither arm includes the separate visited-set
optimization.

The workload was a large workspace snapshot with 5,405 original lockfile
entries, updating `prettier` to `3.9.10`:

```sh
# Lockfile writer, with the manifest updated before invoking npm:
node <npm-installation>/bin/npm-cli.js install prettier@3.9.10 \
  --package-lock-only --ignore-scripts --audit=false --fund=false \
  --timing --force --offline

# Compatibility-check shape, with the original manifest:
node <npm-installation>/bin/npm-cli.js install prettier@3.9.10 \
  --package-lock-only --ignore-scripts --audit=false --fund=false \
  --timing --dry-run=true --offline
```

Each invocation started from fresh copies of the same inputs and a warm
metadata cache, in a four-CPU/12-GB container with networking disabled.
One warmup per arm was excluded, followed by three measured alternating
pairs. Timed runs used patched source directly, without preload hooks or
profiling.

| Command | Median CPU: original -> patched | Median wall: original ->
patched |
| --- | --- | --- |
| Lockfile writer | 9.277 -> 7.359 s (**20.7% lower**) | 8.080 -> 6.326
s (**21.7% lower**) |
| Dry-run checker | 7.565 -> 5.853 s (**22.6% lower**) | 6.528 -> 4.824
s (**26.1% lower**) |

All package manifests and lockfiles were byte-identical across variants.
npm output matched after removing timing information; every invocation
exited successfully.

A tiny-project control with one local dependency used seven alternating
measured pairs after warmups. CPU was 0.346975 -> 0.348489 s and wall
was 0.271516 -> 0.272622 s, both about 0.4% higher, with identical
output. Those small differences do not establish a material regression.

These are local native-command measurements, not a claim about every
project or complete dependency-update jobs. The large fixture is not
included. The synthetic example below independently demonstrates the
eliminated work.

The benchmark runtime uses the older bundle/shrinkwrap predicate; this
PR uses current upstream's `inDepBundle` predicate. In both cases the
change only moves the no-override guard ahead of the existing predicate.

### Validation

On this standalone branch based on `latest`, using Node 24.22.0:

- `node bin/npm-cli.js test --workspace=@npmcli/arborist
--ignore-scripts -- --jobs=4` — **passed: 59 test files; 100%
statements, branches, functions, and lines**.
- `node node_modules/eslint/bin/eslint.js
workspaces/arborist/lib/edge.js workspaces/arborist/test/edge.js` —
**passed**.
- Public synthetic example below — **passed: 128 valid edges in both
variants; recursive bundle-traversal calls reduced from 49,408 to
zero**.
- The npm CLI-wide suite was not run.

<details>
<summary>Public synthetic reproduction</summary>

Run from the repository root after installing development dependencies.
This counts work, not elapsed time. The graph has no overrides, so
bundle membership cannot affect these edge-satisfaction results.

```sh
node <<'JS'
const assert = require('node:assert/strict')
const {resolve} = require('node:path')
const Node = require(resolve('workspaces/arborist/lib/node.js'))

const names = Array.from({length: 128}, (_, i) => `provider-${i}`)
const root = new Node({
  path: '/synthetic',
  pkg: {
    name: 'root',
    version: '1.0.0',
    dependencies: Object.fromEntries(names.map(name => [name, '*'])),
  },
})
const shared = new Node({
  parent: root,
  pkg: {name: 'shared', version: '1.0.0'},
})
const providers = names.map(name => new Node({
  parent: root,
  pkg: {name, version: '1.0.0', dependencies: {shared: '*'}},
}))

let bundleTraversalCalls = 0
const getBundler = Node.prototype.getBundler
Node.prototype.getBundler = function (...args) {
  bundleTraversalCalls++
  return getBundler.apply(this, args)
}
try {
  for (const provider of providers) {
    assert.equal(provider.edgesOut.get('shared').satisfiedBy(shared), true)
  }
} finally {
  Node.prototype.getBundler = getBundler
}
console.log({validatedEdges: providers.length, bundleTraversalCalls})
JS
```

</details>

Prepared with assistance from GitHub Copilot. Validation results above
were obtained locally.

## References
<!-- Examples:
  Related to #0
  Depends on #0
  Blocked by #0
  Fixes #0
  Closes #0
-->

- Related to [#10127](#10127), but
this branch is independent and does not include that change. That PR
makes necessary traversals cheaper; this PR avoids traversals whose
result is irrelevant. The benchmark savings should not be added
together.
- Retains the override/bundle semantics covered by
[#9235](#9235).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@martinrrm
martinrrm merged commit ab930df into npm:latest Nov 6, 2026
24 checks passed
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

🎉 Backport to release/v11 created: #10253

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants