Repository navigation
test(security-scanner-matrix): don't depend on the setup install's manifest cache writes having landed - #37203
Conversation
Fetched npm manifests are written to the manifest disk cache by a thread-pool task that nothing waited for, so whether a manifest was cached when `bun install` exited depended on thread scheduling. On Linux under CPU load ~1.5% of installs were missing a manifest cache file afterwards, and the next install re-fetched it from the registry. Count those writes in `pending_manifest_saves` and have `PackageManager::sleep_until` — the wait every install/outdated/update/ auto-install flow already goes through — not return until they have landed; the runtime's async auto-install poll does the same.
|
@robobun adopt |
|
Update: the install-side wait was reverted on this branch; the manifest cache write stays fire-and-forget by design (a missing entry just means a refetch). The flake is now fixed in the matrix runner instead: the manifest cache is disabled for both installs so the requested-manifest set is deterministic, with snapshots regenerated. A/B data for the underlying write race is in the comments above. CI is running on the new head. |
WalkthroughChangesThe package manager tracks asynchronous manifest-cache saves. Command completion and module polling wait until pending saves finish. A regression test verifies successful installs and completed cache writes. Manifest cache synchronization
Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it changes the exit semantics of every install-flow wait (sleep_until) with new cross-thread atomic/wake coordination and ships without a dedicated test (relying on the scanner-matrix flake as the regression signal, with the release-binary before/after stress count still pending), a human look would still be worthwhile.
What was reviewed:
- Increment happens before
schedule(batch)and the worker-side decrement+wake covers both the ok and error branches ofSerializer::save— no path leaks the count. - The worker-thread
fetch_sub/wake_rawpattern matches the existing one inPackageInstall.rs:700-708;package_manager::get()is an Acquire atomic load, safe off-main-thread. - The second
tick_rawpasses*mut PackageManagerascontext; MiniEventLoop tasks that could interpret it aren't enqueued by the save path (onlywakeup()), and the Js arm ignorescontext. - Runtime auto-install: the save's
wake_rawreachesQueue::on_wake_handler→on_poll, so the addedpoll_modulesguard can't strand a module.
Extended reasoning...
Overview
Adds an AtomicU32 pending_manifest_saves on PackageManager, incremented before Serializer::save_async schedules the thread-pool write and decremented (with wake_raw) in the worker callback. PackageManager::sleep_until gains a second tick_raw loop after the caller's condition is satisfied, blocking until the counter is zero. AsyncModule::Queue::poll_modules adds the counter to its early-return guard. Both init and init_with_runtime_once initialize the field.
Security risks
None. This is internal lifecycle bookkeeping around an on-disk manifest cache; no new inputs are parsed and no trust boundary is crossed.
Level of scrutiny
High. sleep_until is the single blocking wait every install / add / update / outdated / migrate / auto-install flow goes through, and the change adds a second unconditional wait loop to it. The new code is unsafe (raw-pointer field projection from a worker thread, a second tick_raw call with a different context pointer than the first) and coordinates across threads with atomics. A hang here would break bun install for everyone.
Other factors
- The counter pattern is a close copy of the proven
pending_tasksdecrement/wake inPackageInstall.rs, and the ordering (Relaxed add on the scheduling thread beforeschedule, Release sub + wake on the worker, Acquire load in the waiter) is sound. - No new test is added; the PR body argues the race has no deterministic hook and names the existing scanner-matrix test as the signal. The repo's review rules normally require a test in the same PR, so a maintainer should sign off on that exception.
- The description says the release-binary before/after reproduction count will be posted once CI produces a binary — that verification is still outstanding.
- I checked that the added
poll_modulesguard can't deadlock the runtime auto-install path: the save'swake_rawinvokes the registeredon_wakehandler (Queue::on_wake_handler), which posts aPollPendingModulesTask, sopoll_modulesis re-entered after the counter drops.
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it changes sleep_until — the blocking wait every install/add/update path goes through — and adds cross-thread wake/counter coordination with no new automated test, a human look would still be worthwhile.
What was reviewed:
- Counter lifecycle: increment happens before
schedule, decrement runs on both save success and error, andwake_rawis the same thread-safe wake worker threads already call. - The second
tick_rawpasses*mut PackageManager(notErased<C>) as the mini-loopcontext; verified the only install-path mini task (ResultTaskMini) ignores itsextraarg, so this is benign. - Both
initandinit_with_runtime_onceinitialize the new field;poll_modules's early return is re-woken viawake_raw→on_wake_handler.
Extended reasoning...
Overview
Adds an AtomicU32 counter (pending_manifest_saves) on PackageManager, incremented before Serializer::save_async schedules a manifest cache write to the thread pool and decremented (with a wake_raw) from the worker after the write finishes. PackageManager::sleep_until gains a second AnyEventLoop::tick_raw call that keeps ticking after the caller's condition is satisfied until the counter is zero, and AsyncModule::Queue::poll_modules returns early while it is nonzero. Both PM constructors initialize the field.
Security risks
None identified. This is process-local scheduling of a disk-cache write; no untrusted input, no auth/crypto/network surface changes.
Level of scrutiny
High. sleep_until is the single blocking wait that every install-family command (install, add, update, outdated, security-scanner wait, migrate, populate-manifest-cache, isolated/hoisted extraction) funnels through, and the new code path is unsafe raw-pointer projection driven from a worker thread. A mistake here hangs or corrupts every install. The change also intentionally ships without a new automated test (the PR argues the existing scanner-matrix flake is the regression signal, and the release-binary before/after stress count is still pending per the robobun comment). Under the repo's review rules that is a maintainer judgment call, not an auto-approve.
Other factors
I traced a few things that looked risky and found them fine: the second tick_raw passes this.cast::<c_void>() as context, which differs in type from the first call's Erased<C>; MiniEventLoop::tick_once forwards that as extra to any drained AnyTaskWithExtraContext, but the only install-path producer (waiter_thread_posix::ResultTaskMini) ignores extra, and no src/install/ code enqueues context-using mini tasks. Ordering is Release on the worker decrement / Acquire on the saves_landed load. The runtime path's poll_modules early return is re-triggered because the save worker's wake_raw runs on_wake_handler, which posts the Queue poll task. The remaining question a maintainer is better placed to judge is whether draining manifest saves at every sleep_until boundary (not just before process exit) is the intended shape, and whether the no-new-test justification is acceptable.
|
Follow-up on the Linux A/B promised above: with the release artifact from this branch ( |
|
Ran the same A/B on a loaded 16-vCPU Linux x64 box where the base rate did fire. Setup: the repo verdaccio fixtures as the local registry, a tree that resolves 3 manifests (one-dep, no-deps, a-dep), fresh cache dir, lockfile and node_modules each iteration, then counting .npm files in the cache dir after each successful exit. Load was 2-4x nproc busy loops.
Zero install failures in all runs. Losses came in bursts (5 hits inside one 25-iteration span) and some runs were missing 2 or all 3 of the manifest files, which points at scheduling pressure on the pool worker rather than anything file-specific. The base rate is very sensitive to scheduler fairness: even at load average 50 a single install still completed in about 26 ms wall on this box, so most iterations never open the window. That is consistent with your 0/500 and 0/400. |
A manifest whose string data is large and unique makes the cache write take longer than the rest of the install, so a bun that exits without waiting for pending manifest saves reliably loses the file. Verified to fail on unfixed debug and release builds and pass on fixed ones.
There was a problem hiding this comment.
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/bun-install-manifest-cache.test.ts`:
- Around line 74-84: Update the Bun.spawn configuration in the install test to
avoid leaving proc.stdout undrained: either set stdout to "ignore" or consume
proc.stdout alongside stderr and exitCode in the existing Promise.all. Preserve
the current stderr capture and exit-status assertions.
🪄 Autofix
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: a5f91811-0009-4e22-9436-0dfde35c982d
📒 Files selected for processing (1)
test/cli/install/bun-install-manifest-cache.test.ts
|
Updated 7:44 PM PT - Aug 8th, 2026
❌ @dylan-conway, your commit c4d0bad has 1 failures in
🧪 To try this PR locally: bunx bun-pr 37203That installs a local version of the PR into your bun-37203 --bun |
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. The one nit I flagged earlier (undrained stdout pipe) was already addressed in 7c17f71. Because the fix adds a second tick_raw phase to PackageManager::sleep_until — the single blocking wait every install-family command routes through — and introduces cross-thread atomic bookkeeping with new unsafe blocks, a human look is still worthwhile.
What was reviewed:
- Counter lifecycle:
fetch_add(Relaxed)beforeschedule,fetch_sub(Release)+wake_rawin the worker,load(Acquire)insaves_landed— ordering is sound and increment cannot be observed after decrement. - Both
initpaths (initandinit_with_runtime_once) initialize the new field; bothsave_asynccall sites are on the main thread inside the caller's firsttick_raw, so the counter is nonzero before the second wait starts. - Second
tick_rawpassesthis(the*mut PackageManager) ascontextwhere the first passes&raw mut erased; verifiedMiniEventLoop::tick_onceonly forwardscontextto task callbacks andwake_raw'swakeup()does not enqueue a task, so no callback misinterprets it. - Regression test: hermetic (local
Bun.serve,tempDir, per-iterationBUN_INSTALL_CACHE_DIR), stdout ignored, stderr drained concurrently withproc.exited.
Extended reasoning...
Overview
The PR fixes a race where bun install could exit before the thread-pool task writing a fetched manifest to the disk cache had finished, making the next run's cache hit nondeterministic. It adds an AtomicU32 pending_manifest_saves counter on PackageManager, increments it in Serializer::save_async before scheduling, decrements + wakes in the worker after the write, and makes both PackageManager::sleep_until (via a second AnyEventLoop::tick_raw call) and AsyncModule::Queue::poll_modules wait for the counter to hit zero. A new regression test uses a ~40 MB unique-string manifest to make the cache write reliably outlast an install that doesn't wait.
Security risks
None identified. No user-controlled data reaches the new code paths; the change is internal synchronization between the install main thread and its own thread pool. The test's registry is a local Bun.serve({ port: 0 }) and cache dir is per-iteration under tempDir.
Level of scrutiny
High. sleep_until is the one blocking wait that install / add / update / outdated / update -i / migrate / security-scanner / auto-install all funnel through, and the diff appends a second unconditional tick_raw phase to it. That is a behavior change on the exit path of every install-family command. The worker-side decrement runs on a pool thread and reaches the PackageManager via crate::package_manager::get() (raw *mut) inside a new unsafe block, and saves_landed open-codes an atomic field projection through a *mut c_void cast — both are the kind of cross-thread unsafe that REVIEW.md flags for careful review even when the SAFETY comments look right.
Other factors
The PR is thoroughly argued: root-cause traced from the flaky snapshot to save_async's fire-and-forget, an A/B under load (20/2000 → 0/1200), and a deterministic regression test that the author verified fails on unfixed debug and release builds. CI is reported green on the new test across all lanes. The only prior review feedback (undrained stdout pipe) was addressed in 7c17f71. I checked that the second tick_raw's context argument (*mut PackageManager, differing from the first call's Erased<C>) is only forwarded to AnyTaskWithExtraContext::run and that the wake path doesn't enqueue such a task, so no callback receives a misinterpreted pointer — but that reasoning depends on what else can land in mini.tasks during the second wait, which someone who owns this loop should confirm. Given the change is small, well-tested, and clearly motivated, the remaining ask is a maintainer sanity-check on adding an unconditional post-wait to sleep_until rather than gating it more narrowly.
This reverts commit 7c17f71.
This reverts commit 6f9ed5c.
This reverts commit f72d688.
…nifest cache writes having landed The "with modules" matrix ran a setup `bun install`, then asserted the exact set of manifests the install under test requests. With the manifest cache on, that set depended on whether the setup install's asynchronous cache writes had reached disk before it exited - which `bun install` deliberately does not wait for (writes are atomic-rename; a missing entry just means a refetch). Turn the manifest cache off for both installs so the requested set is a property of the command, and regenerate the affected snapshots (no-lockfile "with modules" scenarios now list the manifests they fetch). No-Verification-Needed: test-only change
There was a problem hiding this comment.
LGTM — test-only flake fix that makes the matrix's requested-packages snapshots deterministic by disabling the manifest cache.
What was reviewed:
disableManifestis a real bunfig key (src/bunfig/bunfig.rs:1444) and is applied to both the setup and tested install's bunfig.- Spot-checked snapshot entries (0006/0016/0121/0486/0546) — the added package lists are consistent with the dependency shape for each scanner type and command; entries are sorted.
- Confirmed the sibling
without-node-modulessnapshot already lists these manifests (e.g. entry 0121), so no regen needed there. - Earlier runtime approach (
pending_manifest_saves) and its regression test were fully reverted; the diff is now the two test files only.
Extended reasoning...
Overview
This PR fixes a CI flake in bun-security-scanner-matrix-with-node-modules.test.ts. The final diff (after reverting an earlier runtime-level approach) touches two test files: the shared matrix runner adds disableManifest: true to the bunfig [install.cache] table for both the setup install and the install-under-test, and the "with modules" snapshot file is regenerated (~151 requested-packages entries). No production code is touched.
Security risks
None. Test-infrastructure only; no runtime, auth, or crypto paths.
Level of scrutiny
Low. The runner change is a one-key config addition with an explanatory comment, and the snapshot changes are mechanical output of running the full matrix. The main things worth checking were: (1) that disableManifest is a real key that src/bunfig/bunfig.rs reads, (2) that the same cache config is applied to both bunfig writes so the setup and tested installs agree, (3) that the snapshot deltas are internally consistent with the dependency shape per scenario, and (4) that the sibling "without modules" snapshot doesn't need a matching regen. All four checked out.
Other factors
The PR pivoted from an earlier approach that made bun install block on pending manifest-cache writes; the recent commits revert that and its regression test cleanly, so the CodeRabbit walkthrough and my own earlier inline comment (both about the now-deleted bun-install-manifest-cache.test.ts) are moot. The PR description slightly understates the snapshot scope — a handful of bun.lock exists: true entries where left-pad is explicitly named on the CLI also gained "left-pad" — but that's the expected consequence of disabling the manifest cache and matches what the sibling "without modules" snapshot already recorded, so it's a description nit rather than a correctness issue. The author ran all 720 + 688 cases locally against the new snapshots.
### Problem - `test/cli/install/bun-lock.test.ts` > "peer no published version satisfies" > "declared by a registry package" (from #38851) fails on main about every fourth build (build 104990). `expect(registry.requests).toEqual([])` at bun-lock.test.ts:1778 receives `["/peer-target"]`: the manifest cache has no usable entry for `peer-target`. It has two causes. #40073 covers the first, the `save_async` exit race. This PR fixes the second. - `Serializer::save` (src/install/npm.rs:1352) named the temporary file `<name hash>.npm-<milliseconds>` in the temporary directory every bun process shares. The four concurrent peer tests all save `peer-target`, and two saves in one millisecond opened one file. Windows, release build, four installs saving one package at once: 77 of 80 lost their entry. Linux uses `O_TMPFILE` today; #38916 starts using the name on Linux too, so this fix has to land first. ### Fix - `Serializer::save` names the file with `FileSystem::tmpname`, as `TarballStream` already does. Correct because the name no longer depends on anything two processes share. - Two tests in `bun-install-registry.test.ts`: four synchronized installs keep their own valid entries, and an install still caches its manifest when directories occupy the old temporary names. The second fails 3 of 3 on Windows without the fix and passes 5 of 5 with it. The test registry serves the tarball only after the cache entry exists, so neither test depends on the exit race. - Verified: `bun bd test test/cli/install/bun-install-registry.test.ts` (250 pass) on Linux, both new tests on Windows. ### Background - Manifest cache: each fetched manifest is serialized to `<cache dir>/<name hash>-<registry hash>.npm`. Within the response's `max-age`, a later install resolves from that file and makes no request. - `write_file` opens the temporary file with `O_CREAT | O_TRUNC`, writes, then renames it into the cache. Two processes on one name write one file. On macOS the second rename fails and the first cache holds the second's bytes, which `load_by_file` rejects. On Windows `rename_at_w` moves by handle, so the second rename moves the file out of the first cache again. - The exit race: `save_async` writes the entry from a thread pool task that `bun install` does not wait for, by design (#37203). The test change in #39190 works around it for the bun-lock test. The harness flag in #40073 removes it from every install test. <details><summary>Notes</summary> Probe (Windows, 16 vCPUs): one registry and one project per install, `dependencies: { "peer-target": "2.0.1" }`, each registry holds its manifest response until all four have been asked, then all respond at once. After exit, the `.npm` entry is read and checked for the install's own registry origin. | binary | temp dir | rounds | ok | missing | wrong registry | | --- | --- | --- | --- | --- | --- | | 1.4.1-canary.1 (release, unfixed) | shared `%TEMP%` | 20 | 3 | 60 | 17 | | 1.4.1-canary.1 (release, unfixed) | shared, responses not synchronized | 40 | 135 | 17 | 8 | | 1.4.1-canary.1 (release, unfixed) | one per install | 40 | 160 | 0 | 0 | | debug, unfixed | shared | 20 | 74 | 3 | 3 | | debug, this branch | shared | 20 | 80 | 0 | 0 | The unfixed debug build loses far fewer entries than the release build because its slower parse spreads the four saves over several milliseconds. That is also why the concurrent test detects the bug almost always on release lanes and only sometimes on a debug build. The directory test fails deterministically on a debug build (3 of 3 and, in an earlier shape of the test, 5 of 5 on Windows). Windows mechanism in detail: `open_file_at_windows` maps `O_CREAT | O_TRUNC` to `FILE_OVERWRITE_IF` with `FILE_SHARE_READ | WRITE | DELETE`, so every process opens and truncates the same file. `rename_at_w` (src/sys/windows/mod.rs:1933) opens the source by path and then moves it by handle. When two processes have opened the path before either moves it, both moves succeed: the second one relocates the file out of the first process's cache. That process sees a successful save and has no entry, which is the "no entry, no error" case in the probe. `FileSystem::tmpname` (src/resolver/lib.rs:198) formats `.<random ^ nanoseconds>-<counter>.<ext>`. The temporary directory probe in `PackageManagerDirectories.rs` and `TarballStream::open_destination` use it the same way. Test registry and the exit race: both new tests read the cache after the install exits. To keep them independent of the `save_async` exit race, the registry answers the tarball request only once a `.npm` entry exists in the project's cache (polling with a 5 second deadline, after which it answers anyway so a lost write ends as a failed assertion instead of a hang). The tarball is requested after the manifest is parsed, so the install cannot finish before its entry is on disk. Sequencing: #38916 changes the Linux `O_TMPFILE` path to link the file into the temporary directory under `tmp_path` before renaming it over an existing entry, which makes the name load-bearing on Linux. This PR should land before it. #39190 (the bun-lock warm-up loop) and #40073 (harness flag) handle the exit race; an earlier shape of this PR carried #39190's commit, which the self-review flagged as a duplicate of an open PR, so it was dropped. Gate: the fixed code path is not reachable on Linux today (`O_TMPFILE`), so the new tests pass on Linux with and without the fix. The fail-before proof is the Windows run above. Also run: `cargo clippy -p bun_install`, clean. </details> <!-- robobun:evidence:begin --> --- **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/bun-install-registry.test.ts, test/cli/install/bun-lock.test.ts <!-- robobun:evidence:end -->
What does this PR do?
Fixes the Linux flake in
test/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts(9 of the last ~80 main builds), which showed up as an unexpected extraleft-padentry in therequested-packagessnapshot:Cause: the "with modules" scenarios run a setup
bun install, clear the registry request log, then assert the exact set of manifests the command under test requests. With the manifest cache on, that set depended on whether the setup install's asynchronous cache writes had reached disk before it exited.bun installdeliberately does not wait for those writes (they are atomic-rename; a missing entry just means a refetch), so the asserted set was a race outcome, not a property of the command.Fix (test-only): disable the manifest cache for both installs in the matrix runner so the install under test always fetches its manifests, and regenerate the affected snapshots (the affected "with modules" scenarios, mostly the no-lockfile ones, now list the manifests they fetch).
An install-side wait for the pending cache writes (
pending_manifest_saves) was tried on this branch first and reverted in favor of keeping the cache write fire-and-forget. The reproduction numbers for the underlying write race are in the comments below.How did you verify your code works?
Test-only change: the with-modules scanner matrix runs with the regenerated snapshots in CI on all lanes.