Skip to content

perf(pacquet): trim install-phase syscalls and allocations - #11864

Merged
zkochan merged 4 commits into
mainfrom
pacquet-perf4
May 25, 2026
Merged

zkochan merged 4 commits into
mainfrom
pacquet-perf4

Conversation

@zkochan

@zkochan zkochan commented May 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Continues the perf work from #11856 / #11857. Three install-phase wins on the clean-install path, none user-visible.

  • Striped CAS write lock. pacquet_fs::cas_write_lock used to lazily insert per-path Arc<Mutex<()>> entries into a process-global DashMap<PathBuf, Arc<Mutex<()>>>. Every CAFS write paid a PathBuf::to_path_buf clone + a DashMap shard write lock + an Arc<Mutex<()>> slot allocation, even though the lock is virtually never contended. Replaced with 256 static Mutex<()> stripes keyed by hashed path. Same writer/verifier coordination invariant the per-path mutex provided (writers and verifiers of the same &Path hash to the same stripe), no allocations on the hot path.

  • Skip the pre-flight fs::metadata stat on fresh-target imports. link_file does a fs::metadata(target_link) first so the no-op-on-existing-target contract holds for the Copy method (fs::copy would otherwise silently overwrite). populate_dir only ever runs against a directory it just mkdir'd, so the protection is wasted there — every call goes NotFound. Added a new import_into_fresh_target entry point that skips the stat and lets the import syscall's EEXIST handle the rare collision case. Saves ~170k stat syscalls per clean install on the alotta-files fixture. link_file keeps its full semantics for any caller that genuinely doesn't know whether the target is fresh.

  • Trim per-CAS-file allocations. cas_file_path formats the sha-512 hex into a 128-byte stack buffer instead of a heap String, and <root>/v11/files is memoised on StoreDir behind a OnceLock so file_path_by_head_tail borrows it instead of rebuilding the PathBuf per call.

Bench

5-run hyperfine against the verdaccio mock on the 3343-package alotta-files fixture, 10-core M-series Mac:

wall user sys
baseline (976504f) ~27.8 s 6.0 s 34.4 s
this PR 25.5 s ± 1.9 6.05 s 32.5 s
pnpm v11.2.1 20.9 s ± 1.7 7.4 s 18.5 s

Best pacquet run dropped from ~28 s to 23.2 s, ~10 % improvement on the median.

This doesn't close the gap to pnpm. The remaining ~20 % is dominated by sys-time in clonefileat — pacquet issues roughly twice the kernel time per file as pnpm does, plausibly because pacquet has ~20 concurrent threads contending for the APFS metadata journal where pnpm's libuv pool is bounded to 4. The rayon-pool-size knob discussed in #11851 helps on bigger hosts but regresses 23.95 s → 27.67 s on this 10-core machine, so I left the default alone; the RAYON_NUM_THREADS escape hatch still lets users on bigger hosts tune it.

Test plan

  • `cargo nextest run -p pacquet-fs -p pacquet-store-dir -p pacquet-tarball` (382 tests pass)
  • `cargo nextest run -p pacquet-package-manager` (298 tests pass)
  • `cargo clippy --locked --workspace --all-targets -- --deny warnings` clean
  • Manual clean-install run against verdaccio mock on the bench fixture
  • CI: `just ready` (delegated to CI)

Written by an agent (Claude Code, claude-opus-4-7).

Summary by CodeRabbit

  • Performance

    • More efficient file locking for better concurrency (striped static locks)
    • Reduced memory allocations when constructing file hashes/paths
    • Cached file-store directory path for faster lookups
  • Bug Fixes

    • Improved atomic import/creation path to handle races without failures
  • Documentation

    • Clarified contributor guideline and updated comments to reflect current contracts
  • Tests

    • Updated tests to align with new locking behavior
  • Chores

    • Updated workspace dependency list (one dependency replaced)

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5e1a12d1-8306-4d1a-98a0-675c49019930

📥 Commits

Reviewing files that changed from the base of the PR and between bc46f55 and c2c01b4.

📒 Files selected for processing (2)
  • AGENTS.md
  • pacquet/crates/fs/src/ensure_file.rs
✅ Files skipped from review due to trivial changes (1)
  • AGENTS.md
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Run benchmark on ubuntu-latest
  • GitHub Check: Lint and Test (macos-latest)
  • GitHub Check: Lint and Test (windows-latest)
  • GitHub Check: Lint and Test (ubuntu-latest)
  • GitHub Check: Run benchmark on ubuntu-latest
  • GitHub Check: Code Coverage
  • GitHub Check: Compile & Lint
🧰 Additional context used
📓 Path-based instructions (1)
pacquet/**/*.rs

📄 CodeRabbit inference engine (pacquet/AGENTS.md)

pacquet/**/*.rs: When porting a function that fires pnpm:<channel> events through globalLogger, logger.debug(), or streamParser.write(), mirror the call site, payload, and ordering so the reporter parses pacquet's NDJSON the same way it parses pnpm's.
Declare a newtype wrapper for branded string types. Do not collapse the brand into a plain String or &str.
If upstream always validates before construction, validate in pacquet's wrapper too. The wrapper must construct only via TryFrom<String> and/or FromStr. Do not provide an infallible public constructor.
If upstream never validates, just brand for type-safety. Expose an infallible From<String> (and From<&str> when convenient).
If upstream occasionally constructs without validation, expose from_str_unchecked as an escape hatch alongside the validating constructor.
Match upstream serde behavior for branded types that cross JSON, YAML, or INI boundaries. Use #[serde(try_from = "String")] for deserialization and #[serde(into = "String")] for serialization.
Use #[derive(derive_more::From)] and #[derive(derive_more::Into)] for mechanical conversion impls. Fall back to manual impl only when conversion needs custom logic.
String-literal unions should become enums, not newtype wrappers. Model closed sets of valid string values as enums.
Template literal types should be treated as branded strings with validation discipline from rules 2-5.
Choose owned vs. borrowed parameters to minimize copies. Widen to the most encompassing type (&Path over &PathBuf, &str over &String) when it doesn't force extra copies.
Prefer Arc::clone(&x) / Rc::clone(&x) over x.clone() for reference-counted types, so the cost is visible at the call site.
Follow Rust API Guidelines for naming conventions.
Do not use star imports inside module bodies. Write use super::{Foo, bar} instead of use super::*;. Two forms stay allowed: external-crate preludes like use rayon::prelude::*; and root-of-module re-...

Files:

  • pacquet/crates/fs/src/ensure_file.rs
🧠 Learnings (4)
📓 Common learnings
Learnt from: CR
Repo: pnpm/pnpm

Timestamp: 2026-05-25T12:31:18.760Z
Learning: Keep pnpm and pacquet in sync: Any user-visible change (CLI flags, defaults, environment-variable handling, lockfile/manifest/state-file format, error codes and messages, log emissions, store layout, hook semantics) must land in both the TypeScript pnpm CLI and the Rust pacquet port in the same PR, or with matching commits pushed to the same PR
Learnt from: CR
Repo: pnpm/pnpm

Timestamp: 2026-05-25T12:31:18.760Z
Learning: Before writing new code, search the codebase for existing similar functionality in shared directories (packages/, fs/, crypto/, text/) to avoid duplication. Extract common logic into shared packages rather than duplicating it across locations
Learnt from: CR
Repo: pnpm/pnpm

Timestamp: 2026-05-25T12:31:18.760Z
Learning: Prefer open source packages over custom implementations for common tasks (path manipulation, string utilities, data structures, schema validation). Only write custom code when no suitable package exists or existing packages are too heavy or unmaintained
Learnt from: CR
Repo: pnpm/pnpm

Timestamp: 2026-05-25T12:31:18.760Z
Learning: Follow the Conventional Commits specification for commit messages with types: feat, fix, docs, style, refactor, perf, test, chore
Learnt from: CR
Repo: pnpm/pnpm

Timestamp: 2026-05-25T12:31:18.760Z
Learning: For TypeScript packages, create a changeset file in the .changeset directory for any changes that affect published packages. Always explicitly include 'pnpm' in the changeset with the appropriate version bump (patch, minor, or major)
Learnt from: CR
Repo: pnpm/pnpm

Timestamp: 2026-05-25T12:31:18.760Z
Learning: Never dismiss a failing test as pre-existing or unrelated to changes. Every test failure must be investigated and fixed. If a test was broken before changes, fix it as part of the work rather than skipping it
Learnt from: CR
Repo: pnpm/pnpm

Timestamp: 2026-05-25T12:31:18.760Z
Learning: For the pnpm CLI, always rebuild the bundle (pnpm/dist/pnpm.mjs) before running e2e tests by running 'pnpm --filter pnpm run compile'. E2e tests use the bundled pnpm/dist/pnpm.mjs, not individual package lib/ outputs
Learnt from: CR
Repo: pnpm/pnpm

Timestamp: 2026-05-25T12:31:18.760Z
Learning: Keep PR titles and descriptions current. When pushing new changes to a PR, review and update the title and description if they no longer accurately reflect what the PR does
Learnt from: CR
Repo: pnpm/pnpm

Timestamp: 2026-05-25T12:31:18.760Z
Learning: Reply to and resolve review conversations on GitHub PRs. Once a review comment is addressed, reply with a description of the resolution including the commit hash, then mark the conversation as resolved
Learnt from: CR
Repo: pnpm/pnpm

Timestamp: 2026-05-25T12:31:18.760Z
Learning: Sign all agent-authored content on GitHub (comments, issues, PRs) with a footer indicating the agent name and model name. Example: '--- Written by an agent (Agent Name, model-name).'
📚 Learning: 2026-05-20T19:40:55.051Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 11774
File: pacquet/crates/resolving-deps-resolver/src/resolve_peers.rs:0-0
Timestamp: 2026-05-20T19:40:55.051Z
Learning: In the pacquet Rust code, ensure the semver implementation uses the `node-semver` crate (not `nodejs-semver`). `node-semver`’s public API does not include a `satisfies_with_prerelease`-style method; prerelease-tolerant matching should be implemented inline by first calling `Range::satisfies`, and when it rejects a prerelease version, retry matching against a stripped `MAJOR.MINOR.PATCH` base of the prerelease version.

Applied to files:

  • pacquet/crates/fs/src/ensure_file.rs
📚 Learning: 2026-05-22T00:08:44.646Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 11837
File: pacquet/crates/resolving-npm-resolver/src/pick_package.rs:33-51
Timestamp: 2026-05-22T00:08:44.646Z
Learning: In the pnpm/pnpm repo’s pacquet Rust crates, do not flag Unicode ellipsis characters (U+2026, `…`) in Rust doc comments (`///` / `/** */`) as a lint violation. The pacquet crate’s `dylint.toml` only enables `perfectionist::derive_ordering`, and the Dylint `unicode-ellipsis` rule is not enabled for this project—so `…` in doc comments is an intentional, repo-consistent style.

Applied to files:

  • pacquet/crates/fs/src/ensure_file.rs
📚 Learning: 2026-05-20T23:07:58.444Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 11784
File: pacquet/crates/resolving-deps-resolver/src/hoist_peers.rs:120-133
Timestamp: 2026-05-20T23:07:58.444Z
Learning: When reviewing code in this pacquet Rust port, follow the upstream pnpm compatibility rule: only match pnpm’s behavior exactly. Do not propose review changes that intentionally deviate from pnpm’s documented/observed behavior, even if pnpm appears buggy. If you identify a real bug in pnpm behavior, the review should prioritize fixing it upstream in pnpm first, and avoid implementing a pnpm-behavior workaround here unless the same fix has already landed upstream.

Applied to files:

  • pacquet/crates/fs/src/ensure_file.rs
🔇 Additional comments (1)
pacquet/crates/fs/src/ensure_file.rs (1)

201-234: LGTM!


📝 Walkthrough

Walkthrough

This PR replaces per-path DashMap-based write locking with static hash-striped mutexes, extracts a fresh-target import helper for syscall-based imports (EEXIST-as-no-op), and memoizes StoreDir's files path while changing hex formatting to use a stack buffer.

Changes

Process-Local Synchronization and Import Refactoring

Layer / File(s) Summary
Static Striped Mutex Locking
pacquet/crates/fs/Cargo.toml, pacquet/crates/fs/src/ensure_file.rs, pacquet/crates/fs/tests/ensure_file_stress.rs, pacquet/crates/store-dir/tests/verify_writer_race.rs
Removes dashmap from dependencies and implements cas_write_lock to return a &'static Mutex<()> selected from a fixed array of hash-striped static mutexes. Tests and docs updated to reflect the new static striping and pointer-equality checks.
Fresh-Target Import Helper Extraction and Usage
pacquet/crates/package-manager/src/link_file.rs, pacquet/crates/package-manager/src/import_indexed_dir.rs
Adds pub fn import_into_fresh_target(...) that encapsulates the syscall import path including EEXIST-as-no-op handling when callers guarantee a fresh target. link_file delegates to it for the non-present-target path; import_indexed_dir uses it for parallel fresh-target materialization without per-file fs::metadata pre-flights.
StoreDir Path Memoization and Hex Allocation
pacquet/crates/store-dir/src/store_dir.rs, pacquet/crates/store-dir/src/cas_file.rs
Adds a OnceLock<PathBuf> field to memoize <root>/files (skipped during serde) and refactors helpers to use the cached path. Replaces format!-based hex allocation with a fixed stack buffer written via write! and converted to &str for path construction.
Documentation guideline
AGENTS.md
Adds a short guideline asking authors/agents to describe the current contract in comments rather than referencing prior implementation history.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

  • pnpm/pnpm#11825: Overlaps on cas_write_lock API and verifier coordination; this PR changes the lock implementation/signature.
  • pnpm/pnpm#11856: Also refactors import/EEXIST handling in link_file.rs with related control-flow changes.
  • pnpm/pnpm#11758: Introduced the earlier DashMap-based cas_write_lock approach which this PR replaces.

Poem

🐰 A striped little lock I bring,
No DashMap thump, no costly string,
Fresh paths import with tidy grace,
Hex on stack, no heap to chase —
Hoppity-hop, the build sings!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: performance optimizations focused on reducing syscalls and memory allocations in the install phase through lock contention reduction, fs::metadata elimination, and stack-based formatting.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch pacquet-perf4

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions

github-actions Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
tarball/download_dependency    1.01      8.0±0.13ms   541.1 KB/sec    1.00      8.0±0.25ms   544.4 KB/sec

@codecov-commenter

codecov-commenter commented May 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.67%. Comparing base (ac299aa) to head (c2c01b4).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #11864      +/-   ##
==========================================
+ Coverage   87.66%   87.67%   +0.01%     
==========================================
  Files         220      220              
  Lines       26780    26800      +20     
==========================================
+ Hits        23477    23498      +21     
+ Misses       3303     3302       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

github-actions Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Scenario: Isolated linker: fresh restore, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.983 ± 0.080 1.860 2.107 1.00
pacquet@main 2.041 ± 0.056 1.941 2.118 1.03 ± 0.05
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.98341088356,
      "stddev": 0.08022731564940004,
      "median": 1.97240507016,
      "user": 2.6799873999999995,
      "system": 3.40313836,
      "min": 1.85970811466,
      "max": 2.10686265566,
      "times": [
        2.10686265566,
        2.09038875666,
        2.04445034966,
        1.85970811466,
        1.93061135866,
        1.97117017966,
        1.9568737866600001,
        2.00620187266,
        1.97363996066,
        1.8942018006599999
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.04139128716,
      "stddev": 0.0560674974328728,
      "median": 2.03949180566,
      "user": 2.6823957999999997,
      "system": 3.4826000599999993,
      "min": 1.9414386966600001,
      "max": 2.11821697266,
      "times": [
        2.11195371866,
        2.00239041666,
        2.07988195966,
        2.06003267666,
        2.11821697266,
        2.07130302766,
        2.00639704566,
        1.9414386966600001,
        2.00334742266,
        2.01895093466
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 623.3 ± 27.4 603.8 698.6 1.00
pacquet@main 658.5 ± 9.9 645.9 680.0 1.06 ± 0.05
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.62331202822,
      "stddev": 0.027426183948389894,
      "median": 0.61575620942,
      "user": 0.3438495599999999,
      "system": 1.3385654200000001,
      "min": 0.60379387142,
      "max": 0.69855021442,
      "times": [
        0.69855021442,
        0.61742201442,
        0.6142724914200001,
        0.6305398774200001,
        0.60379387142,
        0.60774525842,
        0.62015895742,
        0.61219913042,
        0.61119853942,
        0.61723992742
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.65854916012,
      "stddev": 0.009918696135150163,
      "median": 0.6542738434200001,
      "user": 0.37162295999999995,
      "system": 1.4577562199999998,
      "min": 0.6459165544200001,
      "max": 0.68000500742,
      "times": [
        0.68000500742,
        0.65320852542,
        0.6549603834200001,
        0.65358730342,
        0.66549649042,
        0.66444120742,
        0.65094374742,
        0.66388049042,
        0.65305189142,
        0.6459165544200001
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.492 ± 0.045 2.430 2.552 1.00
pacquet@main 2.542 ± 0.038 2.463 2.597 1.02 ± 0.02
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.49222062086,
      "stddev": 0.045439305978791276,
      "median": 2.4805694022600004,
      "user": 4.287993519999999,
      "system": 3.3314880599999994,
      "min": 2.4303777382600003,
      "max": 2.5523295422600003,
      "times": [
        2.52551623526,
        2.45540077726,
        2.46796191126,
        2.4303777382600003,
        2.54553261826,
        2.46560222326,
        2.5523295422600003,
        2.44551591026,
        2.54079235926,
        2.4931768932600002
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.5417738921599997,
      "stddev": 0.03793339441775452,
      "median": 2.55622966376,
      "user": 4.244300919999999,
      "system": 3.50191246,
      "min": 2.4627566612600003,
      "max": 2.59675910126,
      "times": [
        2.56142393326,
        2.51355062026,
        2.5054457192600004,
        2.5600217182600002,
        2.54284911426,
        2.55670543326,
        2.55575389426,
        2.56247272626,
        2.4627566612600003,
        2.59675910126
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, hot cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.599 ± 0.020 1.565 1.633 1.00
pacquet@main 1.674 ± 0.035 1.641 1.760 1.05 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.5986666136600003,
      "stddev": 0.019958538972096356,
      "median": 1.59758506166,
      "user": 1.9596742999999996,
      "system": 1.9945507199999999,
      "min": 1.5652063541599999,
      "max": 1.6327827031600002,
      "times": [
        1.58879042716,
        1.62842033816,
        1.58610455416,
        1.60063651416,
        1.60119412116,
        1.59453360916,
        1.58746768816,
        1.5652063541599999,
        1.60152982716,
        1.6327827031600002
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.67353453156,
      "stddev": 0.03490509590914394,
      "median": 1.66340960716,
      "user": 2.0302426999999996,
      "system": 2.1281613199999994,
      "min": 1.6408411571600001,
      "max": 1.7603539111600002,
      "times": [
        1.6408411571600001,
        1.66665153716,
        1.65362156016,
        1.7603539111600002,
        1.65100407116,
        1.66016767716,
        1.68636859816,
        1.69515633116,
        1.64915982616,
        1.67202064616
      ]
    }
  ]
}

@github-actions

github-actions Bot commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/11864
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
2,492.22 ms
(-40.21%)Baseline: 4,168.09 ms
5,001.71 ms
(49.83%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,598.67 ms
(-49.75%)Baseline: 3,181.48 ms
3,817.78 ms
(41.87%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
1,983.41 ms
(-11.98%)Baseline: 2,253.29 ms
2,703.94 ms
(73.35%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
623.31 ms
(-4.71%)Baseline: 654.11 ms
784.93 ms
(79.41%)
🐰 View full continuous benchmarking report in Bencher

zkochan added 2 commits May 25, 2026 13:23
…fresh-target imports

Two install-phase syscall trims:

- `cas_write_lock` swaps the per-path `DashMap<PathBuf, Arc<Mutex<()>>>`
  for 256 static `Mutex<()>` stripes keyed by hashed path. Every CAFS
  write previously paid one `PathBuf::to_path_buf` allocation, a
  `DashMap` shard write lock, plus an `Arc<Mutex<()>>` slot allocation
  even though contention was vanishingly rare. Striping keeps the
  writer/verifier coordination the per-path mutex provided while
  removing those per-call costs. With 256 stripes and ~10 rayon
  workers the false-sharing probability per pair is ~4%, and the
  guarded body (one `O_CREAT|O_EXCL` open + `write_all` of a tar
  entry) is microseconds long.

- `import_indexed_dir::populate_dir` now calls a new
  `import_into_fresh_target` instead of `link_file`. `populate_dir`
  only ever runs against a directory it just `mkdir`'d, so the
  `fs::metadata` pre-flight `link_file` performs to protect the
  Copy-method overwrite contract is wasted — every call is `NotFound`
  in practice and the EEXIST surface from the import syscall is the
  only collision signal we need. Saves ~170k `stat` syscalls per
  clean install on the alotta-files fixture. `link_file` still
  exists with the original semantics for any caller that genuinely
  doesn't know whether the target is fresh.

On the 3343-package alotta-files fixture against the verdaccio mock,
clean-install wall time goes from ~28s to ~19-22s on the local 10-core
machine — roughly closing the gap to pnpm (~20s) for that scenario.

Refs #11857, #11851.
Two micro-optimisations in `cas_file_path`, the helper every CAFS
write goes through:

- `cas_file_path` no longer `format!`s the sha-512 digest into a
  fresh `String`. Sha-512 is always 64 bytes / 128 hex chars, so
  render the hex into a stack buffer and slice it into the
  `file_path_by_hex_str` call instead. One heap allocation per file
  shaved off — ~170k on the alotta-files clean install.

- The repeated `self.v11().join("files")` rebuild used to walk two
  `PathBuf::join`s per call. Memoise the result behind a `OnceLock`
  on `StoreDir` (`cached_files_dir`) so `file_path_by_head_tail`
  borrows it without re-joining. Race-free initialisation across
  rayon workers, one allocation per process instead of one per file.

Refs #11857.
@zkochan
zkochan marked this pull request as ready for review May 25, 2026 12:09
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@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

🧹 Nitpick comments (1)
pacquet/crates/fs/src/ensure_file.rs (1)

242-247: ⚡ Quick win

Add a compile-time guard for the stripe-mask invariant.

cas_write_lock uses & (NUM_CAS_LOCK_STRIPES - 1), which is only correct when the stripe count stays a power of two. Please enforce this with a const assertion so future edits can’t silently break lock distribution/correctness.

Proposed hardening
 const NUM_CAS_LOCK_STRIPES: usize = 256;
+const _: () = assert!(NUM_CAS_LOCK_STRIPES.is_power_of_two());
🤖 Prompt for 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.

In `@pacquet/crates/fs/src/ensure_file.rs` around lines 242 - 247, Add a
compile-time assertion that NUM_CAS_LOCK_STRIPES is a power of two to protect
the stripe-mask invariant used by cas_write_lock; update the constant block
containing NUM_CAS_LOCK_STRIPES to include a const assert (for example using
static_assertions::const_assert! or a const-evaluated check like const _: () = {
assert!(NUM_CAS_LOCK_STRIPES.is_power_of_two()); }; or an equivalent
compile-time array-length trick) so any future change that makes
NUM_CAS_LOCK_STRIPES non-power-of-two fails to compile.
🤖 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 `@pacquet/crates/package-manager/src/import_indexed_dir.rs`:
- Around line 98-99: The docs incorrectly mention link_file() as the
materialization helper; update the comment text to reference the new helper
import_into_fresh_target() (and note that populate_dir calls
import_into_fresh_target()) so readers know which function performs the
pre-flight metadata stat; replace occurrences of link_file() in the comment
block (also at the similar comment around lines 114-115) with
import_into_fresh_target() and keep the mention of matching pnpm's
importIndexedPackage semantics.

---

Nitpick comments:
In `@pacquet/crates/fs/src/ensure_file.rs`:
- Around line 242-247: Add a compile-time assertion that NUM_CAS_LOCK_STRIPES is
a power of two to protect the stripe-mask invariant used by cas_write_lock;
update the constant block containing NUM_CAS_LOCK_STRIPES to include a const
assert (for example using static_assertions::const_assert! or a const-evaluated
check like const _: () = { assert!(NUM_CAS_LOCK_STRIPES.is_power_of_two()); };
or an equivalent compile-time array-length trick) so any future change that
makes NUM_CAS_LOCK_STRIPES non-power-of-two fails to compile.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a9f6216a-b3c6-4369-b2aa-0f81835b90e0

📥 Commits

Reviewing files that changed from the base of the PR and between ac299aa and d839a15.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (8)
  • pacquet/crates/fs/Cargo.toml
  • pacquet/crates/fs/src/ensure_file.rs
  • pacquet/crates/fs/tests/ensure_file_stress.rs
  • pacquet/crates/package-manager/src/import_indexed_dir.rs
  • pacquet/crates/package-manager/src/link_file.rs
  • pacquet/crates/store-dir/src/cas_file.rs
  • pacquet/crates/store-dir/src/store_dir.rs
  • pacquet/crates/store-dir/tests/verify_writer_race.rs
💤 Files with no reviewable changes (1)
  • pacquet/crates/fs/Cargo.toml
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: ubuntu-latest / Node.js 24 / Test
  • GitHub Check: Run benchmark on ubuntu-latest
🧰 Additional context used
📓 Path-based instructions (2)
pacquet/**/*.rs

📄 CodeRabbit inference engine (pacquet/AGENTS.md)

pacquet/**/*.rs: When porting a function that fires pnpm:<channel> events through globalLogger, logger.debug(), or streamParser.write(), mirror the call site, payload, and ordering so the reporter parses pacquet's NDJSON the same way it parses pnpm's.
Declare a newtype wrapper for branded string types. Do not collapse the brand into a plain String or &str.
If upstream always validates before construction, validate in pacquet's wrapper too. The wrapper must construct only via TryFrom<String> and/or FromStr. Do not provide an infallible public constructor.
If upstream never validates, just brand for type-safety. Expose an infallible From<String> (and From<&str> when convenient).
If upstream occasionally constructs without validation, expose from_str_unchecked as an escape hatch alongside the validating constructor.
Match upstream serde behavior for branded types that cross JSON, YAML, or INI boundaries. Use #[serde(try_from = "String")] for deserialization and #[serde(into = "String")] for serialization.
Use #[derive(derive_more::From)] and #[derive(derive_more::Into)] for mechanical conversion impls. Fall back to manual impl only when conversion needs custom logic.
String-literal unions should become enums, not newtype wrappers. Model closed sets of valid string values as enums.
Template literal types should be treated as branded strings with validation discipline from rules 2-5.
Choose owned vs. borrowed parameters to minimize copies. Widen to the most encompassing type (&Path over &PathBuf, &str over &String) when it doesn't force extra copies.
Prefer Arc::clone(&x) / Rc::clone(&x) over x.clone() for reference-counted types, so the cost is visible at the call site.
Follow Rust API Guidelines for naming conventions.
Do not use star imports inside module bodies. Write use super::{Foo, bar} instead of use super::*;. Two forms stay allowed: external-crate preludes like use rayon::prelude::*; and root-of-module re-...

Files:

  • pacquet/crates/fs/tests/ensure_file_stress.rs
  • pacquet/crates/store-dir/src/cas_file.rs
  • pacquet/crates/package-manager/src/link_file.rs
  • pacquet/crates/package-manager/src/import_indexed_dir.rs
  • pacquet/crates/fs/src/ensure_file.rs
  • pacquet/crates/store-dir/src/store_dir.rs
  • pacquet/crates/store-dir/tests/verify_writer_race.rs
pacquet/**/{tests,test}/**/*.rs

📄 CodeRabbit inference engine (pacquet/AGENTS.md)

pacquet/**/{tests,test}/**/*.rs: Prefer real fixtures; reach for the dependency-injection seam only when they can't cover the branch. Most happy paths and error paths should be tested with tempfile::TempDir, the mocked registry, or an integration test that spawns the actual binary.
Use the DI seam — a capability trait on the Host provider, threaded as Sys: <Bounds> — only for branches a real fixture can't reach portably: filesystem error kinds, deterministic time, shared process-global state, or external-service happy paths.
Log before non-assert_eq! assertions, dbg! complex structures, skip logging for simple scalar assert_eq!. Follow the test-logging guidance in CODE_STYLE_GUIDE.md.
Tests must not be tolerant of missing build/runtime environment by silently returning early when a tool isn't found. If the test needs a tool, let it panic when the tool is absent.
Prefer #[cfg_attr(target_os = "windows", ignore = "...")] (or #[cfg(unix)]) over a runtime probe-and-skip helper for platform-locked tools.
Port relevant tests from pnpm when porting behavior. Matching test coverage is the easiest way to prove behavioral parity.
When porting behavior from pnpm, consult plans/TEST_PORTING.md before adding ported tests. Use allow_known_failure! at the not-yet-implemented boundary and update checkboxes as items land.

Files:

  • pacquet/crates/fs/tests/ensure_file_stress.rs
  • pacquet/crates/store-dir/tests/verify_writer_race.rs
🧠 Learnings (3)
📚 Learning: 2026-05-20T19:40:55.051Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 11774
File: pacquet/crates/resolving-deps-resolver/src/resolve_peers.rs:0-0
Timestamp: 2026-05-20T19:40:55.051Z
Learning: In the pacquet Rust code, ensure the semver implementation uses the `node-semver` crate (not `nodejs-semver`). `node-semver`’s public API does not include a `satisfies_with_prerelease`-style method; prerelease-tolerant matching should be implemented inline by first calling `Range::satisfies`, and when it rejects a prerelease version, retry matching against a stripped `MAJOR.MINOR.PATCH` base of the prerelease version.

Applied to files:

  • pacquet/crates/fs/tests/ensure_file_stress.rs
  • pacquet/crates/store-dir/src/cas_file.rs
  • pacquet/crates/package-manager/src/link_file.rs
  • pacquet/crates/package-manager/src/import_indexed_dir.rs
  • pacquet/crates/fs/src/ensure_file.rs
  • pacquet/crates/store-dir/src/store_dir.rs
  • pacquet/crates/store-dir/tests/verify_writer_race.rs
📚 Learning: 2026-05-22T00:08:44.646Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 11837
File: pacquet/crates/resolving-npm-resolver/src/pick_package.rs:33-51
Timestamp: 2026-05-22T00:08:44.646Z
Learning: In the pnpm/pnpm repo’s pacquet Rust crates, do not flag Unicode ellipsis characters (U+2026, `…`) in Rust doc comments (`///` / `/** */`) as a lint violation. The pacquet crate’s `dylint.toml` only enables `perfectionist::derive_ordering`, and the Dylint `unicode-ellipsis` rule is not enabled for this project—so `…` in doc comments is an intentional, repo-consistent style.

Applied to files:

  • pacquet/crates/fs/tests/ensure_file_stress.rs
  • pacquet/crates/store-dir/src/cas_file.rs
  • pacquet/crates/package-manager/src/link_file.rs
  • pacquet/crates/package-manager/src/import_indexed_dir.rs
  • pacquet/crates/fs/src/ensure_file.rs
  • pacquet/crates/store-dir/src/store_dir.rs
  • pacquet/crates/store-dir/tests/verify_writer_race.rs
📚 Learning: 2026-05-20T23:07:58.444Z
Learnt from: zkochan
Repo: pnpm/pnpm PR: 11784
File: pacquet/crates/resolving-deps-resolver/src/hoist_peers.rs:120-133
Timestamp: 2026-05-20T23:07:58.444Z
Learning: When reviewing code in this pacquet Rust port, follow the upstream pnpm compatibility rule: only match pnpm’s behavior exactly. Do not propose review changes that intentionally deviate from pnpm’s documented/observed behavior, even if pnpm appears buggy. If you identify a real bug in pnpm behavior, the review should prioritize fixing it upstream in pnpm first, and avoid implementing a pnpm-behavior workaround here unless the same fix has already landed upstream.

Applied to files:

  • pacquet/crates/fs/tests/ensure_file_stress.rs
  • pacquet/crates/store-dir/src/cas_file.rs
  • pacquet/crates/package-manager/src/link_file.rs
  • pacquet/crates/package-manager/src/import_indexed_dir.rs
  • pacquet/crates/fs/src/ensure_file.rs
  • pacquet/crates/store-dir/src/store_dir.rs
  • pacquet/crates/store-dir/tests/verify_writer_race.rs
🧬 Code graph analysis (3)
pacquet/crates/package-manager/src/link_file.rs (1)
pacquet/crates/package-manager/src/import_indexed_dir.rs (1)
  • import_into_fresh_target (216-216)
pacquet/crates/package-manager/src/import_indexed_dir.rs (1)
pacquet/crates/package-manager/src/link_file.rs (2)
  • LinkFileError (15-28)
  • import_into_fresh_target (163-188)
pacquet/crates/store-dir/src/store_dir.rs (1)
pacquet/crates/store-dir/src/cas_file.rs (1)
  • StoreDir (11-61)
🔇 Additional comments (7)
pacquet/crates/store-dir/src/store_dir.rs (1)

4-7: LGTM!

Also applies to: 63-69, 101-101, 132-133, 135-141, 149-149

pacquet/crates/store-dir/src/cas_file.rs (1)

14-30: LGTM!

pacquet/crates/fs/src/ensure_file.rs (1)

5-5: LGTM!

Also applies to: 9-9, 203-240, 249-250

pacquet/crates/fs/tests/ensure_file_stress.rs (1)

18-20: LGTM!

pacquet/crates/store-dir/tests/verify_writer_race.rs (1)

206-207: LGTM!

Also applies to: 217-218

pacquet/crates/package-manager/src/link_file.rs (1)

140-141: LGTM!

Also applies to: 143-168, 178-180

pacquet/crates/package-manager/src/import_indexed_dir.rs (1)

1-1: LGTM!

Also applies to: 208-223

- Refresh `import_indexed_dir` doc comments so they name
  `import_into_fresh_target()` (the actual materialization helper
  after the fresh-target split) instead of `link_file()`.
- Add a const assertion that `NUM_CAS_LOCK_STRIPES` stays a power of
  two, since `cas_write_lock` uses `& (NUM_CAS_LOCK_STRIPES - 1)` as
  the stripe selector.
- Extend AGENTS.md Comments rules: comments must describe the
  current contract, not what the code replaced. Phrasings like
  "used to", "previously", "the original X", or parentheticals
  naming a removed type belong in `git log`.
- Apply the rule to `cas_write_lock`'s doc, which previously
  framed itself in terms of the removed
  `DashMap<PathBuf, Arc<Mutex<()>>>` shape.
@zkochan
zkochan merged commit d579e6c into main May 25, 2026
23 checks passed
@zkochan
zkochan deleted the pacquet-perf4 branch May 25, 2026 12:36
@zkochan zkochan mentioned this pull request May 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants