Skip to content

install: break folder dependency cycles in the hoist tree builder - #34688

Closed
robobun wants to merge 3 commits into
mainfrom
farm/0dd017ae/fix-migrate-folder-cycle-hang
Closed

robobun wants to merge 3 commits into
mainfrom
farm/0dd017ae/fix-migrate-folder-cycle-hang

Conversation

@robobun

@robobun robobun commented Jul 19, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #25202.

Repro

mkdir repro && cd repro
cat > package.json <<'JSON'
{ "name": "root", "dependencies": { "pkg": "file:pkg" } }
JSON
mkdir pkg && cat > pkg/package.json <<'JSON'
{ "name": "pkg", "version": "1.0.0", "dependencies": { "pkg": "^1.0.0" } }
JSON
npm install --package-lock-only   # npm 11.x
bun pm migrate                    # hangs at 100% CPU

Same hang for bun install with the package-lock.json present, for an npm: alias under the same name ("pkg": "npm:other@^1.0.0"), for two file: link targets that depend on each other (a depends on b, b depends on a), and (without any migration) for bun install on a file: folder whose package.json declares foo: "workspace:." (#25202).

The migration shape is what npm 11.x writes for file: linked folders: it records the target's declared dependencies but does not install them, so there is no nested <target>/node_modules/<name> lockfile entry.

Cause

The npm lockfile migration resolves a link target's dependency by walking up to node_modules/<name>, which is the "link": true entry pointing back at a folder package. workspace:. inside a file: folder resolves that dep to the folder package itself. Either way a folder package ends up with a dependency that resolves to itself (direct case) or to another folder package that reaches back to it (mutual case).

Tree::process_subtree short-circuits folder resolutions straight to Placement without going through hoist_dependency, which is where the dedup (same package id already placed in an ancestor tree) lives. The placement handler then re-enqueues the package's subtree unconditionally, so a folder package that reaches itself re-enqueues forever.

Fix

Before re-enqueueing a placed folder dependency's subtree, walk the enclosing subtree chain (next_id and its parents) and skip the enqueue if the same package id is already the subject of one. The dep is still placed, so its entry reaches bun.lock and the parser can resolve it on reload (needed for the aliased case where the dep name differs from the package name); only the re-enqueue that would loop is cut.

Only the subtree chain is consulted, not sibling placements, and the walk is gated on the resolution being Folder, so acyclic layouts and non-folder placements are unchanged.

Verification

Four new cases in test/cli/install/migration/migrate.test.ts: three package-lock.json migrations (self-named dep, npm: alias under the same name, and a mutual a/b cycle, each the lockfile npm 11.x writes for that tree) and one plain bun install on a file: folder whose target declares workspace:. under a different name (#25202). Each spawns with a 30 s process timeout so the hang surfaces as a normal assertion failure, and each asserts the resulting bun.lock round-trips through bun install --frozen-lockfile.

$ git stash push -- src/ && bun bd test migrate.test.ts -t "terminates when a file:"
 0 pass, 4 fail  (each ~30 s, stderr empty)
$ git stash pop  && bun bd test migrate.test.ts -t "terminates when a file:"
 4 pass, 0 fail  (each <1 s)

The rest of migrate.test.ts and the file:/folder tests in bun-install.test.ts pass unchanged.

Related issues

#25631, #21191, #23453 and #13223 report deep/infinite node_modules nesting for file:..-style folder dependencies. Those reproduce identically with and without this change; they are about the folder package being materialised by copying its source directory (which contains the dependent, whose node_modules contains the folder package again), not about the hoist tree builder, and are left for a separate fix.


no test proof · iteration 0 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/cli/install/migration/migrate.test.ts

Migrating an npm package-lock.json that has a file: link target depending on
its own name (or on another link target that depends back on it) hung forever
at 100% CPU. npm records such a dependency in the lockfile but does not
resolve it, so the migration follows the root node_modules/<name> link back
to the folder package itself. The hoist builder's folder short-circuit then
placed that package inside its own subtree and re-enqueued it without bound.

Walk the enclosing subtree chain before placing a folder dependency and skip
it when the same package id is already a subject of one. Non-cycle layouts
are unchanged because the walk only matches on the package being the subject
of an ancestor subtree, not on sibling placements.
@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Changes

Folder dependency cycle handling

Layer / File(s) Summary
Detect ancestor folder cycles
src/install/lockfile/Tree.rs
Tree::process_subtree traverses ancestors for matching package IDs before placing folder-tagged dependencies, preventing repeated subtree enqueuing.
Validate cyclic migration scenarios
test/cli/install/migration/migrate.test.ts
Adds file-link fixtures and bounded regression tests for cyclic file: dependencies and workspace:. self-references, including lockfile and installation assertions.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly names the main change: preventing folder dependency cycles in the hoist tree builder.
Description check ✅ Passed The description is thorough and covers the fix, repro, and verification, even though it doesn't use the template headings exactly.

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Jul 19, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:52 PM PT - Jul 18th, 2026

❌ @robobun, your commit 12fae95 has 2 failures in Build #75659 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 34688

That installs a local version of the PR into your bun-34688 executable, so you can run:

bun-34688 --bun

@github-actions

Copy link
Copy Markdown
Contributor

Found 5 issues this PR may fix:

  1. Circular dependencies caused an abnormal behavior when creating node_modules. #25631 - file: dependency cycle between module_a and module_a_sub causes infinite node_modules nesting
  2. file:.. preview in subfolder cause import loop #21191 - file:../ dependency from subfolder to parent creates self-referencing cycle with ENAMETOOLONG
  3. bun i never exits, spikes cpu and memory usage on local file dependency with a workspace path dependency #25202 - file: dependency with workspace:. self-reference causes 100% CPU and unbounded memory growth
  4. bun install on projects with file: dependencies is very slow and somehow has more dependencies #13223 - file: dependency to local repo results in 5x more packages and ~10x slower installs due to redundant subtree traversal
  5. file protocol in package.json dependency #23453 - file:../ from sample app inside parent package causes 100% CPU from folder dependency cycle

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #25631
Fixes #21191
Fixes #25202
Fixes #13223
Fixes #23453

🤖 Generated with Claude Code

@robobun

robobun commented Jul 19, 2026

Copy link
Copy Markdown
Collaborator Author

Checked the suggested issues. #25202 is the same hoist cycle and is fixed here (test added). #25631, #21191, #23453 and #13223 reproduce identically with and without this change; they are the folder package being materialised by copying its source directory, which contains the dependent and so copies its own node_modules back in. That is a separate mechanism from the hoist tree builder and is left for another PR.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/cli/install/migration/migrate.test.ts`:
- Line 546: Make both fixtures in test/cli/install/migration/migrate.test.ts at
lines 546-546 and 581-581 disposable so each test cleans up its temporary
directory. Replace tempDirWithFiles usage with disposable tempDir setup and
using where supported, or explicitly remove each directory in a finally block;
update both migration and workspace self-reference fixtures while preserving
their existing file contents and test behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 755f95b2-3951-4294-b775-9e7f83d8516d

📥 Commits

Reviewing files that changed from the base of the PR and between 3f65f08 and af56fb2.

📒 Files selected for processing (2)
  • src/install/lockfile/Tree.rs
  • test/cli/install/migration/migrate.test.ts

@claude claude Bot left a comment

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.

I didn't find any issues, but this changes dependency placement in the hoist tree builder — a core bun install code path — so it's worth a human look before merging.

What was reviewed:

  • Ancestor walk terminates: root tree is seeded from Tree::default() with parent == INVALID_ID, and every subsequent tree's parent id is strictly smaller, so the loop always reaches the break.
  • Acyclic folder deps are unaffected: the guard compares against enclosing-subtree subject packages only, and pkg_id is guaranteed valid/non-root here (the invalid_package_id branch is handled earlier; root is tag Root, not Folder).
  • builder.resolutions[tree.dependency_id] is always in bounds — subtrees are only enqueued for deps with a valid resolved package id, and resolutions only ever transition invalid→valid.
  • Popped empty subtrees can't appear in the ancestor chain (a tree only becomes a parent after a dep is placed in it).
Extended reasoning...

Overview

The PR adds a ~18-line ancestor-chain check in Tree::process_subtree (src/install/lockfile/Tree.rs) that skips placing a folder-tagged dependency when its resolved package id already appears as the subject of an enclosing subtree. This breaks infinite re-enqueue loops for file: folder packages whose dependency graph reaches back to themselves (directly, via an npm: alias, via a mutual pair, or via a workspace:. self-reference). Four regression tests are added to test/cli/install/migration/migrate.test.ts covering each variant, each with a 30 s subprocess timeout so the pre-fix hang surfaces as an assertion failure.

Security risks

None identified. This is a termination fix inside the lockfile hoist builder; it reads only in-memory tree/resolution buffers and does not touch any network, filesystem, credential, or user-input parsing path. All indexed accesses were traced to be within bounds.

Level of scrutiny

High. process_subtree runs on every bun install and determines what ends up in node_modules. A subtle regression — e.g., a legitimate acyclic folder dep silently skipped — would have a very large blast radius. The change is small and its correctness argument (only the subtree ancestor chain is consulted, so a folder dep placed at the root by a sibling still gets its own local placement) is sound, but the interacting invariants around tree ids, popping empty subtrees, BFS ordering, and hoist_root_id are dense enough that a maintainer familiar with this code should confirm nothing else relies on folder deps always being placed unconditionally.

Other factors

  • No CODEOWNERS coverage for src/install/.
  • CodeRabbit's only comment (temp-dir cleanup) was withdrawn as inconsistent with file conventions; nothing else outstanding on the thread.
  • PR description demonstrates the tests fail without the fix and pass with it, and that bun-install.test.ts folder tests and the migrated bun.lock --frozen-lockfile round-trip are unchanged.
  • I confirmed via Lockfile::hoist that the root tree is appended with parent: INVALID_ID and dependency_id: ROOT_DEP_ID, so the new loop's ROOT_DEP_ID => 0 arm and parent == INVALID_ID break are both reached.

The previous commit skipped the dep entirely when its folder package was
already an enclosing subtree. For an aliased self-reference (dep name
different from the package name, as in #25202's foo: workspace:.) that
dropped the only bun.lock entry under that name, so the parser could not
resolve it on reload.

Move the ancestor walk to guard write_item in the Placement arm instead:
the dep is still placed so bun.lock carries it, only the re-enqueue that
would loop is cut. The workspace:. test now asserts the --frozen-lockfile
round-trip.

@claude claude Bot left a comment

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.

I didn't find any issues, but this touches the hoist tree builder that every bun install runs through, so it's worth a human look at whether "place the dep, skip only the re-enqueue" produces the intended bun.lock shape for the aliased/mutual-cycle cases.

What was reviewed:

  • is_folder_cycle ancestor walk: terminates at parent == INVALID_ID, handles ROOT_DEP_ID → pkg 0 the same way process_subtree does, and only reads trees already in builder.list.
  • Gating: first line returns false for every non-Folder resolution, so bundled/npm placements and the ResolveReplace enqueue path (unreachable for folder deps) are unaffected.
  • Tests: cover self-cycle, npm: alias, mutual a↔b, and workspace:.; each bounds the spawn with a process timeout, asserts signalCode === null, and round-trips the resulting bun.lock through --frozen-lockfile.
Extended reasoning...

Overview

Adds a ~25-line is_folder_cycle helper in src/install/lockfile/Tree.rs and calls it at the single site in Tree::process_subtree where a placed dependency's subtree is re-enqueued. When a Tag::Folder package's id already appears as the subject of an enclosing subtree (walked via tree.parent up to INVALID_ID), the re-enqueue is skipped; the dep is still pushed into the tree's dependency list so it reaches bun.lock. Four new tests in migrate.test.ts cover the self-referential, npm:-aliased, mutual-cycle, and workspace:. shapes, each with a 30 s process timeout so a regression fails the assertion instead of hanging the suite.

Security risks

None. No untrusted input parsing is added; the helper reads only in-memory lockfile builder state (package ids, resolution tags, tree parent links). No filesystem, network, or path-construction changes.

Level of scrutiny

High. process_subtree runs for every dependency during every bun install / bun pm migrate, and the hoist tree determines what ends up in node_modules and bun.lock. The change is defensively gated (early-return false unless the resolution tag is Folder, and only when the same package id is already an ancestor — which is precisely the infinite-re-enqueue condition), so the blast radius is narrow by construction. But the hoist algorithm is subtle enough (dedup normally lives in hoist_dependency, which folder deps bypass) that a maintainer who owns src/install/ should confirm the resulting bun.lock shape is what they want for the aliased and mutual cases, and that consulting only the ancestor chain (not sibling placements) is the intended scope.

Other factors

I verified the ancestor walk against the root-tree setup in Lockfile::hoist (Tree::default().process_subtree(ROOT_DEP_ID, INVALID_ID, ...)): the appended root has parent == INVALID_ID and dependency_id == ROOT_DEP_ID, both handled explicitly. Every tree in builder.list has its dependency_id set at append time, so the builder.resolutions[id] index is always in bounds. The ResolveReplace arm also enqueues but is only reachable via hoist_dependency, which Folder resolutions short-circuit past — so the single guard site is sufficient. The one CodeRabbit comment (temp-dir disposal) was withdrawn after the author pointed out the file's existing convention. No prior human review; CI build #75659 is in progress.

@robobun

robobun commented Jul 19, 2026

Copy link
Copy Markdown
Collaborator Author

CI at 12fae95: 283/286 jobs passed. The three red lanes are two pre-existing node:net memory-threshold tests (node-net.test.ts on debian aarch64, test-net-connect-memleak.js on alpine x64 and x64-baseline), both tagged pre-existing by the build annotation and both already being tracked separately. Everything in test/cli/install/ and the four new cycle tests pass on every lane. Ready for review.

@robobun

robobun commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

Verified another in-the-wild shape of this hang against this branch: the lockfile npm >= 7 writes when the file: targets live in a subfolder and reach each other through * ranges.

{ "name":"sandbox","version":"1.0.0","lockfileVersion":3,"requires":true,
  "packages":{
    "":{"name":"sandbox","version":"1.0.0","dependencies":{"alpha":"file:./vendor/alpha","beta":"file:./vendor/beta"}},
    "node_modules/alpha":{"resolved":"vendor/alpha","link":true},
    "node_modules/beta":{"resolved":"vendor/beta","link":true},
    "vendor/alpha":{"name":"alpha","version":"1.0.0","dependencies":{"beta":"*"}},
    "vendor/beta":{"name":"beta","version":"1.0.0","dependencies":{"alpha":"*"}}}}

On current canary (45ee955), bun install with this lockfile never finishes: memory grows at roughly 450 MB/s inside Lockfile::hoist (the Placement arm of Tree::process_subtree re-enqueues the alpha/beta cycle forever) until the machine runs out. With a memory cap it degrades into OutOfMemory: failed to migrate lockfile followed by the ignore-lockfile fallback, so the lockfile is silently dropped.

On this branch (debug + ASAN build at 12fae95): migration completes in ~1 ms, the install finishes with the expected layout (alpha, beta, one nested copy each), the written bun.lock round-trips through bun install --frozen-lockfile, and --backend=symlink --dry-run also completes. The flags make no difference, as expected.

@robobun

robobun commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Checked three more entry points to the same loop against this branch, including one that never touches a migrator.

  1. yarn.lock v1: two file: packages whose lock entries depend on each other ("alpha@file:./vendor/alpha", "alpha@file:../alpha" with beta "file:../beta", and the mirror entry for beta). On canary 45ee955 this loops at the same hoist site (3.6 GB RSS after 6 s). On this branch: migrates in ~150 ms, installs, and the written bun.lock round-trips through bun install --frozen-lockfile.

  2. pnpm-lock.yaml lockfileVersion 9.0 (generated by pnpm 9): two resolution: {directory: ..., type: directory} packages whose snapshots depend on each other. Loops on canary. On this branch: migrates in ~40 ms and round-trips.

  3. No foreign lockfile at all: root {"workspaces":["packages/*"],"dependencies":{"alpha":"file:./vendor/alpha"}}, where packages/alpha is named alpha and depends on alpha: "file:../../vendor/alpha", and vendor/alpha depends on alpha: "workspace:*". This reaches the loop through the normal resolve/hoist path (canary commits 3 GB within 2.5 s and aborts with "Bun has run out of memory" under a memory cap). On this branch it terminates and installs, exit 0.

Also verified on this branch via package-lock.json: a three-package cycle (alpha -> beta -> gamma -> alpha) and the link: protocol variant of the two-package cycle. Both loop on canary, both complete here.

One note on case 3: termination exposes a separate pre-existing bug. The workspace/file: name collision places both same-named packages in the root tree, so the saved bun.lock contains a duplicate "alpha" key in packages, later installs warn Duplicate key "alpha" in object literal and re-resolve, and --frozen-lockfile fails. That reproduces on current canary with no cycle involved (a workspace named alpha plus a file: dependency named alpha, no dependencies between them), so it is independent of this change and only becomes visible here because the install now finishes.

Net: every entry point to the hang found so far terminates with this fix.

@robobun

robobun commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator Author

Closing in favor of #38333, which cuts the folder dependency cycle in Tree.rs and lifts this PR's migrate.test.ts cases (the three package-lock.json shapes and the #25202 install, the latter adjusted to the error that shape now produces there).

@robobun robobun closed this Aug 14, 2026
Jarred-Sumner added a commit that referenced this pull request Aug 14, 2026
…ilter/--catalog, nested overrides, transitive update, and workspace fixes (#38333)

Brings Bun's package manager to parity with pnpm for monorepo workflows,
and fixes the bugs found while checking every command against pnpm's
implementation, pnpm's test suites, pnpm's open issue tracker, pnpm's
docs, npm's arborist fixtures, and — for `bun update` — running real
pnpm and Bun side by side on the same projects.

### What does this PR do?

#### New commands

- **`bun dedupe [--check]`** — collapses duplicate versions in
`bun.lock` onto the smallest set that still satisfies every dependent's
range, using only versions already in the lockfile, then installs. Never
downgrades a direct dependency unless that is the only way to drop a
version; keeps patched versions (and anything needed to reach them, and
says so); refuses to run on a lockfile that is behind `package.json`.
`--check` exits 1 without writing.
- **`bun prune [--production | --omit=…] [--dry-run] [--filter <ws>]`**
— removes everything in `node_modules` that the lockfile does not put
there; `--production` leaves exactly what `bun install --production`
would. Hoisted and isolated layouts, Windows junctions and shims,
workspace links, bundled deps; refuses when `package.json` and
`bun.lock` disagree or when `node_modules` was laid out by a different
linker; understands turbo-pruned checkouts.
- **`bun pm licenses [--json] [--prod|--dev] [--long] [--filter <ws>]`**
— installed packages grouped by license, with a `(dev)` marker and
`paths`/`license`/`description` in `--json`.
- **`bun audit fix [--latest] [--dry-run] [--json]`** — moves each
vulnerable package to the lowest safe version its dependents accept, per
installed instance; rewrites exact pins when that is the only way;
`--latest` also rewrites your own declared ranges (root, workspace,
catalog) so a semver-major fix can be taken, and every blocked or
unfixable item is followed by the command that resolves it (`bun audit
fix --latest`, `bun audit --ignore GHSA-…`); re-audits the tree it
actually installed and reports/exits from that second response (npm's
`_submitQuickAudit`), so an advisory that starts at the version it moved
to is not missed; works across registries; security fixes bypass
`minimumReleaseAge` with an annotation. `bun audit --json` honors
`--audit-level`/`--ignore` for its exit code; `--omit` is honored by
`audit` and `licenses`.

#### `bun update` semantics (pnpm's model)

- A bare `bun update` re-resolves **transitive** packages too — every
edge moves to the newest version its own range (or dist-tag) allows, per
dependent, so `bun.lock` no longer stays stale after an update;
overrides/catalogs changed since the last install are honored. From a
workspace member or `--filter`, only what the selected workspaces reach
is re-resolved; from the root, everything.
- `bun update <name>` reaches any depth, matches `npm:` aliases by real
name, updates in place, never adds to `package.json`, and errors on a
name nothing selected depends on. `-r`/`--filter` fan a named update out
across workspaces. `--latest` never downgrades a locked version that is
ahead of the tag, and `update <name> --latest` also refreshes that
package's own dependencies.
- Plain updates keep dist-tag literals and non-caret ranges (`*`, `1.x`,
`^1 || ^2`) exactly as written and only move the lockfile; `--latest`
rewrites them to the resolved version as before. `bun update -i` applies
only what you selected. New: positional patterns (`bun update
'@types/*'`), `--dev`/`--prod`/`--no-optional`, `-L`, `bun up`.
- `package.json` is written after resolution and `bun.lock`'s declared
ranges, overrides and catalogs are re-derived from the final
`package.json`, replacing the per-command literal rewriting; a no-op
update leaves the file byte-identical.

#### Overrides

- **Nested overrides** (#6608): npm's nested objects, yarn's `a/b` paths
and pnpm's `a>b` selectors, applied to the direct parent→child edge;
**version-scoped targets** (`"lodash@<4.17.21": "4.17.21"`, the shape
`pnpm audit --fix` writes), matched against the dependent's declared
range as pnpm does. Rules persist inside the `overrides` section and the
file is stamped `lockfileVersion: 3` **only when such rules exist** —
existing lockfiles are byte-identical. Flat overrides additionally fix
`$ref` to workspace-member deps, catalog-valued rules going stale, and
warn on pnpm's `-` / `pkg@` forms.

#### Workspaces and filters

- `bun add|remove|update … --filter <ws>` (also `-F`, also `bun install
<pkg> --filter`) edits the selected workspaces' `package.json` files and
**links only those workspaces**, like `bun install --filter`. Filters
gain pnpm's relation selectors (`foo...`, `...foo`, `foo^...`,
`...^foo`) and `{dir}` subtrees, for the install family **and** `bun run
--filter`; `--filter` may precede the subcommand; every command warns
about patterns that match nothing; `add`/`remove` no longer select the
root implicitly.
- `bun add <pkg> --catalog[=name]` reuses an existing catalog entry,
keeps a range an explicit version fits, catalogs the range a package
already declares, decides per target, and refuses workspace names and
local paths; a plain `bun add` uses a default-catalog entry when one
exists. A package defined in both `catalog` and `catalogs.default` is an
error. `catalog:` peers of registry packages bind to the importer's copy
instead of the root catalog.
- `--frozen-lockfile` / `bun ci` on turbo-pruned monorepos: pruned-away
workspaces are tolerated, a survivor depending on a pruned workspace is
an error, catalog subsets are accepted, and an overrides/catalogs change
is a frozen failure.

#### One output vocabulary

Every command here prints the install family's shapes: header, glyph
rows (`+`/`-`/`↑`, dedupe's `↳ name old → new`), exactly one noun-first
summary line with counts and a duration (`2 duplicate versions removed,
3 packages installed (checked 5 packages) [12ms]`, `N packages removed
(checked C) [t]`), no-ops that say what was checked, remedies printed as
copy-pasteable command lines, warnings as `warn:`, `--silent` printing
nothing, and errors with their remedy together on stderr. Transitive and
named updates render as the summary's `↑` rows (once per package;
`--dry-run` prints the same rows plus `N packages would be updated`);
dedupe reports after the install it triggers, so lifecycle-script output
never splits it. A lockfile whose bytes did not change is no longer
rewritten (`Saved lockfile` only prints on a real write;
`--lockfile-only` no-ops print `Done! Checked N packages (no changes)`).
This came out of running every command against fixtures and comparing
with `install`/`add`/`remove` (95 findings, all fixed).

#### Config precedence

A project's `bunfig.toml` now beats any `.npmrc` (project or user-level)
for the same key (npmrc files → bunfig's set fields → CLI); npmrc-only
settings such as `//host/:_authToken` still attach to bunfig-declared
registries, matched by host and path regardless of how either file
spells the trailing slash.

#### Lockfile migration

- `package-lock.json`: rebuilt around a reachability walk that derives
each resolution from the entry itself. Fixes `git+https://github.com/…`
resolutions being written unparseably (the next install threw the
lockfile away), root `bundleDependencies` migrating to an **empty**
lockfile, lockfileVersion 1 (and npm's upcoming 4) making `bun install`
exit 1 instead of resolving fresh, dependency-level bundles,
`dependencies`+`optionalDependencies` double edges, unreferenced entries
aborting the migration, duplicate packages for identical `name@version`
at nested paths, lost `optionalPeers`, lost integrity when a bundled
copy was seen first, and `overrides` not being carried over. All 57 of
arborist's v2/v3 fixture projects are vendored and migrated under
snapshot.
- `pnpm-lock.yaml` v9: bare-hash `patchedDependencies`, snapshot
aliases, `catalog:default`, recorded tarball URLs, git `path:`,
multi-document files, `runtime:` entries, named registries,
peer-suffixed keys chosen per importer, injected workspaces,
manifest-only importer deps.

#### Isolated linker

- An existing store entry whose dependencies re-resolved (override,
dedupe, update) now has its links refreshed on the next install
(measured cost below). `bun prune` builds the same store the installer
builds, so stale `name@version+<peerhash>` variants left by peer bumps
are removed and a kept package's real entry never is (whether it was
installed with full or `--production` features); on the hoisted linker,
dedupe / audit fix / update delete the nested copies whose rows they
collapsed instead of leaving the old copy loadable.
- Blocked entries resume through per-entry intrusive waiter lists
instead of a scan of every store entry after each completion (robobun's
#25983/#28425 attempted this). Measured on the reporter's repro from
#25799 (2,259 store entries) and a synthetic 6,425-entry monorepo, PR
build vs merge-base build: main-thread CPU in the link phase drops 0.85
→ 0.33 s and 5.5 → 0.85 s (the removed work grows quadratically); wall
time is unchanged with spare cores and 16% / 26% faster pinned to one
CPU, the CI/Docker shape in those reports. (The minute-long installs
originally reported were peer resolution, fixed before this PR's base.)
- Two pre-existing leaks surfaced by the new LSan-enabled tests are
fixed: the header buffer of every authenticated registry request, and
the per-entry lifecycle-script lists.

#### Other bug fixes

`bun add x@npm:pkg` writes a range; `bun add --trust a b` no longer
drops `b` when `a` was already trusted; `bun add x --dev` no longer
rewrote every group in `bun.lock`; `catalog:` peer hoisting;
`dependency::Version::eql` treated all `catalog:` specifiers as equal; a
`file:` package whose dependencies reach itself (its own name, an `npm:`
alias under its own name, two link targets depending on each other — the
shapes a `package-lock.json` migration produces, and #25202's
`workspace:.` self-reference) hung `bun install` forever in the hoisting
tree — the migration shapes now install, and #25202's literal shape now
terminates with `Workspace dependency "foo" not found` rather than
installing as npm does; a peer of a `file:` package that was only placed
nested was also written to `optionalPeers` in a migrated bun.lock, so
the next `--frozen-lockfile` failed and a plain install rewrote the
lockfile; `catalog:` literals in `bun update`; alias output in the
install summary; help/completions for everything above.

#### Behavior changes to note in the release notes

- `bun update` moves transitive packages; `bun update <name>` no longer
adds an undeclared package (exit 1); `--production`/`--prod` on update
means "only update `dependencies` and `optionalDependencies`" (a group
filter like `--dev`, not the install flag) and `-r`+names with no match
is an error; `-i` updates only the selection.
- Project `bunfig.toml` overrides any `.npmrc`.
- `bun install <pkg> --filter x` edits `x` (not the root); `bun add y
--filter x` no longer installs a package named `x`; `add`/`remove
--filter '*'` no longer includes the root.
- A plain `bun add x` in a workspace whose default catalog lists `x`
writes `catalog:`; `audit fix` may rewrite exact pins;
`--frozen-lockfile --lockfile-only` writes nothing; overrides/catalog
changes fail frozen installs.
- One-time lockfile churn after upgrading for projects with `catalog:`
peers or dead `pkg@range` override rows; lockfiles that use
nested/scoped overrides are v3 and unreadable by older Bun (only when
opted in). Turborepo, Nx and Dependabot have been checked; the needed
upstream changes are open (nrwl/nx#36666 covers v2 and v3;
vercel/turborepo#13740 accepts v3 and preserves the object rows through
prune — turborepo main today parses v2 and rejects v3; dependabot needs
nothing). Note v2 itself only exists on the 1.4 line.
- `bun audit --json` keeps npm's contract: `--audit-level`/`--ignore`
decide the exit code, the JSON document is the full registry report
(closes #31013 as won't-change). Automatic removal of stale
`node_modules` entries on plain `bun install` (#32974) is separate from
this PR: `bun prune` is the manual form, and dedupe / audit fix / update
now clean up the nested copies they collapse on the hoisted linker;
#32974 should reuse prune's planner, and #29512 (sbom) is sequenced
after this so it can build on `reachable.rs` instead of carrying its own
walk.
- Deliberately kept where we differ from pnpm: root `bun update` covers
the whole workspace; dependents whose ranges allow follow a moved
version (one copy, not two); `--latest` works on transitive names;
`--no-save` touches neither file; prune deletion failures exit 1; audit
requests stay per-registry.

#### Performance

Measured on a 1,113-package Next/Prisma/MUI app (PR build vs a PR build
of the merge base, interleaved, plus canary and 1.3.14): every hoisted
cell is within noise except no-op install, +0.8 ms (+2%, identical
syscalls); isolated no-op is +1.9 ms (+3.9%) — the deliberate cost of
re-checking existing entries' links every install rather than persisting
a stamp file. Everything added is otherwise off the plain-install path
(gated on the feature being used or on a diff), and id-indexed sets are
bitsets.

### How did you verify your code works?

~1,100 new or ported test cases across the install suites (designed
behavior, cases ported from pnpm's suites, pinning tests for pnpm bugs
this implementation is immune to, arborist's fixtures, and the CI review
findings), all `toStrictEqual`; the whole `test/cli/install` directory
passes locally and the existing suites are unchanged except where a
pre-existing expectation was deliberately changed (each listed above).
`bun update` was additionally verified with a rerunnable differential
harness that runs pnpm 11 and this branch on 26 scenario families
against one registry and diffs the resulting resolutions edge by edge —
after this PR only the deliberate differences above remain. Ecosystem:
Turborepo, Nx and Dependabot were checked against the new lockfile
output.

Co-authored work absorbed with credit: @kjanat's #38190 (alias handling,
co-author on the commit), @charpeni's #31143 and @crystalin's #34407
(both superseded), and the tests of the earlier `bun update` PRs (#31752
by @zlotnika, #33127, #36381, #36729, #38224). robobun's #34688
(folder-dependency cycles; its tests are lifted, co-author on the
commit) and #37289 (migrated optionalPeers; its test is lifted,
co-author on the commit) were fixed independently here and are closed by
this PR. #28422's quadratic scan is fixed here as well (already closed).

Related but not closed — `bun prune` gives these a manual fix while the
automatic-cleanup asks stay open: #8662, #26305, #29793, #21216, #16176.
Also related: #10930, #26970, #26751.

Fixes #1343
Fixes #3605
Fixes #14719
Fixes #24122
Fixes #18612
Fixes #20238
Fixes #25826
Fixes #23615
Fixes #26973
Fixes #20593
Closes #31013
Fixes #28959
Fixes #28402
Fixes #27897
Fixes #26675
Fixes #10949
Fixes #18504
Fixes #13388
Fixes #24523
Fixes #6608
Fixes #19059
Fixes #16569
Fixes #8262
Fixes #11901
Fixes #13469
Fixes #25202
Closes #29664
Closes #31143
Closes #34407
Closes #34688
Closes #37289
Closes #38190

---------

Co-authored-by: Kaj Kowalski <info@kajkowalski.nl>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: robobun <117481402+robobun@users.noreply.github.com>
@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

Thanks for this PR, @robobun — closing it in favor of #38333, which carries the fix and these tests.

A file: package whose graph reaches back to itself (npm's link: true shape, the npm: alias variant, two mutually dependent link targets) really did re-enqueue its own subtree until memory ran out.

What carried over:

  • The folderLockfile helper and all four cases, now in test/cli/install/migration/migrate.test.ts, asserting the exact bun.lock entries.
  • Self-dependent pkg migrates to a lockfile whose only entry is pkg; the mutual case ends at a, a/b, b, b/a.
  • bun install on each package-lock.json finishes in milliseconds and round-trips through --frozen-lockfile.

Differences from this PR:

Credited in #38333. It'll be in the next canary (bun upgrade --canary) and in Bun v1.4 — if a shape of this cycle still misbehaves, comment here or on #38333.

(This comment was written by Claude, on behalf of the Bun team.)

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bun i never exits, spikes cpu and memory usage on local file dependency with a workspace path dependency

2 participants