Skip to content

perf(resolving-deps-resolver): sync the discovery view from a write log - #13571

Merged
zkochan merged 7 commits into
mainfrom
amortize-initial-rounds
Aug 1, 2026
Merged

zkochan merged 7 commits into
mainfrom
amortize-initial-rounds

Conversation

@zkochan

@zkochan zkochan commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

Summary

Fourth installment on the peer-phase performance work in
pnpm/tasks#16 (after #13506, #13545
and #13568), taking the issue's item 2 — amortizing the initial hoist
rounds. Related to pnpm/tasks#16; the issue stays open.

The peer-hoist discovery engine keeps one view of the workspace context across
every hoist round and refreshes it before each pass. That refresh walked all
three shared maps end to end (children_by_id, packages,
dependencies_tree), so every round cost one scan of the whole workspace
even when the round had added a handful of nodes — and every extend_tree
bumps the revision that triggers a refresh.

This PR has the context record which keys each write touched, and syncs by
visiting the keys written since the view's cursor.

The design point that makes it safe: only keys are recorded, never values.
The sync reads each key's current value, so a key written several times, or
written by concurrently-walking importers in either order, converges on the
same view. A view discarded after an unmergeable change refills itself by
scanning the shared maps once. The merge logic itself is untouched, so an unmergeable
change — a children-owner handover that re-split a package's children and
peers — still reports the view stale and the engine still rebuilds it.

Measurements, and what each one is worth

In-repo workspace_full_resolution, new hoist-heavy scenario — the load-bearing
number. Two binaries built from this branch and from main with an identical
benchmark file, run interleaved on an idle machine:

run 1 run 2 run 3
main 7.68 s 7.32 s 7.31 s
this PR 7.33 s 6.78 s 6.67 s

Every pair favours the branch; ~7% off the whole resolve (the first branch run is
a warm-up).

Phase timers on the 114-project Bit workspace (resolution-only replay, warm
cache, offline: true, input lockfile restored before each run; same
instrumentation on both sides):

main this PR
sync time, initial rounds (172 syncs) 683 ms 215 ms
sync time, hoist loop (7 syncs) 30 ms 0.3 ms
"complete initial rounds" phase 3.78 s 2.79 s
"hoist loop" phase 1.28 s 1.03 s

The 215 ms that remain are the three view rebuilds a children rewrite forces.

What does not demonstrate this change, stated plainly:

  • The existing peer-heavy scenario of the same benchmark. main and this branch
    measure identically on it (~850 ms either way, 6 interleaved runs). It hands
    every importer all the framework packages up front, so no peer is ever missing,
    the auto-install-peers loop converges in one round, and the context is synced
    once — the cost this PR removes is never incurred. That gap is why this PR adds
    the hoist-heavy scenario.
  • The CI integrated benchmark. Its peer-heavy scenario is an end-to-end install
    whose run-to-run spread (±0.4 s on a ~1.7 s mean) is larger than the effect, and
    it is the same fixture shape as above, so it would not show this even if it were
    quiet.
  • End-to-end replay wall time. 13.55/13.59/14.57 s on main vs 12.87/13.45/14.52 s
    here: the ranges overlap. Best-of-3 differs by ~0.7 s, consistent with the phase
    timers, but three samples at that spread prove nothing on their own.

What is left in the initial rounds, measured

With the sync fixed, the remaining cost of those phases is walking, and it is
concentrated in one place. Counting discovery walks by why they ran:

walk kind count time
first walk of an importer's forest (prepare phase) 114 1.06 s
full re-walk forced by a children rewrite 95 + 31 2.87 s + 0.96 s
incremental (only the directs a hoist added) 55 + 85 0.26 s + 0.10 s

A children-ownership handover flips other occurrences of the package to lazy
children, which bumps children_rewrites; every importer whose next round sees
a changed counter re-walks its entire direct forest, and the discovery engine
discards its whole cache. Three rewrites in the initial rounds cost ~3.8 s of
re-walking. Two ways to attack that, both needing a decision I did not want to
take unilaterally:

  1. Scope the invalidation to the rewritten package. make_non_owner_nodes_lazy
    already holds each rewritten node's ancestor pkgIdWithPatchHash chain, so the
    set of packages whose cached verdict can be affected is computable. The catch:
    find_hit takes the first compatible item in a bucket, so retaining
    unaffected buckets can change which item wins where a full discard would have
    recomputed one — the same class of risk that made the rewrite gating in
    perf(resolver): cut large-workspace peer resolution roughly in half #13506 shift bindings.
  2. Skip the full re-walk for importers that cannot reach the rewritten package.
    Sound (false positives only cost time) but needs a per-importer fingerprint of
    the packages its walk visited, which is memory the engine does not spend today —
    relevant while @pnpm/napi: install of a large graph peaks at >30 GB RSS (per-occurrence tree expansion in peer resolution + hoisted linking) #13540 is reducing peak RSS.

Squash Commit Body

The peer-hoist discovery engine keeps one view of the workspace context
across every hoist round, refreshing it before each pass. That refresh
walked all three shared maps end to end — `children_by_id`, `packages`,
`dependencies_tree` — so every round cost one scan of the whole
workspace even when the round had added a handful of nodes. A resolve of
the 114-project Bit workspace from
https://github.com/pnpm/tasks/issues/16 runs 172 of those syncs in the
initial rounds alone, and each `extend_tree` bumps the revision that
triggers them.

Have the context record which keys of those maps each write touched, and
sync by visiting the keys written since the view's cursor. Only keys are
recorded, never values: the sync reads each key's current value, so a key
written several times, or written by concurrently-walking importers in
either order, converges on the same view. A view discarded after an
unmergeable change (a children-owner handover that re-split a package's
children and peers) refills itself by scanning the shared maps once,
rather than replaying the log, which would copy every key twice.

Neither existing scenario of the `workspace_full_resolution` benchmark
runs the auto-install-peers loop — the peer-heavy one provides every
importer's peers up front, so it converges in one round with a single
sync and measures identically here — so add a hoist-heavy scenario where
the peers are missing and the importers' direct sets differ. That
scenario runs 7.68/7.32/7.31s on main against 7.33/6.78/6.67s here.

On that workspace the initial rounds' sync time drops from 683ms to
215ms — the remainder is the three rebuilds, which replay the log — and
the hoist loop's from 30ms to 0.3ms, taking the two phases from 3.78s +
1.28s to 2.79s + 1.03s.

Related to https://github.com/pnpm/tasks/issues/16.

Checklist

  • I checked the referenced issue and verified that none of the PRs
    already linked to it solves it.
  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • 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.

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

Summary by CodeRabbit

  • Performance

    • Improved peer resolution performance in large workspaces by processing only newly discovered dependency information during hoisting.
    • Resolved dependency output remains unchanged.
  • Bug Fixes

    • Improved synchronization of dependency, package, child-edge, and peer-dependency updates across resolution rounds.
    • Improved recovery when incremental synchronization cannot be applied.
  • Tests

    • Added coverage for incremental synchronization, depth changes, package and peer tracking, and peer-dependency split scenarios.

Copilot AI review requested due to automatic review settings August 1, 2026 18:48
@coderabbitai

coderabbitai Bot commented Aug 1, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c271de2d-592a-4c74-b543-0f4ba875b90a

📥 Commits

Reviewing files that changed from the base of the PR and between c10cc96 and cc2b8a6.

📒 Files selected for processing (1)
  • pnpm/crates/resolving-deps-resolver/benches/workspace_full_resolution.rs

📝 Walkthrough

Walkthrough

The resolver records workspace mutations in append-only logs. PeerHoistDiscovery consumes new writes through SyncCursor. Rebuilds retain cursor state. Tests compare incremental synchronization with full reconstruction. Benchmarks now cover plain, peer-provided, and peer-hoisted resolution.

Changes

Incremental peer discovery

Layer / File(s) Summary
Persistent peer discovery engine
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree.rs, pnpm/crates/resolving-deps-resolver/src/resolve_peers/discovery.rs
PeerHoistDiscovery stores SyncCursor, passes it to synchronization, and rebuilds the discovery tree after stale or failed synchronization.
Workspace synchronization log
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs
WorkspaceTreeCtx records package, child-edge, dependency-node, and peer-name writes. Synchronization consumes entries after the cursor and advances it after success.
Dependency-tree mutation tracking
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/reuse.rs, pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/walk.rs, pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs
Reuse, walking, peer-name insertion, depth changes, and lazy child rewrites record the keys required for incremental synchronization.
Synchronization validation
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs, .changeset/incremental-discovery-tree-sync.md
Tests compare incremental and rebuilt discovery trees and verify incompatible peer-dependency splits. The changeset documents the patch release.
Resolution benchmark scenarios
pnpm/crates/resolving-deps-resolver/benches/workspace_full_resolution.rs
The benchmark runs plain, peer-provided, and peer-hoisted resolution scenarios with shape-specific workspace inputs.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PeerHoistDiscovery
  participant WorkspaceTreeCtx
  participant SyncLog
  participant ResolvedTree
  PeerHoistDiscovery->>WorkspaceTreeCtx: sync_discovery_tree(tree, cursor)
  WorkspaceTreeCtx->>SyncLog: read writes since cursor
  SyncLog-->>WorkspaceTreeCtx: changed package, child, node, and peer-name keys
  WorkspaceTreeCtx->>ResolvedTree: apply changed workspace entries
  WorkspaceTreeCtx-->>PeerHoistDiscovery: synchronization result
Loading

Possibly related issues

  • pnpm/pnpm#13505: Describes the peer-resolution bottleneck addressed by incremental discovery synchronization during hoist rounds.

Possibly related PRs

  • pnpm/pnpm#13491: Extends related WorkspaceTreeCtx and PeerHoistDiscovery synchronization work.
  • pnpm/pnpm#13551: Modifies the related peer-hoist discovery synchronization flow.
  • pnpm/pnpm#13562: Modifies the same dependency-tree modules used for synchronization tracking.

Suggested labels: product: pacquet

Suggested reviewers: copilot

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

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 1, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

The previously reported unused .orig backup has been removed, so no blocking failure remains.

Reviews (6): Last reviewed commit: "test(resolving-deps-resolver): add a hoi..." | Re-trigger Greptile

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Speed up peer-hoist discovery sync via append-only write log

✨ Enhancement 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Track keys written to shared workspace maps and sync discovery view incrementally.
• Thread a sync cursor through peer-hoist discovery to avoid full-map rescans each round.
• Add regression tests and changeset documenting faster peer resolution on large workspaces.
Diagram

graph TD
  W["Walk/Reuse"] --> C["WorkspaceTreeCtx"] --> M[("Shared maps")]
  C --> L[("SyncLog")]
  D["PeerHoistDiscovery"] -->|"sync(cursor)"| C --> V["ResolvedTree view"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Dirty-key sets (dedup) instead of append-only log
  • ➕ Bounds per-round replay work to unique keys (no duplicates)
  • ➕ Can clear sets after each successful sync
  • ➖ Harder to make rebuild-from-scratch deterministic without extra bookkeeping
  • ➖ More coordination needed for concurrent writers (set lifetime/clearing)
2. Per-map revision + incremental iterators
  • ➕ Avoids storing key history; relies on versioning
  • ➕ Can be space-efficient if maps provide change-tracking
  • ➖ Requires intrusive data-structure changes (maps need change journals or copy-on-write)
  • ➖ Hard to support 'rebuild by replaying everything ever written' semantics
3. Event/observer pipeline for discovery view updates
  • ➕ View updates can be applied immediately at write sites
  • ➕ Potentially avoids any sync phase cost
  • ➖ Higher coupling between writers and view merge logic
  • ➖ More correctness risk; harder to keep merge policy unchanged

Recommendation: Keep the append-only key log + cursor approach: it minimizes locking complexity, preserves existing merge behavior by re-reading current values at sync time (keys-only logging), and supports both incremental sync and from-scratch rebuild by replaying the log. Consider optional future dedup (e.g., periodic compaction) only if log growth becomes measurable.

Files changed (8) +529 / -13

Enhancement (4) +144 / -12
reuse.rsRecord workspace-map writes during lockfile reuse +5/-1

Record workspace-map writes during lockfile reuse

• Adds write-log recording for package insertions, peer-name insertions, and children_by_id updates during reuse paths. Ensures incremental sync can observe in-place and conditional updates.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/reuse.rs

walk.rsRecord workspace-map writes during dependency tree walk +3/-0

Record workspace-map writes during dependency tree walk

• Logs writes for packages, children_by_id, and dependencies_tree nodes (including depth improvements and lazy rewrites). Updates children rewrite handling to record affected node IDs for incremental syncing.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/walk.rs

workspace_ctx.rsImplement SyncLog + cursor-based sync_discovery_tree +128/-9

Implement SyncLog + cursor-based sync_discovery_tree

• Adds an append-only SyncLog to track written keys and introduces SyncCursor to replay only new writes per sync. Reworks sync_discovery_tree to consume log slices, update the cursor on success, and leave it unchanged on unmergeable conflicts; includes a helper to copy written keys without holding both locks.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs

discovery.rsThread SyncCursor through PeerHoistDiscovery sync lifecycle +8/-2

Thread SyncCursor through PeerHoistDiscovery sync lifecycle

• Extends PeerHoistDiscovery to maintain a cursor alongside the persistent ResolvedTree view. Sync now passes the cursor, and view rebuilds reset the cursor before replaying the full log.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/discovery.rs

Refactor (1) +1 / -0
resolve_dependency_tree.rsRe-export SyncCursor for discovery integration +1/-0

Re-export SyncCursor for discovery integration

• Exports the new SyncCursor type from workspace_ctx so peer discovery can track its sync position across rounds.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree.rs

Tests (1) +111 / -1
tests.rsAdd tests for incremental sync equivalence and conflict behavior +111/-1

Add tests for incremental sync equivalence and conflict behavior

• Adds coverage ensuring wave-by-wave syncing matches a from-scratch rebuild and that peer-dependency split changes correctly force a full rebuild (sync returns false). Includes helpers that simulate writes while recording the corresponding log entries.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs

Documentation (2) +273 / -0
incremental-discovery-tree-sync.mdAdd changeset for faster large-workspace peer resolution +5/-0

Add changeset for faster large-workspace peer resolution

• Introduces a patch changeset describing the performance improvement: hoist rounds refresh the discovery view incrementally rather than scanning all resolved packages.

.changeset/incremental-discovery-tree-sync.md

discovery.rs.origAdd .orig copy of discovery module +268/-0

Add .orig copy of discovery module

• Adds a full duplicate of the discovery module with a .orig suffix (not compiled by Rust). Review whether this is intentionally kept as a reference artifact or should be removed before merge.

pnpm/crates/resolving-deps-resolver/src/resolve_peers/discovery.rs.orig

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

Copilot AI 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.

Pull request overview

Improves pacquet’s peer-hoist discovery performance by switching the persistent discovery view refresh from full-map rescans to an incremental “replay keys written since cursor” approach, reducing per-round sync costs in large workspaces.

Changes:

  • Add an append-only SyncLog + SyncCursor to WorkspaceTreeCtx, and refresh the discovery ResolvedTree by visiting only keys written since the last cursor.
  • Record write keys at mutation sites (packages, children_by_id, dependencies_tree, peer-dep-name registration) so incremental sync is correct.
  • Add unit tests validating wave-by-wave sync equivalence vs from-scratch rebuild and detecting unmergeable peer-split changes; add a changeset for the perf improvement.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
pnpm/crates/resolving-deps-resolver/src/resolve_peers/discovery.rs.orig Adds a duplicated “.orig” Rust source file (appears unintended).
pnpm/crates/resolving-deps-resolver/src/resolve_peers/discovery.rs Threads SyncCursor through discovery’s sync/rebuild path.
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs Introduces SyncLog/SyncCursor, incremental sync_discovery_tree, and write-recording helpers.
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs Adds sync correctness tests (currently includes a dbg! that should be removed).
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/walk.rs Records write keys when updating packages/children/tree nodes during fresh walks.
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/reuse.rs Records write keys when populating data during lockfile reuse walks.
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree.rs Re-exports SyncCursor for internal crate use.
.changeset/incremental-discovery-tree-sync.md Changeset entry documenting the pacquet peer-resolution perf improvement.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copilot AI review requested due to automatic review settings August 1, 2026 18:54
@github-actions

github-actions Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                                            main                                   pr
-----                                            ----                                   --
lockfile/parse_pnpm_lock                         1.00     11.5±0.02ms    32.7 MB/sec    1.04     11.9±0.03ms    31.5 MB/sec
packument/parse                                  1.00     37.2±0.11µs  1784.9 MB/sec    1.00     37.2±0.17µs  1782.2 MB/sec
tarball/download_dependency                      1.01      2.3±0.05ms  1889.5 KB/sec    1.00      2.3±0.07ms  1913.2 KB/sec
tarball_batch/cold_store_many_medium_tarballs    1.01    171.4±1.06ms 93.4 KElem/sec    1.00    170.2±2.41ms 94.0 KElem/sec

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Remediation recommended

1. Unbounded sync log growth 🐞 Bug ➹ Performance
Description
WorkspaceTreeCtx’s new SyncLog is append-only and never pruned, so it retains every recorded key
for the lifetime of the context even after all views’ cursors have advanced past them. On large (or
attacker-influenced) dependency graphs with many writes/rounds, this can increase memory usage and
allocation/copy work proportional to total write events rather than the distinct map keys.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[R736-758]

+    /// Record a write to one of the maps [`Self::sync_discovery_tree`]
+    /// mirrors. Every write a sync has to observe must be recorded here,
+    /// including an in-place mutation of an entry that already exists:
+    /// the sync visits recorded keys only, so an unrecorded write stays
+    /// invisible to the discovery engine's view.
+    pub(super) fn record_package_write(&self, pkg_id: &str) {
+        lock_recoverable(&self.sync_log).packages.push(pkg_id.to_string());
+    }
+
+    /// See [`Self::record_package_write`].
+    pub(super) fn record_children_by_id_write(&self, pkg_id: &str) {
+        lock_recoverable(&self.sync_log).children_by_id.push(pkg_id.to_string());
+    }
+
+    /// See [`Self::record_package_write`].
+    pub(super) fn record_tree_node_write(&self, node_id: &NodeId) {
+        lock_recoverable(&self.sync_log).dependencies_tree.push(node_id.clone());
+    }
+
+    /// See [`Self::record_package_write`].
+    pub(super) fn record_peer_dep_name(&self, name: &str) {
+        lock_recoverable(&self.sync_log).peer_dep_names.push(name.to_string());
+    }
Relevance

●● Moderate

No direct prior suggestion on pruning append-only logs; team has accepted memory-bounding perf work
(PR pnpm/pnpm#13545).

PR-#13545

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new log stores cloned keys in Vecs via the record_* methods, and sync_discovery_tree only
advances a cursor; there is no code path that drains/compacts the log based on cursor progress.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[332-347]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[736-758]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[780-910]

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

### Issue description
`SyncLog` grows monotonically because every `record_*` call appends to a `Vec`, but nothing ever removes entries that all discovery views have already consumed via `SyncCursor`. This can retain unnecessary memory and add sustained allocation pressure on large resolves.

### Issue Context
- `SyncLog` stores keys as `Vec<...>` and `record_*` pushes cloned keys.
- `SyncCursor` advances, but the log is never compacted/drained.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[332-359]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[736-759]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[786-910]

### Suggested fix
Implement log compaction so entries older than the minimum active cursor are dropped.
- Track a per-slot base offset (e.g., `packages_base`, `children_by_id_base`, …) alongside the `Vec`s, so cursors become “absolute counters” and `written_since(from,to)` indexes into `Vec[(from-base)..(to-base)]`.
- After a successful sync/rebuild, prune each slot up to the min cursor across active views (today likely just one: `PeerHoistDiscovery.cursor`).
- Ensure pruning and cursor/base arithmetic remain correct under concurrent writes (log only grows; pruning must be done under the `sync_log` mutex).

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


2. Rebuild cursor easily ignored ✓ Resolved 🐞 Bug ➹ Performance
Description
WorkspaceTreeCtx::rebuild_discovery_tree() returns the SyncCursor that must be carried forward;
if a caller forgets to store it, subsequent sync_discovery_tree() calls will treat the cursor as
still at 0 and keep replaying the full write-log slice, negating the intended per-round
amortization. The new unit test already ignores this return value, demonstrating how easy it is to
miss.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[238]

+    workspace.rebuild_discovery_tree(&mut from_scratch);
Relevance

●● Moderate

Mixed history on adding #[must_use]/preventing dropped results (accepted in pnpm/pnpm#13491, rejected in
#13161); no cursor precedent.

PR-#13491
PR-#13161

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The test shows rebuild_discovery_tree’s return value is currently dropped, and
sync_discovery_tree explicitly uses the cursor positions to determine which log entries to visit;
an unadvanced cursor forces repeated visits over the full log range.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[237-239]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[649-736]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[739-768]

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

### Issue description
`WorkspaceTreeCtx::rebuild_discovery_tree()` returns a `SyncCursor` that is required to make subsequent incremental syncs start from the correct write-log position. If the return value is ignored, the cursor remains at its old/default value and `sync_discovery_tree()` will repeatedly process a much larger log range than intended, undermining this PR’s performance objective.

### Issue Context
- `sync_discovery_tree()` uses `cursor` to compute `written_since(...)` and advances the cursor only on success.
- `rebuild_discovery_tree()` returns the new cursor snapshot, but Rust currently allows callers to ignore the return.
- The new test currently ignores the return value, making it likely this mistake could happen in future production call sites.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[328-337]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[739-768]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[237-239]

### Suggested fix
1. Add `#[must_use]` to `SyncCursor` (or to `rebuild_discovery_tree()`), so ignoring it triggers `unused_must_use`.
2. Update the test to bind the returned cursor (e.g., `let _cursor = workspace.rebuild_discovery_tree(&mut from_scratch);`).
3. (Optional hardening) Add a `debug_assert!` that `tree` is empty at the start of `rebuild_discovery_tree()` to enforce the documented precondition.

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


3. Key-log cloning overhead ✓ Resolved 🐞 Bug ➹ Performance
Description
WorkspaceTreeCtx::written_since clones the selected SyncLog key range into a fresh Vec via
.to_vec(), and rebuilds (cursor reset) replay/clones the full log; this adds avoidable
allocation+clone cost and transient memory pressure on large workspaces (a hot-path PR).
Code

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[R740-753]

+    /// The keys written to one of [`SyncLog`]'s slots between two cursor
+    /// positions, copied out so the sync can take the map's own lock
+    /// without holding the log's.
+    fn written_since<Key: Clone>(
+        &self,
+        from: usize,
+        to: usize,
+        slot: impl Fn(&SyncLog) -> &Vec<Key>,
+    ) -> Vec<Key> {
+        if from >= to {
+            return Vec::new();
+        }
+        slot(&lock_recoverable(&self.sync_log))[from..to].to_vec()
+    }
Relevance

●● Moderate

Team often accepts perf fixes avoiding cloning/allocs (e.g., pnpm/pnpm#13431) but rejects some micro-opts
(#13388).

PR-#13431
PR-#13388
PR-#13459

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new sync mechanism stores every touched key in an append-only log and then copies the unseen
portion of each slot into a new Vec before syncing, which necessarily clones each key in that
range.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[311-326]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[740-753]
pnpm/crates/resolving-deps-resolver/src/resolve_peers/discovery.rs[69-80]

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

### Issue description
`WorkspaceTreeCtx::written_since()` currently snapshots a portion of the append-only `SyncLog` with `[from..to].to_vec()`. For `String` keys this clones each string in the range, introducing extra allocations and transient memory pressure. The impact is smallest for incremental syncs but largest when a view is rebuilt from scratch (cursor reset), which replays the entire log.

### Issue Context
- `SyncLog` is append-only and stores `Vec<String>` / `Vec<NodeId>`.
- `PeerHoistDiscovery` resets its cursor on rebuild, causing a full replay.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[311-326]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[656-737]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[740-753]
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/discovery.rs[69-80]

### Suggested fix directions (pick one)
1. **Iterate the log range without cloning all keys**: restructure sync to process the log ranges in chunks while holding the log lock briefly, cloning only the current key (or a small batch) at a time.
2. **Store cheap-to-clone key handles**: change `SyncLog` slots from `Vec<String>` to `Vec<Arc<str>>` (and record using a shared/interned representation) so snapshots are cheap `Arc` clones.
3. **Make rebuilds scan maps instead of replaying the full log**: keep the log for incremental sync, but on rebuild (cursor reset) populate the view by scanning the shared maps once and optionally truncate/reset the log.

Ensure any chosen approach preserves the "no lock-order inversion" goal (don’t hold the log lock while also holding map locks for long durations).

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



Informational

4. Scenario timings not comparable 🐞 Bug ➹ Performance ⭐ New
Description
The new hoist-heavy scenario changes the importer workload by reducing direct roots per importer to
ROOTS_PER_IMPORTER (6) while the other scenarios use all PACKAGES_PER_LAYER (20). This
intentionally forces differing forests, but it also changes the baseline graph traversal/resolution
work, making the three printed timings easy to miscompare as if they measured only peer-hoist
behavior.
Code

pnpm/crates/resolving-deps-resolver/benches/workspace_full_resolution.rs[R206-213]

+fn importer_manifest(index: usize, shape: Shape) -> PackageManifest {
+    let roots: Vec<usize> = if shape == Shape::PeersHoisted {
+        (0..ROOTS_PER_IMPORTER).map(|offset| (index + offset) % PACKAGES_PER_LAYER).collect()
+    } else {
+        (0..PACKAGES_PER_LAYER).collect()
+    };
+    let mut dependencies: serde_json::Map<String, serde_json::Value> = roots
+        .into_iter()
Relevance

●● Moderate

No historical evidence on scenario comparability; benchmark-related adjustments often rejected
(e.g., doc/threshold feedback in PRs 13491, 13545).

PR-#13491
PR-#13545

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
ROOTS_PER_IMPORTER is introduced specifically for the hoist-heavy shape and importer_manifest()
uses it only when shape == Shape::PeersHoisted; other shapes still use the full
PACKAGES_PER_LAYER root set, so the scenario’s baseline work differs by construction.

pnpm/crates/resolving-deps-resolver/benches/workspace_full_resolution.rs[58-62]
pnpm/crates/resolving-deps-resolver/benches/workspace_full_resolution.rs[206-216]
pnpm/crates/resolving-deps-resolver/benches/workspace_full_resolution.rs[324-326]

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 benchmark now prints three scenario timings back-to-back, but the new `PeersHoisted` scenario reduces direct roots per importer (6 vs 20 in the other scenarios). This is intentional to diversify forests, but it makes the three timings not apples-to-apples.

### Issue Context
Because the benchmark prints only one elapsed time per scenario, readers may incorrectly attribute runtime differences solely to peer-hoist/discovery behavior rather than also to a different amount of graph work.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/benches/workspace_full_resolution.rs[58-62]
- pnpm/crates/resolving-deps-resolver/benches/workspace_full_resolution.rs[206-216]
- pnpm/crates/resolving-deps-resolver/benches/workspace_full_resolution.rs[287-317]

### Suggested changes
- Encode the root-count difference into the printed label (e.g., `"hoist-heavy (6 roots/importer)"`).
- And/or print a per-scenario workload indicator alongside elapsed time (e.g., number of direct deps per importer, or another resolved-node metric already available in the result), so comparisons are correctly contextualized.

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


5. dbg! in unit test 🐞 Bug ⚙ Maintainability
Description
The new unit test prints dbg!(...) unconditionally, which will spam stderr on every successful
test run and add noise to CI logs.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[249]

+    dbg!(depths(&carried), depths(&from_scratch));
Relevance

●●● Strong

Team has accepted removing unconditional dbg!/noise in tests (e.g., PR pnpm/pnpm#13329; also partially
accepted in pnpm/pnpm#13455).

PR-#13329
PR-#13455

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The test contains an unconditional dbg! call immediately before assertions.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[243-251]

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 `dbg!(...)` call was left in a unit test and will print to stderr even on success.

### Issue Context
This is test-only but adds persistent noise to CI output.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[243-251]

### Proposed fix
Remove the `dbg!(...)` line (or gate it behind a debug-only conditional that is off by default).

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


6. Changeset missing pnpm bump 📘 Rule violation § Compliance
Description
The new changeset lists only pacquet and does not include a required pnpm entry, so release
tooling may not correctly version/bundle this change for pnpm.
Code

.changeset/incremental-discovery-tree-sync.md[R1-3]

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

● Weak

Similar “add pnpm entry to changeset” compliance suggestions repeatedly rejected (e.g., PRs pnpm/pnpm#13417,
#13406, pnpm/pnpm#13491).

PR-#13417
PR-#13406
PR-#13491

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires changesets to contain an explicit pnpm entry with a valid bump
type. The added changeset front-matter includes only pacquet, with no pnpm entry.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/incremental-discovery-tree-sync.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 changeset front-matter is missing a `pnpm` package entry.

## Issue Context
Compliance requires every new/modified changeset to explicitly include `pnpm` with a valid bump type (`patch`/`minor`/`major`).

## Fix Focus Areas
- .changeset/incremental-discovery-tree-sync.md[1-3]

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


Grey Divider

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Previous review results

Review updated until commit cc2b8a6

Results up to commit 1478f61 ⚖️ Balanced


🐞 Bugs (1) 📘 Rule violations (1) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Key-log cloning overhead ✓ Resolved 🐞 Bug ➹ Performance
Description
WorkspaceTreeCtx::written_since clones the selected SyncLog key range into a fresh Vec via
.to_vec(), and rebuilds (cursor reset) replay/clones the full log; this adds avoidable
allocation+clone cost and transient memory pressure on large workspaces (a hot-path PR).
Code

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[R740-753]

+    /// The keys written to one of [`SyncLog`]'s slots between two cursor
+    /// positions, copied out so the sync can take the map's own lock
+    /// without holding the log's.
+    fn written_since<Key: Clone>(
+        &self,
+        from: usize,
+        to: usize,
+        slot: impl Fn(&SyncLog) -> &Vec<Key>,
+    ) -> Vec<Key> {
+        if from >= to {
+            return Vec::new();
+        }
+        slot(&lock_recoverable(&self.sync_log))[from..to].to_vec()
+    }
Relevance

●● Moderate

Team often accepts perf fixes avoiding cloning/allocs (e.g., pnpm/pnpm#13431) but rejects some micro-opts
(#13388).

PR-#13431
PR-#13388
PR-#13459

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new sync mechanism stores every touched key in an append-only log and then copies the unseen
portion of each slot into a new Vec before syncing, which necessarily clones each key in that
range.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[311-326]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[740-753]
pnpm/crates/resolving-deps-resolver/src/resolve_peers/discovery.rs[69-80]

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

### Issue description
`WorkspaceTreeCtx::written_since()` currently snapshots a portion of the append-only `SyncLog` with `[from..to].to_vec()`. For `String` keys this clones each string in the range, introducing extra allocations and transient memory pressure. The impact is smallest for incremental syncs but largest when a view is rebuilt from scratch (cursor reset), which replays the entire log.

### Issue Context
- `SyncLog` is append-only and stores `Vec<String>` / `Vec<NodeId>`.
- `PeerHoistDiscovery` resets its cursor on rebuild, causing a full replay.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[311-326]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[656-737]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[740-753]
- pnpm/crates/resolving-deps-resolver/src/resolve_peers/discovery.rs[69-80]

### Suggested fix directions (pick one)
1. **Iterate the log range without cloning all keys**: restructure sync to process the log ranges in chunks while holding the log lock briefly, cloning only the current key (or a small batch) at a time.
2. **Store cheap-to-clone key handles**: change `SyncLog` slots from `Vec<String>` to `Vec<Arc<str>>` (and record using a shared/interned representation) so snapshots are cheap `Arc` clones.
3. **Make rebuilds scan maps instead of replaying the full log**: keep the log for incremental sync, but on rebuild (cursor reset) populate the view by scanning the shared maps once and optionally truncate/reset the log.

Ensure any chosen approach preserves the "no lock-order inversion" goal (don’t hold the log lock while also holding map locks for long durations).

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



Informational
2. dbg! in unit test 🐞 Bug ⚙ Maintainability
Description
The new unit test prints dbg!(...) unconditionally, which will spam stderr on every successful
test run and add noise to CI logs.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[249]

+    dbg!(depths(&carried), depths(&from_scratch));
Relevance

●●● Strong

Team has accepted removing unconditional dbg!/noise in tests (e.g., PR pnpm/pnpm#13329; also partially
accepted in pnpm/pnpm#13455).

PR-#13329
PR-#13455

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The test contains an unconditional dbg! call immediately before assertions.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[243-251]

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 `dbg!(...)` call was left in a unit test and will print to stderr even on success.

### Issue Context
This is test-only but adds persistent noise to CI output.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[243-251]

### Proposed fix
Remove the `dbg!(...)` line (or gate it behind a debug-only conditional that is off by default).

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


3. Changeset missing pnpm bump 📘 Rule violation § Compliance
Description
The new changeset lists only pacquet and does not include a required pnpm entry, so release
tooling may not correctly version/bundle this change for pnpm.
Code

.changeset/incremental-discovery-tree-sync.md[R1-3]

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

● Weak

Similar “add pnpm entry to changeset” compliance suggestions repeatedly rejected (e.g., PRs pnpm/pnpm#13417,
#13406, pnpm/pnpm#13491).

PR-#13417
PR-#13406
PR-#13491

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires changesets to contain an explicit pnpm entry with a valid bump
type. The added changeset front-matter includes only pacquet, with no pnpm entry.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/incremental-discovery-tree-sync.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 changeset front-matter is missing a `pnpm` package entry.

## Issue Context
Compliance requires every new/modified changeset to explicitly include `pnpm` with a valid bump type (`patch`/`minor`/`major`).

## Fix Focus Areas
- .changeset/incremental-discovery-tree-sync.md[1-3]

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


Results up to commit 258c7de ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Rebuild cursor easily ignored ✓ Resolved 🐞 Bug ➹ Performance
Description
WorkspaceTreeCtx::rebuild_discovery_tree() returns the SyncCursor that must be carried forward;
if a caller forgets to store it, subsequent sync_discovery_tree() calls will treat the cursor as
still at 0 and keep replaying the full write-log slice, negating the intended per-round
amortization. The new unit test already ignores this return value, demonstrating how easy it is to
miss.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[238]

+    workspace.rebuild_discovery_tree(&mut from_scratch);
Relevance

●● Moderate

Mixed history on adding #[must_use]/preventing dropped results (accepted in pnpm/pnpm#13491, rejected in
#13161); no cursor precedent.

PR-#13491
PR-#13161

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The test shows rebuild_discovery_tree’s return value is currently dropped, and
sync_discovery_tree explicitly uses the cursor positions to determine which log entries to visit;
an unadvanced cursor forces repeated visits over the full log range.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[237-239]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[649-736]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[739-768]

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

### Issue description
`WorkspaceTreeCtx::rebuild_discovery_tree()` returns a `SyncCursor` that is required to make subsequent incremental syncs start from the correct write-log position. If the return value is ignored, the cursor remains at its old/default value and `sync_discovery_tree()` will repeatedly process a much larger log range than intended, undermining this PR’s performance objective.

### Issue Context
- `sync_discovery_tree()` uses `cursor` to compute `written_since(...)` and advances the cursor only on success.
- `rebuild_discovery_tree()` returns the new cursor snapshot, but Rust currently allows callers to ignore the return.
- The new test currently ignores the return value, making it likely this mistake could happen in future production call sites.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[328-337]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[739-768]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs[237-239]

### Suggested fix
1. Add `#[must_use]` to `SyncCursor` (or to `rebuild_discovery_tree()`), so ignoring it triggers `unused_must_use`.
2. Update the test to bind the returned cursor (e.g., `let _cursor = workspace.rebuild_discovery_tree(&mut from_scratch);`).
3. (Optional hardening) Add a `debug_assert!` that `tree` is empty at the start of `rebuild_discovery_tree()` to enforce the documented precondition.

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


Results up to commit c10cc96 ⚖️ Balanced


🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Unbounded sync log growth 🐞 Bug ➹ Performance
Description
WorkspaceTreeCtx’s new SyncLog is append-only and never pruned, so it retains every recorded key
for the lifetime of the context even after all views’ cursors have advanced past them. On large (or
attacker-influenced) dependency graphs with many writes/rounds, this can increase memory usage and
allocation/copy work proportional to total write events rather than the distinct map keys.
Code

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[R736-758]

+    /// Record a write to one of the maps [`Self::sync_discovery_tree`]
+    /// mirrors. Every write a sync has to observe must be recorded here,
+    /// including an in-place mutation of an entry that already exists:
+    /// the sync visits recorded keys only, so an unrecorded write stays
+    /// invisible to the discovery engine's view.
+    pub(super) fn record_package_write(&self, pkg_id: &str) {
+        lock_recoverable(&self.sync_log).packages.push(pkg_id.to_string());
+    }
+
+    /// See [`Self::record_package_write`].
+    pub(super) fn record_children_by_id_write(&self, pkg_id: &str) {
+        lock_recoverable(&self.sync_log).children_by_id.push(pkg_id.to_string());
+    }
+
+    /// See [`Self::record_package_write`].
+    pub(super) fn record_tree_node_write(&self, node_id: &NodeId) {
+        lock_recoverable(&self.sync_log).dependencies_tree.push(node_id.clone());
+    }
+
+    /// See [`Self::record_package_write`].
+    pub(super) fn record_peer_dep_name(&self, name: &str) {
+        lock_recoverable(&self.sync_log).peer_dep_names.push(name.to_string());
+    }
Relevance

●● Moderate

No direct prior suggestion on pruning append-only logs; team has accepted memory-bounding perf work
(PR pnpm/pnpm#13545).

PR-#13545

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new log stores cloned keys in Vecs via the record_* methods, and sync_discovery_tree only
advances a cursor; there is no code path that drains/compacts the log based on cursor progress.

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[332-347]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[736-758]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[780-910]

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

### Issue description
`SyncLog` grows monotonically because every `record_*` call appends to a `Vec`, but nothing ever removes entries that all discovery views have already consumed via `SyncCursor`. This can retain unnecessary memory and add sustained allocation pressure on large resolves.

### Issue Context
- `SyncLog` stores keys as `Vec<...>` and `record_*` pushes cloned keys.
- `SyncCursor` advances, but the log is never compacted/drained.

### Fix Focus Areas
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[332-359]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[736-759]
- pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs[786-910]

### Suggested fix
Implement log compaction so entries older than the minimum active cursor are dropped.
- Track a per-slot base offset (e.g., `packages_base`, `children_by_id_base`, …) alongside the `Vec`s, so cursors become “absolute counters” and `written_since(from,to)` indexes into `Vec[(from-base)..(to-base)]`.
- After a successful sync/rebuild, prune each slot up to the min cursor across active views (today likely just one: `PeerHoistDiscovery.cursor`).
- Ensure pruning and cursor/base arithmetic remain correct under concurrent writes (log only grows; pruning must be done under the `sync_log` mutex).

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


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.

@codecov-commenter

codecov-commenter commented Aug 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.01961% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 87.98%. Comparing base (0d35c6c) to head (cc2b8a6).

Files with missing lines Patch % Lines
...-deps-resolver/src/resolve_dependency_tree/walk.rs 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   pnpm/pnpm#13571      +/-   ##
==========================================
+ Coverage   87.97%   87.98%   +0.01%     
==========================================
  Files         563      563              
  Lines       97412    97499      +87     
==========================================
+ Hits        85698    85785      +87     
  Misses      11714    11714              

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

Copilot AI 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.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.

Suppressed comments (1)

pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs:241

  • This test passes &mut super::SyncCursor::default() into sync_discovery_tree. Rust doesn't allow taking a mutable reference to a temporary, so this should fail to compile. Use a local mut cursor variable instead.
    let mut from_scratch = crate::resolved_tree::ResolvedTree::default();
    assert!(
        workspace.sync_discovery_tree(&mut from_scratch, &mut super::SyncCursor::default()),
        "a sync into an empty view has nothing to conflict with",
    );

@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 (3)
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/walk.rs (1)

460-462: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Record the package write after the insert, not before.

record_package_write(&id) at Line 461 runs before packages.insert(...) at Line 462, the opposite order from the branch just above it (Lines 453-457), which mutates existing.peer_dependencies before calling record_package_write. This is currently safe only because the packages lock guard spans both statements in the new-package branch. Swap the order for consistency with the sibling branch and with every other write-recording site in this PR.

See the consolidated comment for the shared fix across this file and reuse.rs.

🤖 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/resolving-deps-resolver/src/resolve_dependency_tree/walk.rs`
around lines 460 - 462, Move ctx.workspace.record_package_write(&id) to after
the packages.insert(...) call in the new-package branch of the dependency-tree
walk, matching the mutation-then-record order used by the sibling branch and
other write-recording sites.
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/reuse.rs (2)

581-582: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Record the package write after the insert, not before.

record_package_write(&id) runs before packages.insert(...). This is the opposite order used by every other write-recording site in this PR (children_by_id, dependencies_tree, and walk.rs's own "changed peer_dependencies" branch). It is currently safe only because the packages lock guard spans both statements. Swap the order for consistency and to remove the dependency on that lock-scope detail.

See the consolidated comment for the shared fix across this file and walk.rs.

🤖 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/resolving-deps-resolver/src/resolve_dependency_tree/reuse.rs`
around lines 581 - 582, In the package update flow, move
ctx.workspace.record_package_write(&id) to execute after packages.insert
completes. Preserve the existing package insertion behavior and apply this
ordering consistently with the other write-recording sites referenced in the
comment.

573-581: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse the existing peer-name registration helper.

This loop duplicates register_peer_dep_names in workspace_ctx.rs, which walk.rs already calls for the same purpose. Call the shared helper instead of re-implementing the loop here.

♻️ Proposed fix
-            {
-                let mut all_peers = lock_recoverable(&ctx.workspace.all_peer_dep_names);
-                for name in peer_dependencies.keys() {
-                    if all_peers.insert(name.clone()) {
-                        ctx.workspace.record_peer_dep_name(name);
-                    }
-                }
-            }
+            register_peer_dep_names(ctx, &peer_dependencies);
             ctx.workspace.record_package_write(&id);
🤖 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/resolving-deps-resolver/src/resolve_dependency_tree/reuse.rs`
around lines 573 - 581, Replace the duplicated peer-name insertion loop in the
reuse flow with the existing WorkspaceContext::register_peer_dep_names helper,
passing the peer dependency names from peer_dependencies. Preserve the
subsequent ctx.workspace.record_package_write(&id) call and remove the direct
all_peer_dep_names locking and iteration.
🤖 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/resolving-deps-resolver/src/resolve_peers/discovery.rs.orig`:
- Around line 1-268: Delete the stray discovery.rs.orig backup file entirely;
keep the active discovery.rs implementation unchanged.

---

Nitpick comments:
In `@pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/reuse.rs`:
- Around line 581-582: In the package update flow, move
ctx.workspace.record_package_write(&id) to execute after packages.insert
completes. Preserve the existing package insertion behavior and apply this
ordering consistently with the other write-recording sites referenced in the
comment.
- Around line 573-581: Replace the duplicated peer-name insertion loop in the
reuse flow with the existing WorkspaceContext::register_peer_dep_names helper,
passing the peer dependency names from peer_dependencies. Preserve the
subsequent ctx.workspace.record_package_write(&id) call and remove the direct
all_peer_dep_names locking and iteration.

In `@pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/walk.rs`:
- Around line 460-462: Move ctx.workspace.record_package_write(&id) to after the
packages.insert(...) call in the new-package branch of the dependency-tree walk,
matching the mutation-then-record order used by the sibling branch and other
write-recording sites.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e7b582e9-174e-492b-887c-596f08854ce4

📥 Commits

Reviewing files that changed from the base of the PR and between d6a01f0 and 83f76ec.

📒 Files selected for processing (8)
  • .changeset/incremental-discovery-tree-sync.md
  • pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/reuse.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/walk.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree/workspace_ctx/tests.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers/discovery.rs
  • pnpm/crates/resolving-deps-resolver/src/resolve_peers/discovery.rs.orig

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Aug 1, 2026
Copilot AI review requested due to automatic review settings August 1, 2026 19:04

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@zkochan

zkochan commented Aug 1, 2026 •

Copy link
Copy Markdown
Member Author

Thanks — Qodo's three findings and CodeRabbit's one:

1. Key-log cloning overhead — taken, fixed in 258c7de. The finding is right about the rebuild path: replaying the whole log to refill a discarded view copies every key twice, once into the log snapshot and once into the view. Rebuilds now scan the shared maps instead (Qodo's suggested direction 3), and take their cursor from the log's length before the scan, so a write landing mid-scan is either picked up by the scan and replayed harmlessly by the next sync, or missed by it and applied by the next sync. The incremental path keeps the small to_vec(): the range is one hoist round's writes, and the alternative — holding the log lock while taking a map lock — is the lock-order inversion the copy exists to avoid.

2. dbg! in the unit test — keeping it, for the reason on the inline thread: pnpm/CODE_STYLE_GUIDE.md line 454 asks for dbg! when assert_eq! compares complex structures, and the assertion compares two BTreeMaps. Test output is captured by cargo test / cargo nextest, so it prints nothing unless the test fails.

3. Changeset missing a pnpm entry — intentional. AGENTS.md is explicit that a Rust-only changeset must omit pnpm (there it names the TypeScript CLI package); this PR touches only pnpm/crates/resolving-deps-resolver.

CodeRabbit's .orig finding was already fixed — Greptile caught the same file and it was removed in 1478f61, one commit before that review ran. Nothing left to do there.


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

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 258c7de

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

Copilot AI review requested due to automatic review settings August 1, 2026 19:12

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@zkochan

zkochan commented Aug 1, 2026

Copy link
Copy Markdown
Member Author

Rebuild cursor easily ignored — taken, fixed in ddcaaf0. rebuild_discovery_tree now takes &mut SyncCursor like the incremental sync does and sets it in place, so there is no return value to drop and no way to leave the view replaying the whole log. The test was the example Qodo pointed at; it passes a cursor now too.

Full gate re-run after the change: 7,549 tests pass, clippy/dylint/fmt clean.


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

@qodo-code-review

Copy link
Copy Markdown

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

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

@zkochan

zkochan commented Aug 1, 2026

Copy link
Copy Markdown
Member Author

On the Codecov note — the one uncovered line is record_package_write on the peer re-split branch in walk.rs (a children-owner handover whose new owner shadows a different set of dependencies, so the package's children/peers split changes). That branch is not exercised anywhere in the suite today, which is why the added line shows uncovered; the two neighbouring record sites (fresh package, children_by_id write) are covered.

It is worth knowing what the gap means: if that call were missing, the discovery view would keep the stale split instead of reporting itself unmergeable. The sync side of exactly that case is pinned by a_changed_peer_dependency_split_makes_the_view_unmergeable; what is untested is the walk calling it. Building a fixture that makes two occurrences shadow different dependency names is a bigger piece of test scaffolding than this PR needs — flagging it rather than leaving it implicit, and happy to add it if you would rather have it here than as a follow-up.


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

@github-actions

github-actions Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: cc2b8a69be95

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.589 ± 0.145 2.363 2.782 1.72 ± 0.22
pacquet@main 2.505 ± 0.139 2.344 2.748 1.66 ± 0.21
pnpr@HEAD 1.505 ± 0.169 1.349 1.793 1.00
pnpr@main 1.542 ± 0.142 1.338 1.728 1.02 ± 0.15
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.5889385138599996,
      "stddev": 0.14536124788984822,
      "median": 2.5641881816599996,
      "user": 1.67312316,
      "system": 1.3081888999999998,
      "min": 2.36274086116,
      "max": 2.78239157816,
      "times": [
        2.47370899716,
        2.78239157816,
        2.55731400016,
        2.74935952616,
        2.46292453916,
        2.49364923716,
        2.57106236316,
        2.36274086116,
        2.75628386216,
        2.67995017416
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.50531227346,
      "stddev": 0.1388891433408085,
      "median": 2.47083109116,
      "user": 1.64097086,
      "system": 1.322052,
      "min": 2.34411170816,
      "max": 2.74835167316,
      "times": [
        2.3544303851599997,
        2.55433002416,
        2.61770336316,
        2.50138748516,
        2.6704056341599998,
        2.44027469716,
        2.34411170816,
        2.43837237416,
        2.74835167316,
        2.38375539016
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.5051756489599997,
      "stddev": 0.16949365162031224,
      "median": 1.4344150731599998,
      "user": 1.2125289599999998,
      "system": 1.1370327999999998,
      "min": 1.3491484411599999,
      "max": 1.79297593316,
      "times": [
        1.3524868021599998,
        1.43771985416,
        1.54418815916,
        1.3491484411599999,
        1.7771966521599998,
        1.79297593316,
        1.38067843016,
        1.60871617316,
        1.4311102921599999,
        1.37753575216
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.54209468976,
      "stddev": 0.14155960795855244,
      "median": 1.57434450716,
      "user": 1.1942226599999999,
      "system": 1.163586,
      "min": 1.33815351316,
      "max": 1.72791574416,
      "times": [
        1.72791574416,
        1.35475775416,
        1.64005812016,
        1.5560811991599999,
        1.36340266216,
        1.56991554716,
        1.68909149116,
        1.60279739916,
        1.57877346716,
        1.33815351316
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 254.1 ± 4.9 246.1 259.7 1.00
pacquet@main 257.0 ± 8.4 248.2 270.9 1.01 ± 0.04
pnpr@HEAD 275.1 ± 9.7 260.3 297.5 1.08 ± 0.04
pnpr@main 272.2 ± 6.6 263.6 285.2 1.07 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.254072092,
      "stddev": 0.0048801298224362445,
      "median": 0.2553057556,
      "user": 0.19889653999999998,
      "system": 0.51591928,
      "min": 0.2460979436,
      "max": 0.2597493616,
      "times": [
        0.2597493616,
        0.24691688460000003,
        0.2536378876,
        0.2460979436,
        0.2579119556,
        0.25697362360000003,
        0.25216635660000003,
        0.2512049476,
        0.2574082116,
        0.25865374760000004
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.2569926701,
      "stddev": 0.008427130441134818,
      "median": 0.2540347796,
      "user": 0.19915953999999997,
      "system": 0.52784828,
      "min": 0.24819911260000002,
      "max": 0.2709102306,
      "times": [
        0.25156694760000003,
        0.2507915016,
        0.25385624960000003,
        0.24819911260000002,
        0.2706283846,
        0.2486573186,
        0.2709102306,
        0.2542133096,
        0.2595713296,
        0.26153231660000004
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.27506419810000005,
      "stddev": 0.009694281743033467,
      "median": 0.2742969046,
      "user": 0.21011833999999996,
      "system": 0.5191480800000001,
      "min": 0.2603491496,
      "max": 0.2974739046,
      "times": [
        0.2796194516,
        0.2762412696,
        0.26586552760000004,
        0.2603491496,
        0.27260174660000003,
        0.2748541256,
        0.2737396836,
        0.2774429586,
        0.2724541636,
        0.2974739046
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.2721583219,
      "stddev": 0.006644998172151029,
      "median": 0.2714321246,
      "user": 0.20907134,
      "system": 0.5103027800000001,
      "min": 0.2636355636,
      "max": 0.2851996526,
      "times": [
        0.2811894086,
        0.2706210126,
        0.27343314160000004,
        0.2636355636,
        0.2681204106,
        0.2659811916,
        0.2722432366,
        0.26837878460000003,
        0.2851996526,
        0.27278081660000003
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 2.589 ± 0.015 2.561 2.606 1.62 ± 0.17
pacquet@main 2.576 ± 0.021 2.547 2.610 1.61 ± 0.17
pnpr@HEAD 1.599 ± 0.164 1.445 1.881 1.00
pnpr@main 1.619 ± 0.194 1.435 1.877 1.01 ± 0.16
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 2.5891580380800003,
      "stddev": 0.014797789337627909,
      "median": 2.59359933808,
      "user": 1.6642129799999998,
      "system": 1.3317186,
      "min": 2.5612367770800004,
      "max": 2.60638101508,
      "times": [
        2.60638101508,
        2.5937641960800004,
        2.5928651480800005,
        2.59343448008,
        2.5612367770800004,
        2.6007296600800003,
        2.5973076820800003,
        2.5767355810800003,
        2.5696560550800003,
        2.5994697860800002
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.5756265478800007,
      "stddev": 0.02135497467473969,
      "median": 2.58042103558,
      "user": 1.6355468799999997,
      "system": 1.3322717999999998,
      "min": 2.5471694530800004,
      "max": 2.60981868608,
      "times": [
        2.54867445008,
        2.5839259950800004,
        2.59467717408,
        2.55736105808,
        2.57916509708,
        2.60981868608,
        2.5471694530800004,
        2.55985142808,
        2.5939451630800003,
        2.58167697408
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 1.5990897597800002,
      "stddev": 0.16446837944423007,
      "median": 1.54573466108,
      "user": 1.18551158,
      "system": 1.1652768,
      "min": 1.44520482208,
      "max": 1.88054111408,
      "times": [
        1.5345970230800001,
        1.88054111408,
        1.44520482208,
        1.62421197608,
        1.55687229908,
        1.67063600608,
        1.87389166108,
        1.44865517008,
        1.45113400108,
        1.50515352508
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 1.61875221518,
      "stddev": 0.19403810014431003,
      "median": 1.5353814850799998,
      "user": 1.1805049799999998,
      "system": 1.1672683,
      "min": 1.43462556308,
      "max": 1.87711664708,
      "times": [
        1.45147371308,
        1.5789872890799999,
        1.85184769308,
        1.79709471208,
        1.43804104108,
        1.49177568108,
        1.43462556308,
        1.87711664708,
        1.44184103308,
        1.8247187790800001
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 398.9 ± 11.2 386.7 418.9 1.31 ± 0.05
pacquet@main 384.1 ± 15.3 364.9 415.9 1.27 ± 0.06
pnpr@HEAD 303.5 ± 7.3 293.8 314.2 1.00
pnpr@main 304.0 ± 4.6 295.0 310.2 1.00 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.39891538146000005,
      "stddev": 0.011215703026692616,
      "median": 0.39639718466000007,
      "user": 0.52390526,
      "system": 0.70815248,
      "min": 0.38666897566,
      "max": 0.41893168166000005,
      "times": [
        0.38803350966000005,
        0.39146970066000003,
        0.38850658366,
        0.40116014766,
        0.39163422166000006,
        0.40433598266000004,
        0.40936959666000006,
        0.41893168166000005,
        0.38666897566,
        0.40904341466000005
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.38413968096,
      "stddev": 0.015291789598810288,
      "median": 0.38330483066000004,
      "user": 0.51421186,
      "system": 0.6664682800000001,
      "min": 0.36492924166,
      "max": 0.41591552566000006,
      "times": [
        0.38386339366000005,
        0.38274626766000003,
        0.36492924166,
        0.36789461966000003,
        0.39077421466000006,
        0.39595520366000003,
        0.38982963166000006,
        0.41591552566000006,
        0.36894173566000005,
        0.38054697566000006
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.3034599780600001,
      "stddev": 0.007269420338763868,
      "median": 0.30221922516,
      "user": 0.19432416,
      "system": 0.50009958,
      "min": 0.29381420066,
      "max": 0.31416937266000006,
      "times": [
        0.30232049366,
        0.29947084366000004,
        0.29381420066,
        0.30211795666,
        0.31331774066,
        0.31416937266000006,
        0.29387409166000006,
        0.30128623066000004,
        0.31087976766000003,
        0.30334908266000005
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.30401003156,
      "stddev": 0.004605759116568173,
      "median": 0.30396187366000005,
      "user": 0.18826926,
      "system": 0.51121198,
      "min": 0.29502666966,
      "max": 0.31024568566000005,
      "times": [
        0.30117860066,
        0.30783437666,
        0.30215881766,
        0.31024568566000005,
        0.29502666966,
        0.30916188366,
        0.30039511466,
        0.30617541966000006,
        0.30326882866000004,
        0.30465491866000005
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.739 ± 0.009 1.725 1.755 5.81 ± 0.17
pacquet@main 1.721 ± 0.009 1.703 1.731 5.75 ± 0.16
pnpr@HEAD 0.299 ± 0.008 0.291 0.315 1.00
pnpr@main 0.300 ± 0.004 0.293 0.306 1.00 ± 0.03
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.7392546963200002,
      "stddev": 0.00857461180969982,
      "median": 1.7395408584199998,
      "user": 0.7544148399999999,
      "system": 0.75525204,
      "min": 1.72471947592,
      "max": 1.75507123292,
      "times": [
        1.7446446539199998,
        1.7420581979199998,
        1.7370235189199998,
        1.75507123292,
        1.74452141792,
        1.74402950092,
        1.72471947592,
        1.7322000089199998,
        1.73583567692,
        1.73244327892
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.72126381832,
      "stddev": 0.008649702923802197,
      "median": 1.72176268642,
      "user": 0.71557344,
      "system": 0.75861234,
      "min": 1.70275841892,
      "max": 1.7307137069199998,
      "times": [
        1.7307137069199998,
        1.72803070092,
        1.7159325959199998,
        1.7210972869199999,
        1.72915146692,
        1.7196612649199998,
        1.72242808592,
        1.70275841892,
        1.7143200079199998,
        1.72854464792
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.29936804682000007,
      "stddev": 0.008386956533125177,
      "median": 0.29633554642000004,
      "user": 0.18242123999999998,
      "system": 0.51365414,
      "min": 0.29064447392000003,
      "max": 0.31467555392,
      "times": [
        0.31467555392,
        0.29580228192,
        0.29490581092,
        0.29686881092000006,
        0.31318721292,
        0.29064447392000003,
        0.30244813392000003,
        0.29436586592,
        0.29173964692000004,
        0.29904267692000003
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.29990738152,
      "stddev": 0.004259560168001965,
      "median": 0.30022426492000004,
      "user": 0.20199664,
      "system": 0.50203464,
      "min": 0.29346698792000003,
      "max": 0.30582974192,
      "times": [
        0.29996546592000006,
        0.29346698792000003,
        0.30048306392,
        0.30401139592000004,
        0.30255749292000006,
        0.30344169992000003,
        0.29882885592,
        0.29688807692,
        0.29360103392000003,
        0.30582974192
      ]
    }
  ]
}

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

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 181.7 ± 4.6 175.3 191.0 2.03 ± 0.10
pacquet@main 183.8 ± 5.8 176.1 195.5 2.06 ± 0.11
pnpr@HEAD 89.3 ± 3.6 85.8 99.6 1.00
pnpr@main 89.3 ± 2.9 85.1 95.7 1.00 ± 0.05
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.18168739459333333,
      "stddev": 0.00464949523468522,
      "median": 0.17992957446000002,
      "user": 0.15916039333333332,
      "system": 0.08858485999999997,
      "min": 0.17533954246,
      "max": 0.19101596146000002,
      "times": [
        0.18571715946,
        0.17985732946000002,
        0.17992957446000002,
        0.17828024446000001,
        0.19101596146000002,
        0.17533954246,
        0.17671337746000002,
        0.17951337546,
        0.19041748546,
        0.18314367646000002,
        0.18330065046000002,
        0.17715930646,
        0.18377473346,
        0.17928946246000002,
        0.18185903946
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.183785529085,
      "stddev": 0.005761543466921402,
      "median": 0.18233439746000002,
      "user": 0.16946681,
      "system": 0.08079462249999998,
      "min": 0.17610762146,
      "max": 0.19548728846000002,
      "times": [
        0.18036226246,
        0.19548728846000002,
        0.18916776946,
        0.18434040346,
        0.17892568046000001,
        0.18150765846,
        0.18123548946,
        0.19446397746000002,
        0.17649359446000001,
        0.18313585646,
        0.18946830946,
        0.17610762146,
        0.18525730846000002,
        0.18153293846000002,
        0.18360419146,
        0.17947811546
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.08929123056714283,
      "stddev": 0.003614104926792856,
      "median": 0.08791863946,
      "user": 0.022462452857142854,
      "system": 0.010285095714285713,
      "min": 0.08575192246,
      "max": 0.09960431746000001,
      "times": [
        0.09960431746000001,
        0.08813529246,
        0.09044800046,
        0.08693309146,
        0.08658992246,
        0.08575192246,
        0.08586617846,
        0.08633123646,
        0.08724356746,
        0.08770198646,
        0.09065795346,
        0.08624578246,
        0.09227970346,
        0.09230167546,
        0.08883298646,
        0.09061270946,
        0.08992131246,
        0.08576378746,
        0.09561504646,
        0.08759514946000001,
        0.08608457546,
        0.09117941646,
        0.09430210546000001,
        0.09579117246,
        0.08839688746,
        0.08586658546,
        0.08656797146,
        0.08753411946
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.08934150523419354,
      "stddev": 0.0029298310686150125,
      "median": 0.08980473446000001,
      "user": 0.0221488664516129,
      "system": 0.010351283870967742,
      "min": 0.08512769146,
      "max": 0.09565002846000001,
      "times": [
        0.09028031846000001,
        0.09068843046,
        0.08781066346000001,
        0.09056105746,
        0.08534994046,
        0.09118099646,
        0.09134821646,
        0.08996143546,
        0.08603595146,
        0.08661214346,
        0.08512769146,
        0.08690210546,
        0.09494865746,
        0.09565002846000001,
        0.08641970346,
        0.08631480946,
        0.09260548146,
        0.09029706646,
        0.08973608046,
        0.08980473446000001,
        0.09177888446,
        0.09446145246,
        0.08577936046,
        0.08676441046,
        0.08700626846000001,
        0.09129536946,
        0.08524560246,
        0.09094768746,
        0.09113332346,
        0.08917603946000001,
        0.08836275146
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.783 ± 0.460 1.414 2.712 1.08 ± 0.46
pacquet@main 1.654 ± 0.561 1.039 2.678 1.00
pnpm@HEAD 3.141 ± 0.240 2.874 3.461 1.90 ± 0.66
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.7828257373444447,
      "stddev": 0.45974374628954506,
      "median": 1.5828631589,
      "user": 1.6676140244444444,
      "system": 0.2473754044444444,
      "min": 1.4135869879,
      "max": 2.7121738219,
      "times": [
        2.7121738219,
        1.4817500469,
        1.4285540809,
        1.4135869879,
        2.0141991788999998,
        2.2985774359,
        1.4759376088999998,
        1.6377893159,
        1.5828631589
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.6544349447888889,
      "stddev": 0.5606681606712537,
      "median": 1.4218021359,
      "user": 1.5203441355555554,
      "system": 0.23894973777777778,
      "min": 1.0393971068999999,
      "max": 2.6782339179,
      "times": [
        2.0596764819,
        1.2533295948999998,
        1.0393971068999999,
        1.1803426238999999,
        1.2608120709,
        1.4218021359,
        1.7823670189,
        2.2139535519,
        2.6782339179
      ]
    },
    {
      "command": "pnpm@HEAD",
      "mean": 3.141099842677778,
      "stddev": 0.23989641034130216,
      "median": 3.0739700399,
      "user": 4.38040958,
      "system": 0.30714562666666667,
      "min": 2.8735771589,
      "max": 3.4609766059,
      "times": [
        3.1987918539,
        2.9149100819,
        3.4116880038999997,
        2.8939174179,
        3.0739700399,
        2.8735771589,
        3.0205091059,
        3.4215583159,
        3.4609766059
      ]
    }
  ]
}

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

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.531 ± 0.113 4.415 4.749 1.28 ± 0.05
pacquet@main 4.523 ± 0.114 4.419 4.799 1.28 ± 0.05
pnpr@HEAD 3.560 ± 0.117 3.442 3.821 1.01 ± 0.05
pnpr@main 3.528 ± 0.117 3.457 3.840 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.53135104302,
      "stddev": 0.11292030441555137,
      "median": 4.49636937912,
      "user": 1.8751786799999999,
      "system": 1.3526438199999997,
      "min": 4.41482521612,
      "max": 4.74879428212,
      "times": [
        4.64440570012,
        4.62086155812,
        4.53301469012,
        4.43801772112,
        4.44300859712,
        4.45972406812,
        4.43431995912,
        4.57653863812,
        4.41482521612,
        4.74879428212
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.522927483520001,
      "stddev": 0.11400992158171458,
      "median": 4.494829832620001,
      "user": 1.83061818,
      "system": 1.3893334199999998,
      "min": 4.41854584712,
      "max": 4.79939221612,
      "times": [
        4.41854584712,
        4.45529616812,
        4.53935679712,
        4.43709791412,
        4.43692360812,
        4.79939221612,
        4.59194597112,
        4.56105664812,
        4.52838907912,
        4.46127058612
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 3.5599209519199997,
      "stddev": 0.11709282149440342,
      "median": 3.53718107362,
      "user": 1.32582858,
      "system": 1.2451071199999997,
      "min": 3.4420068651199998,
      "max": 3.82066612912,
      "times": [
        3.58699583912,
        3.47047415212,
        3.56771455012,
        3.46281961712,
        3.6231866351199997,
        3.46868391312,
        3.82066612912,
        3.65001422112,
        3.4420068651199998,
        3.5066475971199997
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 3.5283977510199995,
      "stddev": 0.11715727956218251,
      "median": 3.4825108386199997,
      "user": 1.3259221799999998,
      "system": 1.2395063199999998,
      "min": 3.45703077012,
      "max": 3.84022204412,
      "times": [
        3.49333259312,
        3.45703077012,
        3.5962233171199998,
        3.46489779212,
        3.84022204412,
        3.4737532081199998,
        3.52833838412,
        3.47330910712,
        3.46560182512,
        3.49126846912
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13571
Testbedpacquet

🚨 1 Alert

BenchmarkMeasure
Units
ViewBenchmark Result
(Result Δ%)
Upper Boundary
(Limit %)
isolated-linker.peer-heavy-resolve.hot-cache.offlineLatency
seconds (s)
📈 plot
🚷 threshold
🚨 alert (🔔)
1.41 s
(+23.50%)Baseline: 1.14 s
1.37 s
(102.92%)

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,561.24 ms
(-3.45%)Baseline: 2,652.87 ms
3,183.44 ms
(80.45%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
1,724.72 ms
(-3.55%)Baseline: 1,788.13 ms
2,145.75 ms
(80.38%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
386.67 ms
(-13.14%)Baseline: 445.15 ms
534.18 ms
(72.39%)
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
175.34 ms
(-15.15%)Baseline: 206.64 ms
247.97 ms
(70.71%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
2,362.74 ms
(-2.05%)Baseline: 2,412.15 ms
2,894.57 ms
(81.63%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
4,414.83 ms
(-1.96%)Baseline: 4,503.12 ms
5,403.75 ms
(81.70%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
246.10 ms
(-9.39%)Baseline: 271.61 ms
325.93 ms
(75.51%)
isolated-linker.peer-heavy-resolve.hot-cache.offline📈 view plot
🚷 view threshold
🚨 view alert (🔔)
1,413.59 ms
(+23.50%)Baseline: 1,144.62 ms
1,373.54 ms
(102.92%)

🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Projectpnpm's project
Branchpr/13571
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,481.56 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
289.95 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
287.82 ms
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
⚠️ NO THRESHOLD
84.84 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
1,355.25 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
3,447.35 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
258.30 ms
🐰 View full continuous benchmarking report in Bencher

zkochan added 6 commits August 1, 2026 22:09
The peer-hoist discovery engine keeps one view of the workspace context
across every hoist round, refreshing it before each pass. That refresh
walked all three shared maps end to end — `children_by_id`, `packages`,
`dependencies_tree` — so every round cost one scan of the whole
workspace even when the round had added a handful of nodes. A resolve
of the 114-project Bit workspace from
https://github.com/pnpm/pnpm/issues/13505 runs 172 of those syncs in the
initial rounds alone, and each `extend_tree` bumps the revision that
triggers them.

Have the context record which keys of those maps each write touched, and
sync by visiting the keys written since the view's cursor. Only keys are
recorded, never values: the sync reads each key's current value, so a
key written several times, or written by concurrently-walking importers
in either order, converges on the same view — and a view rebuilt from
scratch replays the whole log, which visits every key ever written. The
merge itself is untouched, so an unmergeable change (a children-owner
handover that re-split a package's children and peers) still reports the
view stale and the engine still rebuilds.

On that workspace the initial rounds' sync time drops from 683ms to
215ms — the remainder is the three rebuilds, which replay the log — and
the hoist loop's from 30ms to 0.3ms, taking the two phases from 3.78s +
1.28s to 2.79s + 1.03s.

Related to https://github.com/pnpm/pnpm/issues/13505.
The equivalence assertion alone passes when both views are empty, which
is what a sync that observes no writes produces.

Related to https://github.com/pnpm/pnpm/issues/13505.
A `patch` run left `discovery.rs.orig` behind and it was committed with
the sync change. Nothing compiles or reads it.

Related to https://github.com/pnpm/pnpm/issues/13505.
A view discarded after an unmergeable change replayed the whole write
log to refill itself, which copies every key twice — once into the log
snapshot the sync reads from, once into the view. Scan the shared maps
instead, and take the cursor from the log's length *before* the scan, so
a write that lands mid-scan is either picked up here and replayed
harmlessly by the next sync, or missed here and applied by it.

The delta path is unchanged; only the from-scratch path stops going
through the log.

Related to https://github.com/pnpm/pnpm/issues/13505.
…lace

Returning the cursor let a caller drop it, which silently costs the
amortization: the next sync would start from zero and replay the whole
log. Take `&mut SyncCursor` like the incremental sync does, so there is
nothing to forget.

Related to https://github.com/pnpm/pnpm/issues/13505.
Rebuilds stopped replaying the write log when they started scanning the
shared maps; the cursor's doc still described the replay.

Related to https://github.com/pnpm/pnpm/issues/13505.
Copilot AI review requested due to automatic review settings August 1, 2026 20:13
@zkochan
zkochan force-pushed the amortize-initial-rounds branch from ddcaaf0 to c10cc96 Compare August 1, 2026 20:13

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Neither existing scenario runs the auto-install-peers loop: the
peer-heavy one hands every importer all the framework packages up front,
so no peer is ever missing and the loop converges in a single round with
one context sync. Anything that changes the cost of a hoist round is
therefore invisible to it — the write-log sync in this branch measures
identically on it, main and branch alike (~850ms either way).

Add a third scenario where the peers are not provided and the importers'
direct sets differ, so each importer hoists its own missing peers across
several rounds, extending the tree in between. It costs ~8x the
peer-heavy scenario (6.9s vs 0.9s) because the hoist loop dominates it,
which is what makes it a regression benchmark for that loop.

Related to https://github.com/pnpm/pnpm/issues/13505.
@qodo-code-review

Copy link
Copy Markdown

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

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

Copilot AI review requested due to automatic review settings August 1, 2026 20:22

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@qodo-code-review

Copy link
Copy Markdown

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

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

@zkochan

zkochan commented Aug 1, 2026

Copy link
Copy Markdown
Member Author

The Bencher alert on isolated-linker.peer-heavy-resolve.hot-cache.offline (+23.50%, 1,414 ms vs a 1,145 ms baseline) is noise, not this PR. Evidence rather than assertion:

  • The same job that produced the alert measured pacquet@main at min 1.039 s and pacquet@HEAD at min 1.414 s — but with σ of 0.46 s and 0.56 s on means of 1.78 s and 1.65 s. That is a ~30% coefficient of variation, so the minimum of nine is itself a noisy statistic here.
  • An earlier CI run of this identical code reported the opposite direction: HEAD min 0.970 s vs main min 1.267 s, i.e. the PR "23% faster". Same commit range, two runs apart.
  • A local 5-run A/B on this exact fixture, this branch's tip against 0d35c6cb01: min 1.074 s vs 1.061 s — 1.2% apart.
  • The in-repo workspace_full_resolution peer-heavy scenario, six interleaved runs: 850.7 ms on main vs 853.5 ms here.

Four measurements, no consistent direction, spread far exceeding any effect this PR could have on that fixture — which is expected, because the fixture cannot see this change at all: it resolves to 401 graph nodes (from the engine's own pacquet::install::phase events: "phase":"resolve_workspace","elapsed_ms":1200,"importers":41,"nodes":401), and the per-round sync cost this PR removes is proportional to graph size. There is nothing there to save.

I have not re-pushed to reroll the dice; that would just be gambling on the same distribution.

Separately, this is the concrete case for giving the resolver a scenario that can discriminate — I'm validating one now (its own DAG at ~5,000 nodes over 120 importers that each hoist their peers), and I will not propose it until it separates a build with this fix from one without.


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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants