Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion .changeset/remove-failed-optional-dependency.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
"pnpm": patch
---

pnpm now removes an optional dependency from `node_modules` if its install script fails, unless the global virtual store is enabled. Code that checks whether the package is installed no longer finds a package that cannot load [#8756](https://github.com/pnpm/pnpm/issues/8756).
`pnpm install` now removes an optional dependency from `node_modules` if its install script fails. Code that checks whether the package is installed no longer finds a package that cannot load [#8756](https://github.com/pnpm/pnpm/issues/8756).
74 changes: 65 additions & 9 deletions pnpm/crates/cli/tests/suite/global_virtual_store/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,11 +365,66 @@ fn gvs_build_failure_keeps_the_slot_marked_for_a_rebuild() {
drop((root, mock_instance));
}

/// An optional dependency whose build fails is skipped, but its GVS slot
/// stays for the same reason as [`gvs_build_failure_keeps_the_slot_marked_for_a_rebuild`]:
/// other projects may link it.
/// TS: `GVS removes an optional dependency whose build failed from its slot`
/// (`globalVirtualStore.ts`).
///
/// The package directory goes, so the parent's link inside its own shared
/// slot finds nothing, while the failed slot keeps its lock and links.
#[test]
fn gvs_optional_build_failure_keeps_the_slot() {
fn gvs_removes_an_optional_dependency_whose_build_failed_from_its_slot() {
let CommandTempCwd { root, workspace, npmrc_info, .. } =
CommandTempCwd::init().add_mocked_registry();
let AddMockedRegistry { store_dir, mock_instance, .. } = npmrc_info;

write_manifest(
&workspace,
&serde_json::json!({ "@pnpm.e2e/pkg-with-failing-optional-dependency": "1.0.0" }),
);
set_gvs_workspace_yaml(
&workspace,
&allow_builds_yaml(&[("@pnpm.e2e/pkg-with-failing-postinstall", true)]),
);
let failed_version_dir =
pkg_version_dir(&store_dir, "@pnpm.e2e/pkg-with-failing-postinstall", "1.0.0");
let parent_version_dir =
pkg_version_dir(&store_dir, "@pnpm.e2e/pkg-with-failing-optional-dependency", "1.0.0");

for _ in 0..2 {
pacquet(&workspace)
.with_arg("install")
.assert()
.success();

let failed_slot = sole_hash_dir(&failed_version_dir);
assert!(
!pkg_in_slot(&failed_slot, "@pnpm.e2e/pkg-with-failing-postinstall").exists(),
"the optional dependency whose build failed must be removed from its slot",
);
let parent_slot = sole_hash_dir(&parent_version_dir);
assert!(
pkg_in_slot(&parent_slot, "@pnpm.e2e/pkg-with-failing-optional-dependency")
.join("package.json")
.exists(),
"the parent must stay installed",
);
assert!(
!pkg_in_slot(&parent_slot, "@pnpm.e2e/pkg-with-failing-postinstall")
.join("package.json")
.exists(),
"the parent must not resolve the optional dependency whose build failed",
);
}

drop((root, mock_instance));
}

/// TS: `rebuild keeps a global virtual store slot whose optional build failed`
/// (`building/commands/test/build/index.ts`).
///
/// A rebuild may re-run the scripts of a slot other projects use with a
/// working build, so its failure keeps the slot.
#[test]
fn gvs_rebuild_keeps_the_slot_whose_optional_build_failed() {
let CommandTempCwd { root, workspace, npmrc_info, .. } =
CommandTempCwd::init().add_mocked_registry();
let AddMockedRegistry { store_dir, mock_instance, .. } = npmrc_info;
Expand All @@ -384,16 +439,17 @@ fn gvs_optional_build_failure_keeps_the_slot() {
);

pacquet(&workspace)
.with_arg("install")
.with_args(["install", "--ignore-scripts"])
.assert()
.success();
pacquet(&workspace)
.with_arg("rebuild")
.assert()
.success();

let version_dir = pkg_version_dir(&store_dir, "@pnpm.e2e/failing-postinstall", "1.0.0");
let pkg = pkg_in_slot(&sole_hash_dir(&version_dir), "@pnpm.e2e/failing-postinstall");
assert!(
pkg.join("package.json").exists(),
"the failed optional build's slot must stay in place",
);
assert!(pkg.join("package.json").exists(), "a failed rebuild must keep the slot");

drop((root, mock_instance));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ fn build_candidate<Reporter: self::Reporter>(
cache_key: Option<&str>,
optional: bool,
) -> Result<(), BuildModulesError> {
let Some((pkg_dir, _slot_lock)) = slot_to_build(context, snapshot_key, candidate)? else {
let Some((pkg_dir, slot_lock)) = slot_to_build(context, snapshot_key, candidate)? else {
return Ok(());
};

Expand All @@ -103,6 +103,7 @@ fn build_candidate<Reporter: self::Reporter>(
snapshot_key,
&pkg_dir,
&extra_bin_paths,
slot_lock.as_ref(),
(candidate.should_run_scripts, optional, &candidate.name, &candidate.version),
)?
else {
Expand Down Expand Up @@ -342,6 +343,7 @@ fn run_snapshot_scripts<Reporter: self::Reporter>(
snapshot_key: &PackageKey,
pkg_dir: &Path,
extra_bin_paths: &[PathBuf],
slot_lock: Option<&pnpm_fs::DirLock>,
run: (bool, bool, &str, &str),
) -> Result<Option<bool>, BuildModulesError> {
let (should_run_scripts, optional, name, version) = run;
Expand All @@ -357,11 +359,20 @@ fn run_snapshot_scripts<Reporter: self::Reporter>(
if !optional {
return Err(BuildModulesError::LifecycleScript(err));
}
discard_skipped_optional_dependency(
context.pkg_roots(),
context.directories.lockfile_dir,
snapshot_key,
)?;
// A global virtual store slot is removed only by an install that
// holds its lock. A rebuild may re-run the scripts of a slot other
// projects use with a working build, and without the lock another
// install may be writing into the slot. A kept slot stays marked
// for the next install to rebuild.
if !context.directories.layout.enable_global_virtual_store()
|| (context.rebuild.is_none() && slot_lock.is_some())
{
discard_skipped_optional_dependency(
context.pkg_roots(),
context.directories.lockfile_dir,
snapshot_key,
)?;
}
Reporter::emit(&LogEvent::SkippedOptionalDependency(SkippedOptionalDependencyLog {
level: LogLevel::Debug,
details: Some(err.to_string()),
Expand Down
19 changes: 9 additions & 10 deletions pnpm/crates/deps-restorer/src/build_modules/slots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,23 +108,22 @@ pub(crate) fn mark_global_virtual_store_build_started(pkg_roots: PkgRoots<'_>, k
}
}

/// Remove every project-local copy of an optional dependency whose build
/// Remove every installed copy of an optional dependency whose build
/// failed, so a consumer that probes for it finds it absent rather than
/// half-built.
/// half-built. The next install finds the directory missing and retries
/// the build.
///
/// A no-op under the global virtual store: other projects may link the
/// shared slot, so a failed build leaves it marked for the next install to
/// rebuild (see [`mark_global_virtual_store_build_started`]). A directory that is not a
/// plain descendant of the virtual store or the lockfile directory is left
/// alone, since its path comes from a lockfile-controlled package name.
/// Under the global virtual store this removes the package directory of
/// the shared slot, and the caller must hold the slot's lock. The slot
/// keeps its lock and its dependency links, and every project that links
/// it finds the package absent. A directory that is not a plain descendant
/// of the virtual store or the lockfile directory is left alone, since its
/// path comes from a lockfile-controlled package name.
pub(crate) fn discard_skipped_optional_dependency(
pkg_roots: PkgRoots<'_>,
lockfile_dir: &Path,
key: &PackageKey,
) -> Result<(), BuildModulesError> {
Comment thread
zkochan marked this conversation as resolved.
Resolved
if pkg_roots.layout.enable_global_virtual_store() {
return Ok(());
}
let virtual_store_dir = pkg_roots.layout.package_store_dir();
for pkg_dir in pkg_roots.all(key) {
if !is_contained_descendant(virtual_store_dir, &pkg_dir)
Expand Down
7 changes: 6 additions & 1 deletion pnpm11/building/during-install/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,9 @@ async function buildDependency<T extends string> (
} catch (err: unknown) {
assert(util.types.isNativeError(err))
if (depNode.optional) {
if (!opts.enableGlobalVirtualStore) {
// Without the lock another install may be writing into the shared
// slot, so the slot is kept, marked for the next install to rebuild.
if (!opts.enableGlobalVirtualStore || slotLock != null) {
await removeSkippedOptionalDependency(depNode, opts)
}
// TODO: add parents field to the log
Expand Down Expand Up @@ -648,6 +650,9 @@ function containedNodeModulesLink (modulesDir: string, alias: string): string |
* Remove every installed copy of an optional dependency whose build failed,
* so a consumer that probes for it finds it absent rather than half-built.
* The next install finds the directory missing and retries the build.
* Under the global virtual store this removes the package directory of the
* shared slot, whose lock the caller holds. The slot keeps its lock and its
* dependency links, and every project that links it finds the package absent.
* A hoisted location outside the lockfile directory is never removed.
* Rejects if a removal fails, so the package is not reported as skipped.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,39 @@ test('GVS build failure keeps the slot and marks it for a rebuild', async () =>
expect(fs.readFileSync(path.join(pkgInGvs, '.pnpm-needs-build'), 'utf8')).toBe('started')
})

test('GVS removes an optional dependency whose build failed from its slot', async () => {
prepareEmpty()
const globalVirtualStoreDir = path.resolve('links')
const manifest = {
dependencies: {
'@pnpm.e2e/pkg-with-failing-optional-dependency': '1.0.0',
},
}
const opts = testDefaults({
enableGlobalVirtualStore: true,
virtualStoreDir: globalVirtualStoreDir,
fastUnpack: false,
allowBuilds: { '@pnpm.e2e/pkg-with-failing-postinstall': true },
})
const failedVersionDir = path.join(globalVirtualStoreDir, '@pnpm.e2e/pkg-with-failing-postinstall/1.0.0')
const parentVersionDir = path.join(globalVirtualStoreDir, '@pnpm.e2e/pkg-with-failing-optional-dependency/1.0.0')

// A repeat install leaves the package removed.
for (let i = 0; i < 2; i++) {
// eslint-disable-next-line no-await-in-loop
await install(manifest, opts)

const hashes = fs.readdirSync(failedVersionDir)
expect(hashes).toHaveLength(1)
expect(fs.existsSync(path.join(failedVersionDir, hashes[0], 'node_modules/@pnpm.e2e/pkg-with-failing-postinstall'))).toBeFalsy()
const parentHashes = fs.readdirSync(parentVersionDir)
expect(parentHashes).toHaveLength(1)
const parentModules = path.join(parentVersionDir, parentHashes[0], 'node_modules')
expect(fs.existsSync(path.join(parentModules, '@pnpm.e2e/pkg-with-failing-optional-dependency/package.json'))).toBeTruthy()
expect(fs.existsSync(path.join(parentModules, '@pnpm.e2e/pkg-with-failing-postinstall/package.json'))).toBeFalsy()
}
})

test('GVS build waits for another install building the same slot', async () => {
prepareEmpty()
const globalVirtualStoreDir = path.resolve('links')
Expand Down
Loading