Skip to content

fix(deps-restorer): repair a shared virtual-store slot in place - #13810

Merged
zkochan merged 12 commits into
pnpm:mainfrom
lazerg:fix/issue-13806-shared-slot-repair-in-place
Aug 11, 2026
Merged

zkochan merged 12 commits into
pnpm:mainfrom
lazerg:fix/issue-13806-shared-slot-repair-in-place

Conversation

@lazerg

@lazerg lazerg commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When two importers reach the same global virtual-store slot at once, the first one populates it in place and only writes the completion marker at the end. The second one arrives while that is happening, sees a directory that exists but has no marker, so its non-destructive rename fails on an occupied target, is_complete_import says no, and it drops through to remove_dir_all. That removes the files the first importer is still writing, and the final rmdir then loses the race against those writes and reports ENOTEMPTY.

A safe-to-skip target is content-addressed by its path, so an incomplete one does not have to be removed at all. It now takes the same in-place populate_dir repair that the marker-less path already uses for force: false, which is non-destructive and converges when both importers run it.

To confirm the diagnosis I ran the scenario with a 600-file package and the second thread held back until the slot appeared: 6 failures in 200 runs on main with the exact RemoveExisting { ... code: 66 } from the issue, 0 in 400 runs after the change.

Repairing in place has to heal the slot, not just fill in what is missing. The linking tiers report EEXIST for a dirent that is already there, so an in-place repair that adopts whatever it finds keeps a file truncated by an interrupted copy — and then puts the completion marker on top of it, so every later install sees a finished slot and never looks again. The destructive path used to hide this by rebuilding the tree.

So the gate is now pnpm's allFilesMatch (fs/indexed-pkg-importer/src/importIndexedDir.ts) rather than a check that each file exists, and the repair swaps a fresh copy in through a temp sibling for every entry that does not match its store file. An entry that shares the store inode is recognised without a read, so an intact slot still costs two stats per file. The repair also clears a dirent of the wrong kind, which the wipe used to take care of implicitly.

The shared-slot branch moved ahead of the node_modules preservation step. A slot repaired in place keeps a nested node_modules/ by never removing anything, so a package with bundled dependencies no longer falls through to the destructive path this PR exists to avoid.

The regression tests assert the slot directory keeps its inode across a repair, that a damaged file is restored under a linking tier (the earlier tests all used Copy, where fs::copy overwrites and hides the difference), and that a file the package does not declare is left alone — removing strays from a slot other projects read is the destructive behavior being retired.

The same fix in the TypeScript CLI

importIndexedDir there has its own safeToSkip, and both halves of the bug: a slot that fails allFilesMatch falls through to renameOverwriteSync, which removes the directory a concurrent importer is writing into, and the fast path that writes into a shared slot in place adopts whatever dirent it finds, so a truncated file survives and the completion marker lands on top of it.

A shared target is now populated by whoever wins an exclusive mkdir, adopted by everyone else when it matches, and otherwise repaired entry by entry, each mismatching file swapped in through a temp sibling. Nothing on that path unlinks, so a nested node_modules/ survives without the staging dance keepModulesDir needed.

One addition the Rust side already had: safeToSkip is restricted to targets whose path pins their contents, which is what the flag has always asked of its callers. link.ts and deps-restorer pass enableGlobalVirtualStore straight through, so an injected local package — copied into its target at install time, and free to change with no lockfile change — was reaching the mode too. Its stale files still need a rebuild to clear, so resolvedFrom: 'local-dir' now takes the staging path, matching pacquet's source_is_mutable exclusion.

Fixes #13806

Squash Commit Body

An importer that finds a shared virtual-store slot occupied but incomplete cannot tell an interrupted import from another importer that is still writing into it. Removing the directory in the second case deletes files that importer is in the middle of creating, and the trailing rmdir then fails with ENOTEMPTY.

Repair an incomplete safe-to-skip target in place instead of removing and swapping it. The mode is only used where the target path uniquely identifies its contents, so there are no stale files to clear, and two importers running the repair against one slot converge on the same tree.

Gate the slot on allFilesMatch rather than on existence, and place every entry that does not match its store file through a temp sibling, so a file left damaged by an interrupted import is healed rather than adopted. Run the whole branch before the node_modules preservation step, since repairing in place already preserves a nested node_modules by never removing anything.

Fixes pnpm/pnpm#13806

Checklist

  • I checked the referenced issue and verified that none of the PRs
    already linked to it solves it.
  • The change lands in both stacks: importIndexedDir in the TypeScript
    CLI has the same safeToSkip mode and the same two problems with it, and
    is fixed the same way here.
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests.

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Bug Fixes

    • Repaired incomplete shared package installations in place without deleting active directories.
    • Replaced damaged files while preserving valid and unrelated content, including nested dependencies.
    • Resolved file-versus-directory conflicts and removed stale files from local installations.
    • Prevented unnecessary changes to complete installations during repair.
    • Improved recovery from interrupted or partially completed package installations.
  • Tests

    • Added coverage for corrupted files, incomplete installations, directory mismatches, stale content, and structure preservation.

@lazerg
lazerg requested a review from zkochan as a code owner August 11, 2026 06:36
@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 commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The shared-slot import path now repairs incomplete occupied virtual-store slots in place. It preserves complete slots and unrelated entries, replaces damaged entries atomically, and validates actual store contents.

Changes

Shared slot repair

Layer / File(s) Summary
Placement modes and import routing
pnpm/crates/deps-restorer/src/import_indexed_dir.rs
The importer separates fresh placement from repair placement and routes directory, file, and marker operations through placement-aware helpers.
In-place repair and completeness validation
pnpm/crates/deps-restorer/src/import_indexed_dir.rs
Repair placement preserves matching and undeclared entries, clears blocking entries, replaces damaged entries atomically, and compares target contents with the store.
Safe-skip integration and public options
pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts, pnpm11/store/controller-types/src/index.ts
Safe-to-skip non-local targets use shared-directory repair. ImportIndexedDirOptions accepts resolvedFrom, which is re-exported from the controller types.
Regression coverage and release metadata
pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs, pnpm11/fs/indexed-pkg-importer/test/importIndexedDir.test.ts, .changeset/repair-shared-slot-in-place.md
Tests cover missing files, corruption, file/directory mismatches, nested dependencies, target directory preservation, and occupied-target classification. The changeset records the repair behavior.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Importer
  participant SharedSlot
  participant Store
  Importer->>SharedSlot: inspect occupied target
  SharedSlot->>Store: compare expected contents
  Store-->>Importer: report matching and damaged entries
  Importer->>SharedSlot: repair entries in place
  SharedSlot-->>Importer: retain complete target directory
Loading

Assessment against linked issues

Objective Addressed Explanation
Both concurrent importers succeed when they materialize the same shared virtual-store slot [#13806] ✅

Possibly related PRs

  • pnpm/pnpm#13648: Both PRs modify shared virtual-store slot preservation and repair logic.
  • pnpm/pnpm#13649: Both PRs modify indexed-directory import and completion behavior.

Suggested labels: product: pacquet, product: pnpm@11

Suggested reviewers: zkochan

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@greptile-apps

greptile-apps Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge within the eligible follow-up-review scope.

No blocking failure remains.

Reviews (10): Last reviewed commit: "fix(indexed-pkg-importer): validate file..." | Re-trigger Greptile

greptile-apps[bot]
greptile-apps Bot previously approved these changes Aug 11, 2026
@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Aug 11, 2026
@codecov-commenter

codecov-commenter commented Aug 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.01796% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.25%. Comparing base (ac97bc1) to head (e789d29).
⚠️ Report is 12 commits behind head on main.

Files with missing lines Patch % Lines
...npm/crates/deps-restorer/src/import_indexed_dir.rs 90.96% 15 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff            @@
##             main   #13810     +/-   ##
=========================================
  Coverage   88.24%   88.25%             
=========================================
  Files         624      625      +1     
  Lines      101807   102927   +1120     
=========================================
+ Hits        89837    90835    +998     
- Misses      11970    12092    +122     

☔ View full report in Codecov by Harness.
📢 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 Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: e789d29ebde7

Regular scenarios report direct and pnpr installs. The peer-heavy resolver scenario compares current Rust, main Rust, and TypeScript pnpm. Bencher consumes pacquet@HEAD and pnpr@HEAD.

The tables below show mean ± σ; Bencher thresholds on the minimum latency, which is far less perturbed by shared-runner contention (noise only adds time).

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.484 ± 0.179 2.328 2.813 1.62 ± 0.20
pacquet@main 2.499 ± 0.118 2.384 2.695 1.63 ± 0.18
pnpr@HEAD 1.573 ± 0.153 1.380 1.783 1.03 ± 0.14
pnpr@main 1.531 ± 0.151 1.378 1.775 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.48395962958,
      "stddev": 0.1794112753037104,
      "median": 2.4002687431800003,
      "user": 1.66380424,
      "system": 1.4263624599999998,
      "min": 2.3279880151800003,
      "max": 2.8132844301800004,
      "times": [
        2.37458275118,
        2.3628919021800003,
        2.3279880151800003,
        2.5728523881800003,
        2.43220139118,
        2.4061461271800004,
        2.7874942121800004,
        2.8132844301800004,
        2.36776371918,
        2.39439135918
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.4994595284800005,
      "stddev": 0.11840437219811455,
      "median": 2.45876652568,
      "user": 1.65295514,
      "system": 1.34843566,
      "min": 2.38357988118,
      "max": 2.6947024071800003,
      "times": [
        2.6947024071800003,
        2.6474456021800004,
        2.4979035411800004,
        2.6402986321800004,
        2.39633317418,
        2.41485714118,
        2.49250363418,
        2.38357988118,
        2.4019418541800004,
        2.42502941718
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.5729558020799999,
      "stddev": 0.15323646531493204,
      "median": 1.5648573501799998,
      "user": 1.10353034,
      "system": 1.17095716,
      "min": 1.37994034918,
      "max": 1.7825237651799999,
      "times": [
        1.6051142481799998,
        1.76323262718,
        1.4576364851799999,
        1.44337497018,
        1.39371069118,
        1.71315032318,
        1.7825237651799999,
        1.37994034918,
        1.66627410918,
        1.5246004521799998
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.5312289097799998,
      "stddev": 0.15090670179674723,
      "median": 1.47279765468,
      "user": 1.0892032399999998,
      "system": 1.16759816,
      "min": 1.37810060618,
      "max": 1.77542926618,
      "times": [
        1.7113241561800001,
        1.77542926618,
        1.4038712571799998,
        1.37810060618,
        1.59340348318,
        1.3918959841799998,
        1.41167840418,
        1.47276144118,
        1.47283386818,
        1.70099063118
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 264.4 ± 5.0 253.0 269.3 1.00
pacquet@main 266.4 ± 11.5 254.0 284.9 1.01 ± 0.05
pnpr@HEAD 287.0 ± 7.7 273.3 299.8 1.09 ± 0.04
pnpr@main 279.2 ± 8.9 269.1 294.7 1.06 ± 0.04
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.2643891923,
      "stddev": 0.004979036215853874,
      "median": 0.2653039627,
      "user": 0.23010776000000002,
      "system": 0.5361328399999999,
      "min": 0.25296856570000004,
      "max": 0.2692663637,
      "times": [
        0.2686230867,
        0.26753119670000003,
        0.2636594807,
        0.2685443987,
        0.25296856570000004,
        0.2607558917,
        0.2692663637,
        0.26640076570000004,
        0.2619350137,
        0.2642071597
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.26638153280000004,
      "stddev": 0.011466611594665716,
      "median": 0.2630272052,
      "user": 0.21975276,
      "system": 0.5513754399999999,
      "min": 0.2539826697,
      "max": 0.28486261370000004,
      "times": [
        0.2700044187,
        0.25476585970000004,
        0.2539826697,
        0.2620932227,
        0.2585530977,
        0.2845243397,
        0.2576635387,
        0.28486261370000004,
        0.26396118770000004,
        0.27340437970000003
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.2869788625,
      "stddev": 0.007691805125126416,
      "median": 0.2850473712,
      "user": 0.23976826,
      "system": 0.56050894,
      "min": 0.27332653370000004,
      "max": 0.2998171197,
      "times": [
        0.28290091170000004,
        0.2863436037,
        0.2837511387,
        0.2998171197,
        0.29559482470000004,
        0.2919879057,
        0.27332653370000004,
        0.2909210747,
        0.2823252417,
        0.28282027070000004
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.27916155930000003,
      "stddev": 0.008851027734287815,
      "median": 0.27608993470000004,
      "user": 0.23014465999999997,
      "system": 0.5475193399999998,
      "min": 0.26914061770000003,
      "max": 0.2946912507,
      "times": [
        0.2855895077,
        0.27668422470000004,
        0.2842326907,
        0.26914061770000003,
        0.27549564470000004,
        0.28992115770000004,
        0.2946912507,
        0.2733603277,
        0.2723127607,
        0.2701874107
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.702 ± 0.063 2.657 2.869 1.61 ± 0.16
pacquet@main 2.754 ± 0.067 2.674 2.899 1.64 ± 0.16
pnpr@HEAD 1.678 ± 0.159 1.454 1.981 1.00
pnpr@main 1.749 ± 0.130 1.517 1.896 1.04 ± 0.13
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.7016968855199996,
      "stddev": 0.06349786975802904,
      "median": 2.67229429182,
      "user": 1.74559124,
      "system": 1.5232626599999999,
      "min": 2.65719948182,
      "max": 2.86885230682,
      "times": [
        2.86885230682,
        2.66811557182,
        2.69182419382,
        2.66926682582,
        2.67461094582,
        2.6699776378199997,
        2.66659382482,
        2.65719948182,
        2.72715788382,
        2.72337018282
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.75360218012,
      "stddev": 0.06682626946421996,
      "median": 2.7564175878199997,
      "user": 2.0048897400000003,
      "system": 1.6101599599999996,
      "min": 2.67378305682,
      "max": 2.89945350582,
      "times": [
        2.67387376682,
        2.89945350582,
        2.76063998982,
        2.77712844182,
        2.76652010682,
        2.75219518582,
        2.67378305682,
        2.74274390382,
        2.69410644882,
        2.79557739482
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.6776679564199999,
      "stddev": 0.15904678927291543,
      "median": 1.68021952382,
      "user": 1.2323849399999998,
      "system": 1.3277332599999998,
      "min": 1.4535319868199998,
      "max": 1.98077566682,
      "times": [
        1.98077566682,
        1.7139304278199998,
        1.58009991082,
        1.47249058282,
        1.79892758582,
        1.7880250388199999,
        1.4535319868199998,
        1.6228100638199998,
        1.71957968082,
        1.64650861982
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.7490415132200003,
      "stddev": 0.13020511430879966,
      "median": 1.7714419508199999,
      "user": 1.1690331399999998,
      "system": 1.29428996,
      "min": 1.51742000982,
      "max": 1.89554399782,
      "times": [
        1.89554399782,
        1.51742000982,
        1.66947520082,
        1.8476337698199998,
        1.79106999482,
        1.87556894582,
        1.7518139068199998,
        1.5611297788199998,
        1.83990664382,
        1.74085288382
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 474.9 ± 26.9 429.4 507.1 1.23 ± 0.10
pacquet@main 496.9 ± 29.7 446.3 545.3 1.29 ± 0.10
pnpr@HEAD 384.6 ± 20.1 352.0 414.0 1.00
pnpr@main 458.7 ± 65.0 362.1 580.8 1.19 ± 0.18
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.47489737052000003,
      "stddev": 0.026896883693089416,
      "median": 0.48208239252000007,
      "user": 0.67654938,
      "system": 0.7530816399999999,
      "min": 0.42935724302000006,
      "max": 0.50710676802,
      "times": [
        0.47768608102000004,
        0.49746023802000006,
        0.48647870402000004,
        0.49722388502000003,
        0.50710676802,
        0.43574648202000005,
        0.47551009702,
        0.45263203702000004,
        0.48977217002000006,
        0.42935724302000006
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.49692385712,
      "stddev": 0.029736308182089426,
      "median": 0.5038360310200001,
      "user": 0.6778667799999999,
      "system": 0.7898735399999999,
      "min": 0.44629559702000005,
      "max": 0.5452698300200001,
      "times": [
        0.47655455702000005,
        0.49396962602000005,
        0.47931423602000006,
        0.5452698300200001,
        0.51415930202,
        0.51370243602,
        0.5158672670200001,
        0.46617761602,
        0.51792810402,
        0.44629559702000005
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.38463782432,
      "stddev": 0.020110206141611197,
      "median": 0.38369363152,
      "user": 0.29356467999999997,
      "system": 0.6251649399999999,
      "min": 0.35203832702000004,
      "max": 0.41399592802,
      "times": [
        0.36314775302,
        0.40266373302,
        0.38309649602,
        0.37804807202,
        0.39948029002,
        0.41399592802,
        0.40300354102,
        0.36661333602,
        0.35203832702000004,
        0.38429076702000003
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.4587051535200001,
      "stddev": 0.06503818855527886,
      "median": 0.47151309652000006,
      "user": 0.36209907999999996,
      "system": 0.70194054,
      "min": 0.36214787602000004,
      "max": 0.5807732680200001,
      "times": [
        0.36214787602000004,
        0.50796419502,
        0.43195472702000004,
        0.5807732680200001,
        0.47813396002,
        0.38175546102,
        0.46489223302000005,
        0.40629747202000005,
        0.48074932302000006,
        0.49238302002000006
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.243 ± 0.057 2.139 2.307 4.84 ± 0.36
pacquet@main 2.498 ± 0.277 2.177 3.026 5.39 ± 0.71
pnpr@HEAD 0.463 ± 0.032 0.415 0.509 1.00
pnpr@main 0.542 ± 0.045 0.463 0.631 1.17 ± 0.13
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.2430971544399996,
      "stddev": 0.05663903881217623,
      "median": 2.24397185504,
      "user": 1.6845323799999998,
      "system": 1.2865679399999999,
      "min": 2.13930824304,
      "max": 2.30671385004,
      "times": [
        2.30406358404,
        2.21209292504,
        2.20071907204,
        2.29785535604,
        2.2645258030399997,
        2.30671385004,
        2.2842994980399998,
        2.22341790704,
        2.13930824304,
        2.19797530604
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.4981358655399997,
      "stddev": 0.27660648576645513,
      "median": 2.48770031304,
      "user": 1.8885213799999998,
      "system": 1.3997036399999998,
      "min": 2.17707165604,
      "max": 3.02636752904,
      "times": [
        2.41021649104,
        3.02636752904,
        2.69180698404,
        2.56518413504,
        2.74803441904,
        2.60661457004,
        2.27387339004,
        2.23385693704,
        2.17707165604,
        2.2483325440399997
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.46315039964000004,
      "stddev": 0.0322819839338396,
      "median": 0.46342025854,
      "user": 0.36260367999999993,
      "system": 0.74400274,
      "min": 0.41524493104000004,
      "max": 0.50870482104,
      "times": [
        0.48819046204,
        0.50870482104,
        0.46149037204000004,
        0.43238827604,
        0.50459958804,
        0.41524493104000004,
        0.47888325404000004,
        0.46535014504,
        0.44905079604000003,
        0.42760135104
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.5415337070399999,
      "stddev": 0.045389071185028274,
      "median": 0.54090877004,
      "user": 0.4314161799999999,
      "system": 0.8223583400000001,
      "min": 0.46269416104,
      "max": 0.63078089804,
      "times": [
        0.5529407310400001,
        0.51861979904,
        0.46269416104,
        0.58300418204,
        0.55737501304,
        0.50372032804,
        0.52438441804,
        0.63078089804,
        0.54315926404,
        0.53865827604
      ]
    }
  ]
}

Scenario: Isolated linker: fresh resolve, hot cache, offline

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 375.0 ± 38.1 313.0 428.9 2.90 ± 0.40
pacquet@main 372.7 ± 38.2 319.4 435.1 2.88 ± 0.40
pnpr@HEAD 129.5 ± 12.1 109.6 150.5 1.00
pnpr@main 131.4 ± 13.4 110.4 160.9 1.01 ± 0.14
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.37499162102000005,
      "stddev": 0.03806195055716591,
      "median": 0.37157231002,
      "user": 0.37663414,
      "system": 0.10328816,
      "min": 0.31303989352000006,
      "max": 0.42885676352,
      "times": [
        0.31303989352000006,
        0.41940454752000006,
        0.33434151452000005,
        0.35023284752000006,
        0.41770422552,
        0.37334105052000005,
        0.42885676352,
        0.38118583752,
        0.36980356952000004,
        0.36200596052000006
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.3726612402200001,
      "stddev": 0.03819825363020643,
      "median": 0.36681244902000004,
      "user": 0.37157854,
      "system": 0.11050246,
      "min": 0.31941815752,
      "max": 0.43511794752000005,
      "times": [
        0.35688368352000005,
        0.43511794752000005,
        0.36562621652000005,
        0.36799868152000004,
        0.31941815752,
        0.32143783952000005,
        0.37878044252000004,
        0.35829081652000005,
        0.42119592152,
        0.40186269552000004
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.12951827781166672,
      "stddev": 0.012122675995160825,
      "median": 0.13076665152000003,
      "user": 0.044932665000000004,
      "system": 0.019806759999999996,
      "min": 0.10958129852000001,
      "max": 0.15050293252000002,
      "times": [
        0.11349392452000001,
        0.11277763952,
        0.12837578252,
        0.12863850552000003,
        0.13829103752000002,
        0.11322808552000001,
        0.11648082252,
        0.13486376352,
        0.13442855652000002,
        0.12813291752000003,
        0.11012025052,
        0.10958129852000001,
        0.12022036252,
        0.13777105152000002,
        0.12712140752,
        0.15050293252000002,
        0.14310027552000001,
        0.14657967852000003,
        0.13881414052000002,
        0.13289479752000002,
        0.13863512252000001,
        0.14211071752,
        0.13743498052000003,
        0.12484061652000002
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.1313797929961905,
      "stddev": 0.013404141905130444,
      "median": 0.12942613552,
      "user": 0.041671492380952385,
      "system": 0.023104640952380955,
      "min": 0.11044062252,
      "max": 0.16092792552000001,
      "times": [
        0.12936731352000003,
        0.11577682952,
        0.14578750052000003,
        0.14936250252000002,
        0.12749973752000002,
        0.13802621052000003,
        0.11615310652000001,
        0.11906267852,
        0.11044062252,
        0.13918411452,
        0.13036727252000002,
        0.16092792552000001,
        0.12647302152,
        0.12942613552,
        0.13338977552000003,
        0.12043227952,
        0.14442200752000003,
        0.14376493352000003,
        0.14244631852000003,
        0.12383254352,
        0.11283282352
      ]
    }
  ]
}

Scenario: Isolated linker: peer-heavy resolve, hot cache, offline

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.237 ± 0.263 0.857 1.624 1.26 ± 0.35
pacquet@main 0.979 ± 0.177 0.769 1.253 1.00
pnpm@HEAD 3.585 ± 0.120 3.389 3.743 3.66 ± 0.67
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.2367371895155557,
      "stddev": 0.26321098655932634,
      "median": 1.30397984896,
      "user": 1.2521644066666666,
      "system": 0.2322545533333333,
      "min": 0.85688030096,
      "max": 1.62438054896,
      "times": [
        0.89407056296,
        1.33147027496,
        1.39510470796,
        1.45237136996,
        1.27214217296,
        1.30397984896,
        1.00023491796,
        1.62438054896,
        0.85688030096
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.9791195856266667,
      "stddev": 0.17663304351576184,
      "median": 0.94265527796,
      "user": 0.9629016288888889,
      "system": 0.17207822,
      "min": 0.76883519096,
      "max": 1.2533257019600001,
      "times": [
        0.86675593896,
        1.2533257019600001,
        0.94405687796,
        1.20431198296,
        0.80348962496,
        0.94265527796,
        0.76883519096,
        0.8898948049600001,
        1.1387508699600002
      ]
    },
    {
      "command": "pnpm@HEAD",
      "mean": 3.5849615837377775,
      "stddev": 0.11996724422784816,
      "median": 3.60513471296,
      "user": 5.492009073333333,
      "system": 0.2965625533333333,
      "min": 3.38851591296,
      "max": 3.74326720896,
      "times": [
        3.38851591296,
        3.53938551696,
        3.70265699096,
        3.4534079589599997,
        3.64455810796,
        3.74326720896,
        3.50980264096,
        3.60513471296,
        3.67792520296
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.709 ± 0.188 4.476 4.962 1.32 ± 0.07
pacquet@main 4.520 ± 0.074 4.431 4.646 1.27 ± 0.04
pnpr@HEAD 3.561 ± 0.108 3.474 3.843 1.00
pnpr@main 3.593 ± 0.130 3.492 3.914 1.01 ± 0.05
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.70881901206,
      "stddev": 0.18753681352754809,
      "median": 4.69033485466,
      "user": 2.22078302,
      "system": 1.6334487600000003,
      "min": 4.47628831766,
      "max": 4.96225040866,
      "times": [
        4.96225040866,
        4.61762723166,
        4.55047083466,
        4.47628831766,
        4.76304247766,
        4.82173530266,
        4.93106784766,
        4.54566786566,
        4.51879174666,
        4.90124808766
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.51963978866,
      "stddev": 0.0736184219961869,
      "median": 4.496287242659999,
      "user": 1.85384212,
      "system": 1.4395883599999997,
      "min": 4.43064553266,
      "max": 4.64645011266,
      "times": [
        4.48534969166,
        4.59889634766,
        4.43064553266,
        4.50722479366,
        4.59903164166,
        4.44771419866,
        4.45794021266,
        4.48198115366,
        4.64645011266,
        4.54116420166
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.56131351616,
      "stddev": 0.10827618613831308,
      "median": 3.5299964176599996,
      "user": 1.3330122199999999,
      "system": 1.34219486,
      "min": 3.47376340866,
      "max": 3.84261734566,
      "times": [
        3.53645440266,
        3.47376340866,
        3.63548688766,
        3.4979494076599997,
        3.84261734566,
        3.5235384326599997,
        3.5528443786599997,
        3.5423324036599997,
        3.51330512066,
        3.4948433736599998
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.59330337056,
      "stddev": 0.13023501953872957,
      "median": 3.54874056566,
      "user": 1.40057622,
      "system": 1.3968342599999999,
      "min": 3.49192494766,
      "max": 3.91382585166,
      "times": [
        3.59202093966,
        3.49192494766,
        3.50546019166,
        3.50226977566,
        3.64243780766,
        3.6367650446599997,
        3.50030651166,
        3.64449933366,
        3.5035233016599996,
        3.91382585166
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13810
Testbedpacquet

🚨 1 Alert

BenchmarkMeasure
Units
ViewBenchmark Result
(Result Δ%)
Upper Boundary
(Limit %)
isolated-linker.fresh-resolve.hot-cache.offlineLatency
milliseconds (ms)
📈 plot
🚷 threshold
🚨 alert (🔔)
313.04 ms
(+32.71%)Baseline: 235.89 ms
283.06 ms
(110.59%)

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,657.20 ms
(-1.75%)Baseline: 2,704.51 ms
3,245.41 ms
(81.88%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
2,139.31 ms
(+18.11%)Baseline: 1,811.21 ms
2,173.45 ms
(98.43%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
429.36 ms
(-7.17%)Baseline: 462.51 ms
555.02 ms
(77.36%)
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
🚨 view alert (🔔)
313.04 ms
(+32.71%)Baseline: 235.89 ms
283.06 ms
(110.59%)

isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
2,327.99 ms
(-5.51%)Baseline: 2,463.69 ms
2,956.43 ms
(78.74%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
4,476.29 ms
(-1.29%)Baseline: 4,534.69 ms
5,441.62 ms
(82.26%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
252.97 ms
(-15.90%)Baseline: 300.81 ms
360.97 ms
(70.08%)
isolated-linker.peer-heavy-resolve.hot-cache.offline📈 view plot
🚷 view threshold
856.88 ms
(+15.67%)Baseline: 740.82 ms
888.99 ms
(96.39%)
🐰 View full continuous benchmarking report in Bencher

Repairing a shared slot in place stopped it from being destroyed under a
concurrent importer, but it also stopped it from being healed: the linking
tiers report EEXIST for a dirent that is already there, and the repair
adopted it whatever its content. A file truncated by an interrupted copy
therefore survived the repair, and the completion marker went down on top
of it, so every later install saw a finished slot and never looked again.

Gate the slot on pnpm's `allFilesMatch` rather than on existence, and give
the repair a placement mode that swaps a fresh copy in through a temp
sibling for every entry that does not match its store file. Matching
entries are recognised by their shared store inode, so an intact slot
still costs two stats per file and no read.

The repair also clears a dirent of the wrong kind, which the previous
wipe-and-swap took care of implicitly, and it now runs before the
node_modules preservation dance instead of after it: a slot repaired in
place keeps its nested node_modules by never removing anything, so a
package with bundled dependencies no longer falls through to the
destructive path the fix exists to avoid.
@greptile-apps
greptile-apps Bot dismissed their stale review August 11, 2026 12:26

Dismissed because a newer commit was pushed; Greptile will re-review the current head.

@zkochan

zkochan commented Aug 11, 2026

Copy link
Copy Markdown
Member

Pushed 5cdc49c on top of this branch.

Repairing the slot in place fixed the crash but gave up the self-healing the destructive path provided as a side effect. The linking tiers (Auto → clone/hardlink, which is what installs actually use) return EEXIST for a dirent that is already there, and import_into_fresh_target adopts it. So an incomplete slot holding a file truncated by an interrupted copy kept that file, and the repair then placed the completion marker on top — after which is_complete_import was true forever and no later install would look at it again. Verified against the branch with PackageImportMethod::Hardlink: index.js stayed half-written, where main rebuilt it. Every test in the file used Copy, where fs::copy overwrites, which is why safe_to_skip_does_not_accept_a_slot_that_is_still_being_written still passed.

The follow-up:

  • Gates the slot on pnpm's allFilesMatch (inode, then size, then bytes) instead of on each file existing, matching fs/indexed-pkg-importer/src/importIndexedDir.ts. A slot damaged after its import completed is now detected, which existence checks never could.
  • Gives the repair a placement mode that swaps a fresh copy in through a temp sibling for each entry that does not match its store file — atomic under a concurrent reader, and it heals what the gate detects. Matching entries are recognised by their shared store inode, so an intact slot costs two stats per file and no read. The force: false marker-repair path keeps adopting, since it mirrors upstream's repair and a private slot has no second importer.
  • Clears a dirent of the wrong kind. lib as a regular file where the package needs lib/ failed the install with CreateDir ... File exists on this branch; the wipe used to handle it implicitly.
  • Moves the shared-slot branch ahead of the node_modules preservation step. keep_modules_dir is exactly the interrupted-build call shape, so a package with bundled dependencies took !nm_moved into remove_dir_all — the same race, still open. Repairing in place preserves the nested directory by never removing anything.

Strays are deliberately still left alone: removing files the package does not declare is the destructive behavior being retired here, and a completed build's outputs live among them.

One thing for the description, now corrected there: the TypeScript CLI does have safeToSkip, and on a slot that fails allFilesMatch it falls through to renameOverwriteSync, so the destructive swap is still reachable in that stack. Worth a follow-up issue.


Written by an agent (Claude Code, claude-opus-5[1m]).

greptile-apps[bot]
greptile-apps Bot previously approved these changes Aug 11, 2026

@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 (2)
pnpm/crates/deps-restorer/src/import_indexed_dir.rs (1)

406-432: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Repair compares every file twice.

stage_and_swap calls all_files_match first. If it returns false, populate_dir with Placement::Repair calls file_matches_store_entry again for every entry. For the copy tier, each call reads both files in full, so a single mismatched byte in the last entry costs two full reads of the whole package.

Consider dropping the separate all_files_match pre-pass and letting the repair pass decide per entry. The repair pass already skips matching entries, so the fast path stays cheap. The only behavioral difference is that repair also runs create_dir_all and places the marker, which are idempotent.

🤖 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 `@pnpm/crates/deps-restorer/src/import_indexed_dir.rs` around lines 406 - 432,
Remove the separate all_files_match pre-pass from stage_and_swap and let
populate_dir with Placement::Repair perform per-entry matching and replacement.
Preserve the existing fast path for matching entries, while allowing the repair
path’s idempotent directory creation and marker placement to run.
pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs (1)

777-808: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding a concurrent-repair test.

The added tests cover single-importer repair of missing, damaged, and wrong-type entries. The issue this PR fixes is a race between two importers on one slot. A test that spawns two threads calling import_indexed_dir on the same target with FORCE_SHARED would exercise the convergence guarantee directly, and it would fail against the pre-fix remove_dir_all behavior.

REVIEW_GUIDE.md asks for regression tests that fail without the fix and that cover concurrent behavior where relevant.

🤖 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 `@pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs` around lines 777 -
808, Add a regression test alongside
safe_to_skip_repairs_incomplete_target_without_replacing_it that launches two
threads concurrently calling import_indexed_dir on the same target with
FORCE_SHARED, synchronizes their start, and joins both successfully. Verify the
final target converges to the complete expected contents, ensuring the test
fails with the prior remove_dir_all behavior and exercises the concurrent-repair
guarantee.

Source: Path instructions

🤖 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 `@pnpm/crates/deps-restorer/src/import_indexed_dir.rs`:
- Around line 502-535: Update the safe_to_skip branch around the
stage-to-dir_path fs::rename: classify ResourceBusy as an occupied target when
appropriate, but for any other rename failure clean up stage and immediately
return ImportIndexedDirError::Swap. Prevent unclassified rename errors from
falling through to the destructive remove_dir_all(dir_path) path, while
preserving the existing adopt-and-repair behavior for occupied targets.

---

Nitpick comments:
In `@pnpm/crates/deps-restorer/src/import_indexed_dir.rs`:
- Around line 406-432: Remove the separate all_files_match pre-pass from
stage_and_swap and let populate_dir with Placement::Repair perform per-entry
matching and replacement. Preserve the existing fast path for matching entries,
while allowing the repair path’s idempotent directory creation and marker
placement to run.

In `@pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs`:
- Around line 777-808: Add a regression test alongside
safe_to_skip_repairs_incomplete_target_without_replacing_it that launches two
threads concurrently calling import_indexed_dir on the same target with
FORCE_SHARED, synchronizes their start, and joins both successfully. Verify the
final target converges to the complete expected contents, ensuring the test
fails with the prior remove_dir_all behavior and exercises the concurrent-repair
guarantee.
🪄 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: CHILL

Plan: Pro Plus

Run ID: 6a8b592b-d639-4326-85ba-b72c378abbe1

📥 Commits

Reviewing files that changed from the base of the PR and between c87f64d and 5cdc49c.

📒 Files selected for processing (3)
  • .changeset/repair-shared-slot-in-place.md
  • pnpm/crates/deps-restorer/src/import_indexed_dir.rs
  • pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs

@qodo-code-review

qodo-code-review Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Action required

1. Unsafe inode shortcut ✓ Resolved 🐞 Bug ⛨ Security ⭐ New
Description
mismatchReason() treats ino/dev equality as proof the target matches the store file, but on
Windows ino can be unreliable (often 0) and JS number inodes can lose 64-bit precision. This can
incorrectly skip size/content checks and leave a corrupted or tampered file in a shared slot that
later installs will trust.
Code

pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[R353-356]

+    const srcStat = gfs.statSync(src)
+    if (targetStat.ino === srcStat.ino && targetStat.dev === srcStat.dev) return undefined
+    if (targetStat.size !== srcStat.size) return 'has a different size'
+    if (!filesHaveEqualContents(target, src)) return 'has different content'
Relevance

●●● Strong

Team previously accepted guarding ino/dev equality on Windows (zero/precision issues); this matches
that safety pattern.

PR-#12284

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new implementation unconditionally treats ino/dev equality as an identity proof, which is
known to be unsafe on Windows when inode values are unreliable/zero or lose precision; the repo
already contains a safer pattern that guards against this exact pitfall.

pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[349-360]
pnpm11/bins/linker/src/index.ts[378-395]
PR-#12284

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`mismatchReason()` uses `targetStat.ino === srcStat.ino && targetStat.dev === srcStat.dev` as a fast-path match. On Windows (and potentially other platforms with large file IDs), `ino`/`dev` returned as JS `number` can be unreliable (e.g. `ino === 0`) or lossy, causing false “match” and skipping the size+byte comparison.

### Issue Context
This function is used to decide whether shared-slot repair should replace a target entry. A false match means a damaged/incorrect file may be left in place and the directory can still be treated as complete.

### Fix Focus Areas
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[349-360]

### What to change
- Only use the inode/device fast-path when identity is reliable:
 - Prefer `fs.statSync(..., { bigint: true })` / `fs.lstatSync(..., { bigint: true })` (or equivalent) so `ino/dev` are not precision-lost.
 - Require `ino`/`dev` to be non-zero/truthy before considering equality (mirroring the pattern used elsewhere in the repo).
 - Otherwise fall back to size check + `filesHaveEqualContents()`.
- Add/adjust a unit test (can be via mocking `fs.lstatSync` / `gfs.statSync`) to ensure `(ino=0, dev=0)` does **not** short-circuit to “match”.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Parallel full-file reads ✓ Resolved 🐞 Bug ➹ Performance
Description
file_matches_store_entry() loads both target and store files fully into memory via fs::read, and
in Placement::Repair it runs inside populate_dir()’s Rayon par_iter, so multiple large files
may be buffered concurrently and can spike memory/IO (potentially aborting on OOM). This is newly
introduced by the in-place repair logic and affects the shared-slot repair path under
contention/damage scenarios.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[R430-432]

+    target_meta.len() == store_meta.len()
+        && matches!((fs::read(target), fs::read(store_path)), (Ok(target), Ok(store)) if target == store)
+}
Relevance

●● Moderate

Perf concern is plausible but change is non-trivial and no close historical accept/reject precedent
found.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
populate_dir() runs per-entry work in parallel (par_iter) and, in Placement::Repair, each
entry may call file_matches_store_entry() which performs full-buffer reads of both files. This
combination directly creates concurrent large allocations and extra IO in the repair path.

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[267-283]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[314-326]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[419-432]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`file_matches_store_entry()` currently uses `fs::read()` on both files, which allocates full file buffers and, when called concurrently from Rayon in `Placement::Repair`, can create large transient memory spikes and heavy IO.

### Issue Context
Repair mode is invoked for shared-slot occupied targets (`safe_to_skip`) and for in-place repairs, and it is executed via Rayon parallelism across many entries.

### Fix Focus Areas
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[267-344]
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[419-432]

### Suggested fix
- Replace the `fs::read` byte-equality check with a bounded-memory streaming comparison (e.g., `std::fs::File` + `BufReader` reading fixed-size chunks and comparing incrementally).
- Keep the existing inode fast-path on Unix (`is_same_file`) but make the fallback comparison bounded-memory on all platforms.
- (Optional) If the intention is primarily “heal if damaged”, consider skipping byte-compare in `Placement::Repair` for the copy tier and always `import_atomic` (bounded extra writes) to avoid any read-amplification; otherwise keep streaming compare.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

3. Flaky child cleanup gate ✓ Resolved 🐞 Bug ☼ Reliability
Description
The concurrent test only writes the release file when writer.kill() returns false, but kill()
returning true only confirms signal delivery, not that the child has exited. If termination is
delayed for any reason, the child can remain blocked waiting for releaseFile and the test can hang
until Jest times out.
Code

pnpm11/fs/indexed-pkg-importer/test/importIndexedDir.concurrent.test.ts[R38-41]

+  } finally {
+    if (!writer.kill()) fs.writeFileSync(releaseFile, '')
+    await writerExit
+  }
Relevance

●●● Strong

Team often accepts hardening child-process test cleanup to avoid hangs/races (exit vs close, added
deadlines).

PR-#12925
PR-#11530
PR-#12786

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The parent test conditionally creates releaseFile based on kill()’s return, but the child is
explicitly blocked waiting for that file; if it stays alive, await writerExit can stall until
timeouts.

pnpm11/fs/indexed-pkg-importer/test/importIndexedDir.concurrent.test.ts[28-41]
pnpm11/fs/indexed-pkg-importer/test/fixtures/concurrentSharedSlotImport.mjs[14-20]
pnpm11/fs/indexed-pkg-importer/test/fixtures/concurrentSharedSlotImport.mjs[43-49]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The test’s `finally` block uses `if (!writer.kill()) fs.writeFileSync(releaseFile, '')` as the only barrier release. `ChildProcess.kill()` returning `true` only means the signal was sent, not that the subprocess has exited, so cleanup can block on `await writerExit` longer than intended.

### Issue Context
The fixture subprocess blocks inside `waitForFile(releaseFile)` until `releaseFile` exists, so the parent test should always ensure the file is created during cleanup regardless of whether a signal was successfully sent.

### Fix Focus Areas
- pnpm11/fs/indexed-pkg-importer/test/importIndexedDir.concurrent.test.ts[38-41]

### Suggested change
- In the `finally` block, write `releaseFile` unconditionally (best-effort), then `await writerExit`.
- Optionally still call `writer.kill()` (or escalate to SIGKILL after a short grace period) if you want to guarantee prompt termination, but don’t rely on `kill()`’s boolean return to decide whether the barrier is released.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Whole-file reads in repair ✓ Resolved 🐞 Bug ➹ Performance
Description
The TS importer’s mismatchReason() compares content by reading both files fully with
gfs.readFileSync(); in shared-slot repair this can run per entry, causing large memory/IO spikes
on big binaries and also following symlinks/special files (stat/read) which may block. This is a new
hot-path cost for safeToSkip repairs and can regress install performance under contention/damage
scenarios.
Code

pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[R303-307]

+function fileMatches (dir: string, f: string, src: string): boolean {
+  const reason = mismatchReason(path.join(dir, f), src)
+  if (reason === undefined) return true
+  globalInfo(`Re-importing "${dir}" because file "${f}" ${reason}`)
+  return false
Relevance

●●● Strong

Team has accepted replacing whole-file reads with chunked/streaming comparisons to avoid memory/IO
spikes in hot paths.

PR-#12284

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
fileMatches() calls mismatchReason(), which reads the entire file contents for both target and
store source. The new shared-slot repair path (repairIndexedDir / replaceFileIfDifferent)
invokes this per entry, making whole-file reads part of the repair hot path.

pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[151-182]
pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[303-324]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`mismatchReason()` uses `readFileSync()` on both target and source to detect content differences. During shared-slot repair (`repairIndexedDir` → `replaceFileIfDifferent`), this can execute many times and loads entire files into memory (twice) per comparison.

### Issue Context
This logic is now used both by `allFilesMatch()` and by the new shared-slot repair loop, so repair scenarios can amplify the memory and I/O cost.

### Fix Focus Areas
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[151-182]
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[303-324]

### Implementation notes
- Replace `readFileSync(...).equals(...)` with a streaming/chunked compare (8–64KB buffers) to cap memory.
- Prefer `lstatSync` and reject symlinks/non-regular files early (treat as mismatch) to avoid blocking on special files.
- Keep the existing inode/dev fast-path when available, then size check, then streamed byte-compare.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Retry ignores convergence 🐞 Bug ➹ Performance
Description
TypeScript renameFileWithRetry() can sleep/retry for up to 60s without checking whether another
concurrent repair already made dest match src, so shared-slot repairs may waste up to the full
retry budget even after the directory is already correct.
Code

pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[R204-207]

+    } catch (err) {
+      if (!isTransientRenameError(err) || Date.now() - startedAt >= RENAME_RETRY_BUDGET_MS) throw err
+      if (backoffMs > 0) Atomics.wait(renameRetrySleepBuffer, 0, 0, backoffMs)
+      backoffMs = Math.min(backoffMs + 10, RENAME_RETRY_BACKOFF_CAP_MS)
Relevance

●● Moderate

Early convergence check in retry loop is plausible, but no matching precedent; team previously
rejected related perf short-circuits.

PR-#13648
PR-#12204

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The retry budget and backoff are hard-coded (60s total), and the retry loop doesn’t consult
mismatchReason()/content equality during retries; the only post-failure match check happens after
the retry loop exits via throw, which means convergence by another importer won’t be detected
promptly.

pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[15-18]
pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[169-209]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`renameFileWithRetry()` retries transient Windows rename errors (EPERM/EACCES/EBUSY) for up to 60 seconds, but it doesn’t check whether the destination has already converged to the intended content (e.g., another importer won the race and published the correct file). This can introduce large, avoidable stalls in the exact concurrent-import scenario this PR targets.

## Issue Context
`replaceFileIfDifferent()` only calls `mismatchReason(dest, src)` again *after* `renameFileWithRetry()` throws, so it cannot short-circuit early during the retry window.

## Fix Focus Areas
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[16-18]
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[172-209]

## Suggested fix
Inside the `catch` block of `renameFileWithRetry()` (before sleeping):
- Best-effort check if `dest` already matches `src` (note: `src` here is the temp sibling, so comparison is valid).
 - e.g. `if (mismatchReason(dest, src) === undefined) return` (or a lighter-weight stat/inode check, falling back to content compare only when needed).
- If it matches, return successfully so the caller can clean up the temp file.

This preserves the safety property of not deleting the destination while eliminating unnecessary waiting once the content is already correct.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View review recommended (9)
6. Blocking rename retries 🐞 Bug ➹ Performance
Description
Rust shared-slot repairs now publish each replaced entry via a retrying rename; on Windows this can
block Rayon workers for up to ~60s per entry under persistent file locks, making installs appear
hung and potentially starving the worker pool.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[R576-578]

+    match pacquet_fs::rename_with_retry(&temp, target) {
        Ok(()) => Ok(()),
-        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
+        Err(_) if file_matches_store_entry(target, store_path) => {
Relevance

●● Moderate

Perf/concurrency tradeoff; similar import-path performance tweaks were rejected previously, unclear
they’ll change retry design now.

PR-#13648

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
populate_dir() runs entry placement in a Rayon par_iter(), and place_entry()/place_marker()
can call import_atomic(). import_atomic() uses pacquet_fs::rename_with_retry(), whose
implementation retries with sleep backoff for up to a 60s budget on transient Windows rename
failures; this directly ties long blocking sleeps to Rayon workers.

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[338-353]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[555-586]
pnpm/crates/fs/src/ensure_file.rs[441-487]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`import_atomic()` uses `pacquet_fs::rename_with_retry()` during in-place repair. On Windows this helper can sleep/retry for up to a minute while holding a Rayon worker. Under concurrency + AV/indexer locks this can make installs look stuck and can starve the Rayon pool.

## Issue Context
This is on the repair path (`Placement::Repair`) which is explicitly meant to handle concurrent importers. In that scenario, another importer can win the race and publish the correct destination while this thread is still in the retry loop.

## Fix Focus Areas
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[555-586]
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[338-353]
- pnpm/crates/fs/src/ensure_file.rs[441-487]

## Suggested fix
Add an early-convergence escape during retries so we don’t spend the full retry budget once the destination already matches:
- Option A (localized): replace the single call to `rename_with_retry()` in `import_atomic()` with a small retry loop that:
 - retries only transient Windows errors,
 - before each sleep (or after a failed rename), checks `file_matches_store_entry(target, store_path)`, and if it matches, removes `temp` and returns `Ok(())`.
- Option B (library): extend `rename_with_retry()` to accept a callback/predicate that can stop the retry loop when the destination is already in the desired state (so `deps-restorer` can pass the file-match check without `pnpm/crates/fs` learning about store semantics).

Either option preserves the safety property (“don’t delete the destination”) while reducing worst-case wall-clock stalls in the concurrent-repair case.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Test comment uses “used to” ⊘ Outdated 📘 Rule violation ⚙ Maintainability
Description
Newly added test-related comments use historical phrasing like used to be instead of describing
the current behavior/contract being asserted. This can become stale over time and mislead readers
about the present intent or invariant.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs[R816-819]

+// The classifier decides whether a failed swap adopts the target or gives up on it, and giving
+// up is the only safe answer for an error that says nothing about the target: the alternative
+// used to be a fall-through to `remove_dir_all`, which deletes a slot another importer holds.
+// A Windows sharing violation arrives as `ResourceBusy` and would have taken exactly that path.
Relevance

●● Moderate

Repo enforces present-tense comments, but similar “remove historical phrasing” nits have mixed
accept/reject precedents.

PR-#13669
PR-#13662

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The rule/checklist requires avoiding historical references in comments (e.g., used to). In the
cited additions, the comment explicitly says used to be a fall-through to remove_dir_all, which is
historical phrasing rather than a present-tense description of the current behavior, so it violates
the requirement and risks becoming outdated.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs[816-819]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[631-634]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A newly added comment uses historical phrasing (`used to be ...`) rather than documenting the current behavior/contract/invariant being asserted. Rewrite it to describe the present behavior and intent so it doesn’t become stale or misleading.

## Issue Context
Comments (including in tests) should explain the current scenario, behavior, and rationale; historical implementation notes like “used to” belong in PR/commit history rather than inline source comments.

## Fix Focus Areas
- pnpm/crates/deps-restorer/src/import_indexed_dir/tests.rs[816-819]
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[631-634]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


8. linkAdoptingExisting declared before use ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new top-level function linkAdoptingExisting() is declared before its first usage in the same
file. This violates the rule requiring TypeScript function declarations to appear after their first
usage.
Code

pnpm11/fs/indexed-pkg-importer/test/importIndexedDir.test.ts[R12-15]

+function linkAdoptingExisting (src: string, dest: string): void {
+  try {
+    fs.linkSync(src, dest)
+  } catch (err: unknown) {
Relevance

●● Moderate

Ordering rule is sometimes enforced (accepted), but also sometimes rejected in tests/other files.

PR-#12789
PR-#12872

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713432 requires top-level TypeScript function declarations to be declared after at
least one usage in the same file. The new test file declares linkAdoptingExisting() and only uses
it later when constructing linkingImporter.

Rule 713432: Declare TypeScript functions only after their first usage
pnpm11/fs/indexed-pkg-importer/test/importIndexedDir.test.ts[10-21]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A new top-level TypeScript function declaration appears before its first usage in the file, which violates the project rule.

## Issue Context
`linkAdoptingExisting()` is declared before it is used to build `linkingImporter`.

## Fix Focus Areas
- pnpm11/fs/indexed-pkg-importer/test/importIndexedDir.test.ts[10-21]

## Suggested fix
Either:
- Convert `linkAdoptingExisting` to a `const` arrow/function expression (rule scope excludes these), or
- Move the `function linkAdoptingExisting(...) { ... }` block below the first usage (relying on hoisting).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


9. retryWithFixedFileMap has 5 params ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
New TypeScript functions (e.g. retryWithFixedFileMap, importIntoSharedDir) take more than three
parameters. This violates the rule limiting TypeScript function parameter counts, increasing
call-site complexity and churn.
Code

pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[R223-226]

+function retryWithFixedFileMap (
+  err: unknown,
+  importer: Importer,
+  newDir: string,
Relevance

●● Moderate

Mixed precedent: max-3-params refactors sometimes accepted, sometimes rejected depending on
churn/benefit.

PR-#13133
PR-#13792

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713433 restricts TypeScript functions to three parameters or fewer unless using an
options object. The added signatures show 4+ positional parameters in new functions.

Rule 713433: Limit TypeScript functions to three parameters or fewer
pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[107-112]
pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[223-229]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
New/modified TypeScript functions exceed the 3-parameter limit.

## Issue Context
The rule requires at most three parameters, otherwise prefer a single options/config object.

## Fix Focus Areas
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[107-112]
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[223-229]

## Suggested fix
Refactor signatures to accept a single options object, e.g.:
- `retryWithFixedFileMap({ err, importer, newDir, filenames, opts })`
- `importIntoSharedDir({ importer, newDir, filenames, opts })`
Then update all call sites accordingly.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


10. Duplicate file comparisons ✓ Resolved 🐞 Bug ➹ Performance
Description
In importIntoSharedDir(), the code runs allFilesMatch() and, when it returns false, immediately runs
repairIndexedDir(), which re-checks each entry via mismatchReason() again. In worst cases (e.g., the
first mismatch is late in the file map, or the completion marker is encountered late), this repeats
many stats and sometimes full-file reads, slowing shared-store installs under contention.
Code

pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[R132-135]

+  if (allFilesMatch(newDir, filenames)) return
  try {
-    renameOverwriteSync(stage, newDir)
-  } catch (renameErr: unknown) {
+    repairIndexedDir(importer, newDir, filenames)
+  } catch (err: unknown) {
Relevance

●● Moderate

Perf concern is plausible but requires behavior/context tradeoff; no close prior
acceptance/rejection found.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new shared-dir path always calls allFilesMatch() before repair, and both allFilesMatch() and
replaceFileIfDifferent() call mismatchReason(), which may read entire files in the copy tier.
This establishes the redundant IO/comparison work introduced by the new control flow.

pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[107-138]
pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[145-180]
pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[293-318]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`importIntoSharedDir()` currently does a full preflight `allFilesMatch()` pass and then (on mismatch) does a repair pass that re-checks each file again via `mismatchReason()`. This can duplicate `statSync` work and (for copy-tier files with equal size) `readFileSync` byte comparisons.

### Issue Context
This path is triggered for `safeToSkip` targets (shared content-addressed dirs). Under common races (slot exists but marker is not written yet) and large packages, duplicated checks can add noticeable IO.

### Fix Focus Areas
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[132-138]
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[293-318]
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[145-180]

### Suggested fix directions
- Add a cheap early short-circuit before `allFilesMatch()` (e.g., if `filenames` includes `package.json`, `statSync`/`existsSync` that first and skip expensive checks when it’s missing).
- Consider removing the preflight `allFilesMatch()` in the shared-dir path and instead run `repairIndexedDir()` directly (it already does per-entry comparisons and only replaces when mismatching), optionally tracking whether any replacement happened.
- Alternatively, compute mismatches once and reuse the results during repair so `mismatchReason()` isn’t re-run for entries already checked.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


11. repair-shared-slot missing pnpm entry ✓ Resolved 📘 Rule violation § Compliance
Description
The new changeset lists only pacquet and omits pnpm, which violates the requirement that
changesets explicitly include the pnpm package entry. This can cause the release tooling to miss
or misclassify the pnpm bump for this change.
Code

.changeset/repair-shared-slot-in-place.md[R1-3]

+---
+"pacquet": patch
+---
Relevance

●● Moderate

Mixed precedent: some PRs added required pnpm entry, others explicitly rejected the same request.

PR-#13748
PR-#13549

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires each new/modified changeset to include an explicit pnpm package
entry with a valid bump type. The added changeset front-matter includes only pacquet and therefore
fails this requirement.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/repair-shared-slot-in-place.md[1-3]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new changeset file does not include a `pnpm` entry, but the compliance rules require changesets to explicitly declare `pnpm` with a valid bump type.

## Issue Context
File `.changeset/repair-shared-slot-in-place.md` currently declares only `"pacquet": patch`.

## Fix Focus Areas
- .changeset/repair-shared-slot-in-place.md[1-3]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


12. is_same_file reimplements same-file ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The PR adds a custom is_same_file implementation for inode equality, despite the workspace already
depending on the well-maintained same-file crate. This duplicates existing OSS functionality and
increases long-term maintenance burden.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[R437-440]

+fn is_same_file(left: &fs::Metadata, right: &fs::Metadata) -> bool {
+    use std::os::unix::fs::MetadataExt;
+    left.ino() == right.ino() && left.dev() == right.dev()
+}
Relevance

●● Moderate

Switching to same-file is a design/dependency choice; no close team precedent found in this area.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713437 requires avoiding custom reimplementations when a well-maintained OSS
dependency already exists. This PR adds a bespoke is_same_file function, while the workspace
already includes same-file as a dependency, indicating the functionality is already available.

Rule 713437: Avoid reimplementing functionality provided by well-maintained open source packages
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[434-445]
Cargo.toml[164-164]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A custom `is_same_file` helper was added, but the repo already depends on the `same-file` crate which provides this functionality.

## Issue Context
The new helper compares `(dev, ino)` on Unix and always returns `false` on non-Unix, which is a partial reimplementation of `same_file::is_same_file`.

## Fix Focus Areas
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[434-445]
- Cargo.toml[164-164]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


13. Marker check not first ✓ Resolved 🐞 Bug ➹ Performance
Description
In the occupied shared-slot branch, the code calls all_files_match() directly; because cas_paths
is a HashMap, iteration order is arbitrary, so a marker-missing (mid-import) slot can still
trigger expensive comparisons (and even file reads) before the missing marker is encountered. This
regresses the prior cheap marker_present() short-circuit for the common “slot exists but marker
not written yet” race case.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[R520-523]

+                let _ = fs::remove_dir_all(&stage);
+                return if all_files_match(dir_path, cas_paths) {
+                    Ok(())
+                } else {
Relevance

●● Moderate

Ordering/short-circuit optimization is subjective and context-dependent; no close historical
precedent found.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The occupied-target path now consults all_files_match() directly, and all_files_match() iterates
a HashMap of entries and calls file_matches_store_entry() per entry, so the missing-marker case
isn’t guaranteed to short-circuit early.

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[509-535]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[406-417]
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[419-432]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
On `safe_to_skip` + occupied target, the code calls `all_files_match()` without first checking the completion marker. Because `cas_paths` is a `HashMap`, the marker entry is not guaranteed to be checked early, so a marker-missing directory can still incur avoidable work.

### Issue Context
This branch is specifically for shared-slot contention; the common contention case described in the PR is “directory exists, marker not yet present”. In that case, the fastest safe decision is to go straight to repair without scanning/reading other files.

### Fix Focus Areas
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[509-535]
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[406-417]

### Suggested fix
- In the `is_occupied_target` branch, first check `marker_present(dir_path, cas_paths)`.
 - If `false`, skip `all_files_match` and go directly to `populate_dir(..., Placement::Repair)`.
 - If `true`, then run `all_files_match` to detect post-import corruption.
- Alternatively, modify `all_files_match` to explicitly check the marker file first (using `marker_file(cas_paths)`) before iterating the rest.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


14. Ported from historical comment 📘 Rule violation ⚙ Maintainability
Description
A newly added comment includes historical/temporal implementation details (Ported from ... with a
commit hash), rather than documenting the current behavior and rationale in present terms. This
risks becoming stale and violates the no-historical-implementations-in-comments rule.
Code

pnpm/crates/deps-restorer/src/import_indexed_dir.rs[R175-178]

+        // `populate_dir`. Ported from pnpm/pnpm#12204 (cbfeeef328), whose
+        // repair adopts an existing dirent rather than replacing it —
+        // pnpm's own fast path does, and a private slot has no second
+        // importer racing this one.
Relevance

●● Moderate

Repo often dislikes historical phrasing, but there are recent rejections of similar “historical”
comment rewrites too.

PR-#13669
PR-#13662

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 772199 forbids comments that describe historical implementations using phrasing
like "Ported from" and references to removed/previous code. The comment at the cited lines
explicitly references a prior PR/commit hash instead of documenting the current behavior contract.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm/crates/deps-restorer/src/import_indexed_dir.rs[171-178]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The added comment references historical implementation context ("Ported from ..." with a commit hash) instead of describing the current behavior.

## Issue Context
Inline source comments should describe current invariants/behavior; historical provenance belongs in PR/commit history.

## Fix Focus Areas
- pnpm/crates/deps-restorer/src/import_indexed_dir.rs[171-178]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

15. Missing trailing commas in params ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
Several newly added multi-line TypeScript parameter lists omit the trailing comma on the last
parameter. This violates the trailing-comma requirement and will cause noisier diffs when parameters
change.
Code

pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[R109-112]

+  newDir: string,
+  filenames: Map<string, string>,
+  opts: ImportIndexedDirOptions
+): void {
Relevance

● Weak

Trailing-comma suggestions for multi-line TS params are often explicitly rejected despite the rule.

PR-#13804

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713434 requires trailing commas for multi-line TypeScript parameter lists. The new
function signatures span multiple lines and the last parameter line is not terminated with a comma.

Rule 713434: Require trailing commas in TypeScript collections and multi-line constructs
pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[107-112]
pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[223-229]
pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[379-396]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Multi-line TypeScript function parameter lists added in this PR are missing trailing commas on the last parameter.

## Issue Context
The repository requires trailing commas in multi-line constructs for TS/TSX.

## Fix Focus Areas
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[107-112]
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[223-229]
- pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts[379-396]

## Suggested fix
Add a trailing comma after the last parameter in each affected multi-line signature (and any similar multi-line argument lists introduced nearby).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context
✅ Compliance rules (platform): 26 rules

Grey Divider

Tip of the day
💡 Did you know, you can group findings by type and pick your Finding display, from Minimal to Full

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

Port the pacquet fix to the TypeScript CLI, whose importIndexedDir has the
same safeToSkip mode and the same two problems with it.

A slot that fails allFilesMatch fell through to renameOverwriteSync, which
removes the directory a concurrent importer may still be writing into and
that a third may be reading from. And the fast path that writes into a
shared slot in place adopts whatever dirent is already there, because the
linking tiers report EEXIST for it, so a file truncated by an interrupted
copy survived the import and the completion marker went down on top of it.

A shared slot is now populated by whoever wins an exclusive mkdir, adopted
by everyone else when it already matches, and otherwise repaired entry by
entry: each file that does not match its store entry is swapped in through
a temp sibling, which replaces it atomically under a reader. Nothing on
this path unlinks, so concurrent importers converge, a nested node_modules
survives without the staging dance keepModulesDir used to need, and files
the package does not declare are left to whoever put them there.

Restrict safeToSkip to targets whose path pins their contents, which is
what the flag has always required of its callers. A local directory is
copied into the target at install time and can change with no lockfile
change, so its stale files still have to be cleared by a rebuild — pacquet
excludes those from the mode for the same reason.
@greptile-apps
greptile-apps Bot dismissed their stale review August 11, 2026 12:49

Dismissed because a newer commit was pushed; Greptile will re-review the current head.

@zkochan

zkochan commented Aug 11, 2026

Copy link
Copy Markdown
Member

Ported to the TypeScript CLI in ba80772 (+ b193e38 for naming), so the fix lands in both stacks.

importIndexedDir there does have safeToSkip — my earlier note about the description was right — and it had both halves of the bug:

  • A slot that fails allFilesMatch fell through to renameOverwriteSync, which removes the directory a concurrent importer is still writing into and a third may be reading from. That is the ENOTEMPTY race, in the other stack.
  • The fast path that writes into a shared slot in place adopts whatever dirent is there, because linkOrCopy and the clone function both swallow EEXIST — so a file truncated by an interrupted copy survived, and tryImportIndexedDir then put package.json on top of it.

Now: whoever wins an exclusive mkdir writes the package; everyone else adopts the directory when allFilesMatch and otherwise repairs it entry by entry, each mismatching file placed through a temp sibling and renamed over. Nothing on that path unlinks, so concurrent importers converge and a nested node_modules/ survives without the staging dance keepModulesDir needed. The EEXIST case-conflict and ENOENT invalid-filename recoveries are shared with the staging path rather than duplicated.

One thing the port turned up. safeToSkip requires that the target path pin its contents, but link.ts and installing/deps-restorer pass enableGlobalVirtualStore straight through, so an injected local package was reaching the mode as well. That was survivable while the fall-through rebuilt the directory; with a non-destructive repair it would leave files deleted from the source behind forever. resolvedFrom: 'local-dir' now takes the staging path, which is the same exclusion pacquet makes with source_is_mutable.

Verified locally: the package's own suite (29 tests, 6 new), plus test/install/globalVirtualStore.ts (21), injectLocalPackages.ts and packageImportMethods.ts (18) in @pnpm/installing.deps-installer, and a full pnpm run compile-only. Each new test was checked against a deliberately broken implementation — adopting instead of replacing, skipping the blocking-dirent clear, dropping the local-dir exclusion — and each break failed exactly the test that covers it and nothing else.

Worth a look from someone who knows the injected-local-dependency paths better than I do: that is the one behavior change beyond the shared-slot fix.


Written by an agent (Claude Code, claude-opus-5[1m]).

@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.

🧹 Nitpick comments (2)
pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts (1)

145-162: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document why the repair path uses importFile for package.json.

The Importer doc comment on Lines 21-25 states that package.json must be written through importFileAtomic. repairIndexedDir passes importer.importFile instead. The write is still atomic because replaceFileIfDifferent renames a temp sibling over the destination. That reasoning is not obvious to a reader who follows the Importer contract. Add a short comment that records the invariant.

📝 Proposed comment
   if (packageJsonSrc !== undefined) {
+    // The rename in replaceFileIfDifferent is atomic on its own, so the
+    // completion marker does not need importFileAtomic here.
     replaceFileIfDifferent(importer.importFile, packageJsonSrc, path.join(newDir, 'package.json'))
   }
🤖 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 `@pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts` around lines 145 -
162, Add a concise comment immediately before the package.json
replaceFileIfDifferent call in repairIndexedDir explaining that although the
Importer contract normally requires importFileAtomic, replaceFileIfDifferent
writes via a temporary sibling and atomic rename, preserving atomic package.json
replacement when using importer.importFile.

Source: Coding guidelines

pnpm11/fs/indexed-pkg-importer/test/importIndexedDir.test.ts (1)

63-83: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert that the matching package.json is not replaced.

This test proves the corrupted file is repaired. It does not prove the matching entry is left untouched. The inode check in mismatchReason is the mechanism that makes a shared slot converge without churn, and no TypeScript test covers it. Capture the destination inode before the import and assert it after.

🧪 Proposed assertion
   const filenames = new Map([
     ['index.js', path.join(src, 'index.js')],
     ['package.json', path.join(src, 'package.json')],
   ])
+  const packageJsonInoBefore = fs.statSync(path.join(newDir, 'package.json')).ino
   importIndexedDir(linkingImporter, newDir, filenames, { safeToSkip: true })
 
   expect(fs.readFileSync(path.join(newDir, 'index.js'), 'utf8')).toBe('module.exports = 1')
+  // A matching entry is adopted, not swapped out from under a concurrent reader.
+  expect(fs.statSync(path.join(newDir, 'package.json')).ino).toBe(packageJsonInoBefore)
 })

Note that the destination package.json here has identical content but a different inode from the source, so mismatchReason falls through to the content comparison and returns undefined. The assertion therefore verifies the content path, not the inode fast path. If you want to cover the inode fast path, hardlink the source into the destination instead of writing a copy.

🤖 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 `@pnpm11/fs/indexed-pkg-importer/test/importIndexedDir.test.ts` around lines 63
- 83, Update the importIndexedDir() safeToSkip test to record the destination
package.json inode before importing, then assert it remains unchanged afterward
while retaining the existing index.js repair assertion. Use the existing
destination package.json setup so the assertion verifies matching-content
entries are not replaced.

Source: Path instructions

🤖 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.

Nitpick comments:
In `@pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts`:
- Around line 145-162: Add a concise comment immediately before the package.json
replaceFileIfDifferent call in repairIndexedDir explaining that although the
Importer contract normally requires importFileAtomic, replaceFileIfDifferent
writes via a temporary sibling and atomic rename, preserving atomic package.json
replacement when using importer.importFile.

In `@pnpm11/fs/indexed-pkg-importer/test/importIndexedDir.test.ts`:
- Around line 63-83: Update the importIndexedDir() safeToSkip test to record the
destination package.json inode before importing, then assert it remains
unchanged afterward while retaining the existing index.js repair assertion. Use
the existing destination package.json setup so the assertion verifies
matching-content entries are not replaced.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 9b8db4f7-3877-42e8-b4a0-fad5f33b55d8

📥 Commits

Reviewing files that changed from the base of the PR and between 5cdc49c and b193e38.

📒 Files selected for processing (5)
  • .changeset/repair-shared-slot-in-place.md
  • pnpm/crates/deps-restorer/src/import_indexed_dir.rs
  • pnpm11/fs/indexed-pkg-importer/src/importIndexedDir.ts
  • pnpm11/fs/indexed-pkg-importer/test/importIndexedDir.test.ts
  • pnpm11/store/controller-types/src/index.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • .changeset/repair-shared-slot-in-place.md
  • pnpm/crates/deps-restorer/src/import_indexed_dir.rs

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit b193e38

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

greptile-apps[bot]
greptile-apps Bot previously approved these changes Aug 11, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13810
Testbedpnpr

⚠️ WARNING: No Threshold found!

Without a Threshold, no Alerts will ever be generated.

Click here to create a new Threshold
For more information, see the Threshold documentation.
To only post results if a Threshold exists, set the --ci-only-thresholds flag.

Click to view all benchmark results
BenchmarkLatencymilliseconds (ms)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,526.79 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
286.32 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
306.47 ms
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
⚠️ NO THRESHOLD
85.24 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,376.49 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
3,444.04 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
274.67 ms
🐰 View full continuous benchmarking report in Bencher

@zkochan
zkochan merged commit e9a3ca3 into pnpm:main Aug 11, 2026
39 of 40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Concurrent importers of one virtual-store slot can fail with ENOTEMPTY

3 participants