Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/install/PackageManager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,10 @@ pub struct PackageManager {
///
/// TODO: Does this need to be atomic? It seems to be accessed only from the main thread.
pub(crate) pending_pre_calc_hashes: AtomicU32,
/// Manifest cache writes still running on the thread pool. Not part of
/// `pending_tasks` (nothing consumes their result), but `sleep_until` and
/// the runtime's module poll do not report done until they land.
pub pending_manifest_saves: AtomicU32,
pub pending_tasks: AtomicU32,
pub total_tasks: u32,
pub(crate) preallocated_network_tasks: PreallocatedNetworkTasks,
Expand Down Expand Up @@ -947,6 +951,24 @@ impl PackageManager {
trampoline::<C>,
)
};

// The tasks the caller waited on may have handed manifest cache
// writes to the thread pool (`Serializer::save_async`). Nothing reads
// their result, but returning — and letting the command exit — before
// they land makes what the next run finds cached a matter of thread
// scheduling, so every wait also covers them.
fn saves_landed(this: *mut c_void) -> bool {
// SAFETY: `this` is the `*mut PackageManager` passed below; atomic
// field projection only, no `&mut PackageManager` is formed.
unsafe {
(*this.cast::<PackageManager>())
.pending_manifest_saves
.load(Ordering::Acquire)
== 0
}
}
// SAFETY: as above; `saves_landed` never borrows `*event_loop`.
unsafe { AnyEventLoop::tick_raw(event_loop, this.cast::<c_void>(), saves_landed) };
}

pub(crate) fn ensure_temp_node_gyp_script(&mut self) -> Result<(), Error> {
Expand Down Expand Up @@ -1922,6 +1944,7 @@ pub fn init(
wr!(patch_calc_hash_batch, thread_pool::Batch::default());
wr!(patch_task_queue, PatchTaskQueue::default());
wr!(pending_pre_calc_hashes, AtomicU32::new(0));
wr!(pending_manifest_saves, AtomicU32::new(0));
wr!(pending_tasks, AtomicU32::new(0));
wr!(total_tasks, 0);
wr!(lifecycle_script_time_log, LifecycleScriptTimeLog::default());
Expand Down Expand Up @@ -2355,6 +2378,7 @@ fn init_with_runtime_once(
wr!(patch_task_fifo, PatchTaskFifo::init());
wr!(patch_task_queue, PatchTaskQueue::default());
wr!(pending_pre_calc_hashes, AtomicU32::new(0));
wr!(pending_manifest_saves, AtomicU32::new(0));
wr!(pending_tasks, AtomicU32::new(0));
wr!(total_tasks, 0);
wr!(lifecycle_script_time_log, LifecycleScriptTimeLog::default());
Expand Down
26 changes: 20 additions & 6 deletions src/install/npm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1237,11 +1237,10 @@ pub mod package_manifest {
}

/// We save into a temporary directory and then move the file to the cache directory.
/// Saving the files to the manifest cache doesn't need to prevent application exit.
/// It's an optional cache.
/// Therefore, we choose to not increment the pending task count or wake up the main thread.
///
/// This might leave temporary files in the temporary directory that will never be moved to the cache directory. We'll see if anyone asks about that.
/// Nothing consumes the result, so this is not a `pending_tasks` entry;
/// it is counted in `pending_manifest_saves` instead so the command
/// waits for the write to land before exiting (otherwise whether the
/// next run finds the manifest cached depends on thread scheduling).
pub(crate) fn save_async(
this: &PackageManifest,
scope: &registry::Scope,
Expand Down Expand Up @@ -1301,6 +1300,17 @@ pub mod package_manifest {
Output::flush();
}
}
drop(save_task);

let pm = crate::package_manager::get();
// SAFETY: atomic field projection from a worker thread (no
// `&mut PackageManager`); `wake_raw` is the thread-safe wake.
unsafe {
(*pm)
.pending_manifest_saves
.fetch_sub(1, core::sync::atomic::Ordering::Release);
PackageManager::wake_raw(pm);
}
}
}

Expand All @@ -1317,7 +1327,11 @@ pub mod package_manifest {

// SAFETY: task is a valid Box-allocated SaveTask
let batch = PoolBatch::from(unsafe { core::ptr::addr_of_mut!((*task).task) });
PackageManager::get().thread_pool.schedule(batch);
let manager = PackageManager::get();
manager
.pending_manifest_saves
.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
manager.thread_pool.schedule(batch);
}

fn manifest_file_name<'b>(
Expand Down
4 changes: 3 additions & 1 deletion src/jsc/AsyncModule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,9 @@ impl Queue {
// `container_of`-derived `*mut` reborrow. The package manager is a
// separate heap allocation, disjoint from `self` (= `vm.modules`).
let pm = VirtualMachine::get().as_mut().package_manager();
if pm.pending_tasks.load(Ordering::Relaxed) > 0 {
if pm.pending_tasks.load(Ordering::Relaxed) > 0
|| pm.pending_manifest_saves.load(Ordering::Relaxed) > 0
{
return;
}

Expand Down
104 changes: 104 additions & 0 deletions test/cli/install/bun-install-manifest-cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe, tempDir } from "harness";
import { createHash } from "node:crypto";
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";

// Manifest cache writes are handed to the install thread pool, and `bun
// install` must not exit before they land (`pending_manifest_saves` in
// PackageManager). A manifest with many unique strings makes the cache write
// take longer than the rest of the install, so a bun that does not wait exits
// first and the `.npm` file never appears in the cache directory.
//
// Sized so the write reliably loses that race on unfixed builds (debug and
// release) while staying far from the race on fixed ones, which wait. The
// string data must be unique per entry: repeated strings are deduplicated by
// the serializer and shrink the write.
const FAKE_VERSIONS = 6_000;
const DEPS_PER_VERSION = 8;
const INSTALL_ITERATIONS = 3;

function buildManifest(origin: string, shasum: string): string {
const pad = Buffer.alloc(800, "ab-cd.").toString();
const versions: string[] = [];
for (let v = 0; v < FAKE_VERSIONS; v++) {
const version = `1.${Math.floor(v / 1000)}.${v % 1000}`;
const deps: string[] = [];
for (let d = 0; d < DEPS_PER_VERSION; d++) {
const n = (v * DEPS_PER_VERSION + d).toString().padStart(7, "0");
deps.push(`"fake-dependency-package-name-padding-${n}":"1.0.0-${n}.${pad}"`);
}
versions.push(
`"${version}":{"name":"baz","version":"${version}","dependencies":{${deps.join(",")}},` +
`"dist":{"shasum":"${shasum}","tarball":"${origin}/baz/-/baz-${version}.tgz"}}`,
);
}
versions.push(
`"0.0.3":{"name":"baz","version":"0.0.3","dist":{"shasum":"${shasum}","tarball":"${origin}/baz/-/baz-0.0.3.tgz"}}`,
);
return `{"name":"baz","dist-tags":{"latest":"0.0.3"},"versions":{${versions.join(",")}}}`;
}

test(
"bun install waits for manifest cache writes before exiting",
async () => {
const tarball = readFileSync(join(import.meta.dir, "baz-0.0.3.tgz"));
const shasum = createHash("sha1").update(tarball).digest("hex");

let manifest = "";
await using server = Bun.serve({
port: 0,
fetch(req) {
if (new URL(req.url).pathname.endsWith(".tgz")) {
return new Response(tarball, { headers: { "Content-Type": "application/octet-stream" } });
}
return new Response(manifest, { headers: { "Content-Type": "application/json" } });
},
});
const origin = `http://127.0.0.1:${server.port}`;
manifest = buildManifest(origin, shasum);

const files: Record<string, string> = {};
for (let i = 0; i < INSTALL_ITERATIONS; i++) {
files[`p${i}/package.json`] = JSON.stringify({
name: "manifest-cache-wait",
version: "1.0.0",
dependencies: { baz: "0.0.3" },
});
files[`p${i}/bunfig.toml`] = `[install]\nregistry = "${origin}/"\n`;
}
using dir = tempDir("manifest-cache-wait", files);

for (let i = 0; i < INSTALL_ITERATIONS; i++) {
const cwd = join(String(dir), `p${i}`);
await using proc = Bun.spawn({
cmd: [bunExe(), "install", "--ignore-scripts", "--silent"],
cwd,
// CI exports BUN_INSTALL_CACHE_DIR (shared per-run tmpdir), and the
// env var outranks bunfig. Point it at this iteration's cache dir so
// every install is a cold fetch and the assertion reads the right dir.
env: { ...bunEnv, BUN_INSTALL_CACHE_DIR: join(cwd, "cache") },
stdout: "ignore",
stderr: "pipe",
});
const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]);
// The install exited; the manifest for `baz` must already be in the
// cache directory. Without the wait the process exits mid-write and the
// file is missing.
const cacheDir = join(cwd, "cache");
const manifestFiles = existsSync(cacheDir) ? readdirSync(cacheDir).filter(f => f.endsWith(".npm")) : [];
expect({
iteration: i,
manifestFiles: manifestFiles.length,
exitCode,
stderr: exitCode === 0 ? "" : stderr,
}).toEqual({
iteration: i,
manifestFiles: 1,
exitCode: 0,
stderr: "",
});
}
},
{ timeout: 240_000 },
);