Skip to content

Parse Cargo.lock once in a hosted Cargo scan (#761) - #2138

Merged
Mikola Lysenko (mikolalysenko) merged 3 commits into
mainfrom
perf/cargo-hosted-lock-parse-once
Nov 18, 2026
Merged

Mikola Lysenko (mikolalysenko) merged 3 commits into
mainfrom
perf/cargo-hosted-lock-parse-once

Conversation

@mikolalysenko

@mikolalysenko Mikola Lysenko (mikolalysenko) commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #761.

Problem

scan --mode hosted on a Cargo project parsed Cargo.lock several times for every patched crate: for the other-versions probe, for the dependents check, for the override check and the plan, and again on the refusal paths. Each parse reads the whole lock, by then partly rewritten. #761 measured it at 79% of the instructions of a hosted scan on the benchmark fixture (600 crates, 15 patched).

Fix

The rewrite holds the lock in one CargoHostedLock (formats/cargo/hosted.rs): the text, one parse of it made on first use, and the repoints committed so far as splices into that text. The splices are applied once, when the rewrite ends.

The probes and the plans have to answer as a fresh parse of the lock as rewritten so far would. Three rules keep that:

  • A repoint that only replaces the block's source and checksum values writes the two into the model. That is every repoint of a registry crate in a lock in the format cargo has written since 1.41, unless a dependent names the package by its full id (cargo spells it that way when a name and version are ambiguous).
  • Any other repoint (a line added to the block, a v1 lock's [metadata] line, a full id in another block) is applied to the text at once, and the text is parsed again on its next use.
  • A plan is made on a fresh parse when the bytes it would read have moved: for a package this rewrite has already repointed, and for a rewrite with a splice that touches a pending one.

A rewrite that never reads the lock does not parse it: an offline-source refusal, a floor refusal, an invalid override.

plan returns the repoint as a value that holds the lock until it is committed or dropped, so no other plan can come between the two. Committing it returns the edits to record, so no edit is recorded for a repoint that was not made.

Result

sp-bench compare on the benchmark fixture (600 crates, 15 patched), perf profile, on an arm64 Mac. Head is this branch at c6f144325. Base is the rewrite as it was at 59823ff46, one commit before the branch's base; the commit between them (#2100) touches no Cargo code.

scenario base wall head wall Δ wall [95% CI] Δ CPU Δ peak RSS
cargo/hosted 131.7 ms 77.4 ms -41.5% [-43.5, -40.5] -48.5% -2.8%
cargo/rescan 106.0 ms 50.8 ms -51.9% [-53.1, -50.6] -51.5% +0.2%

A second run gave -42.4% and -51.0%.

What is left of the lock in a hosted scan is the inventory's own parse (formats::cargo::read_packages, 12% in #761's profile), which this does not touch. A v1 lock, a lock where dependents name the patched crates by full id, and a block that gets a source or checksum line it did not have are parsed once per such repoint, where they were parsed several times.

No behaviour change intended

  • a_rewrite_on_one_parse_matches_the_crate_by_crate_rewrite runs seeded locks through runs of up to eight repoints, with repeats, re-pins to a second index, absent crates and dropped plans. At every step it compares the whole model, what the probes read, the plan and its edits with a fresh parse of the text the crate-by-crate rewrite has at that point, and at the end the text. The locks are 600 from the existing generator (v1 and v3/v4, with its hostile shapes), 1,500 from a new one whose full ids name the lock's own packages (twins, packages already at a hosted index, stray ids, stray [metadata] lines), and the hand-written ones.
  • Each rule is needed for those tests to pass. I took each out in turn, and every time a test fails: the fresh parse for an already-repointed package, the parse after a repoint that reaches outside its block, the parse after a repoint that adds a line to its block, the overlap rule, and the checksum written into the model.
  • cargo_rewrite_order_tests holds two rewrites where a later crate's refusal depends on what an earlier one did to the lock. They pass on the rewrite as it was (I ran them against the three changed files at 59823ff46) and on this branch.
  • The rewrite golden (redirect_golden), the restore golden (upstream_restore_golden) and the per-plan goldens (span_splice_matches_golden_*) pass unchanged.
  • a_rewrite_parses_the_lock_once pins the count on the lock holder: one parse for 29 repoints of a 200-crate lock, one for a re-run that mixes repoints with crates already at their index, two when one package is planned twice.
  • the_rewrite_parses_the_lock_once pins it through the Cargo rewrite itself, by counting CargoLock::parse: one parse for four repoints, none for a rewrite refused before it reads the lock.

Review

/code-review high ran three times: on the first version (ten findings), on the rework that followed (nine), and on this PR as opened (eight, none on a lock cargo writes). The fixes for the third round were not reviewed again. The tests above are what checks them.

Fixed from the first round:

  • Two probes read the parse as it was before an earlier repoint of the same run. A block with no source that a first crate's pin gave one was still read as a path package by the dependents check of a second crate, and the override check of a crate named by two patches read its source as still crates.io. Tests: the two in cargo_rewrite_order_tests.
  • A re-run that mixes new and already-pinned crates parsed once per already-pinned crate. An answer that is no rewrite is kept unless this run repointed that same package.
  • commit took any splices. It takes the repoint plan returned, which only plan can make.
  • The lock was parsed before gates that refuse without reading it. It is parsed on first use.
  • Option<&CargoLock> meant two things in the dependents check. It takes the lock holder.
  • The test-only mirror of the plan type, a name shared with vlt's HostedLock, and two doc links to a function that had become test-only.

Fixed from the second round:

  • A repoint that left the lock unreadable no longer stopped the crates after it. A v1 lock with a stray [metadata] line for the id the repoint gives the package ends up with a duplicate key. Every crate used to parse the lock, so the next one was refused. On one parse the crates after it were repointed on a lock cargo cannot read. A repoint that reaches outside its block now parses the lock again.
  • A package planned twice could be planned on the bytes as first parsed. The check only looked for a splice that touched a pending one, and a second plan can miss them all. Every answer for a package repointed since the parse is made on a fresh parse.
  • The model kept the old checksum and the old full ids of a repointed package. No probe read them yet. A block-only repoint now writes the checksum too, and any other repoint parses again.
  • plan and commit were tied by a hidden field, and the edits went to the caller before the repoint was made.
  • The sweep's full ids named no package of the lock, so it almost never rewrote a reference. See the 1,500 locks above.
  • Two parallel outcome enums with a hand-written mapping (now one generic enum), a doc link to a type that does not exist, and strings cloned per plan (the lock keeps package indices).

Fixed from the third round:

  • commit did nothing, silently, for a plan made before the lock's latest one, while the caller had already written the manifest and the config and went on to count the patch as pinned. Nothing reached it, but nothing ruled it out. A planned repoint now borrows the lock, so the compiler rules it out.
  • A repoint that adds a line to its block could leave a lock that no longer parses, with the crates after it still repointed. It takes a block whose checksum or source is a table, which cargo never writes. A repoint is kept on the held parse only when it replaces the two values where they stand. Test: the second lock in a_lock_a_repoint_leaves_unreadable_refuses_the_crates_after_it.
  • "A rewrite that never reads the lock does not parse it" was pinned on the holder only, where it is true by construction. See the_rewrite_parses_the_lock_once.
  • The sweep compared four projections of the model, so the checksum commit writes was unchecked. It compares the whole model.
  • A plan made and thrown away for a package already repointed (the check comes first now), and splice copying the text and shifting its tail once per splice (one pass now).

Not fixed:

  • cargo_unpinnable_dependents takes the lock holder while the other probes take Option<&CargoLock>. The first round asked for this: with the Option, None meant both "no lock" and "a lock that does not parse".
  • CargoHostedLock and pnpm's PnpmLockState are two holders of a text and its pending splices, and the restore path has a splice loop of its own. Folding them into one touches pnpm's hosted planner and the Cargo restore, which this PR leaves alone, and the Cargo holder also keeps a parsed model in step, which pnpm's does not have. That is a refactor for a PR of its own.

Testing

  • cargo test -p socket-patch-core --lib: 7,908 passed.
  • CLI suites in_process_redirect, hosted_memory_engine, mode_migration_cargo, e2e_vex_redirect, scan, rollback: 638 passed.
  • Goldens: redirect_golden (1) and upstream_restore_golden (62) pass.
  • Real cargo: e2e_redirect_cargo_shapes (15) and e2e_redirect_cargo_build (3) pass.
  • cargo fmt --check and cargo clippy --locked --workspace --all-features -- -D warnings are clean.
  • cargo doc --document-private-items reports no unresolved link in the files this PR touches.
  • All of the above ran on c6f144325. After merging main into the branch I re-ran only the Cargo lock, VEX discovery and vendor test groups of the core crate (317 passed).

🤖 Generated with Claude Code

The hosted Cargo rewrite parsed Cargo.lock several times for every
patched crate: for the other-versions probe, the dependents check,
the override check and the plan, each time over the whole lock as
rewritten so far. #761 measured that at 79% of the instructions of a
hosted scan of a 600-crate project with 15 patches.

The rewrite now holds the lock in one CargoHostedLock: the text, one
parse of it made on first use, and the repoints committed so far as
splices into that text, applied once when the rewrite ends. Its
probes and plans answer as a fresh parse of the lock as rewritten so
far would:

- A repoint that changes only the package's own block writes the new
  source and checksum into the model. That is every repoint of a lock
  in the format cargo has written since 1.41, unless a dependent
  names the package by its full id.
- Any other repoint (a v1 lock's [metadata] line, a full id in
  another block) is applied to the text at once, and the text is
  parsed again on its next use.
- A plan is made on a fresh parse when the bytes it would read have
  moved: for a package this rewrite has already repointed, and for a
  rewrite with a splice that touches a pending one.

A rewrite that never reads the lock does not parse it. plan() gives
the repoint as a value and commit() takes it and returns its edits,
so no edit is recorded for a repoint that was not made.

No behaviour change intended. A seeded sweep compares every plan,
edit, probe answer and final text with the crate-by-crate rewrite,
and two order tests cover a later crate whose refusal depends on an
earlier repoint; both pass on the old rewrite too.

Closes #761.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@cursor

cursor Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

PR Summary

Medium Risk
Hosted redirect behavior hinges on subtle parse/splice timing for dependents, twins, and v1 metadata; regressions would break --locked graphs or skip/warn incorrectly, though heavy equivalence tests mitigate this.

Overview
Introduces CargoHostedLock so hosted Cargo rewrites keep one lazy parse of Cargo.lock, batch repoints as non-overlapping byte splices, and apply them at the end—replacing per-crate repeated parses and full-text rewrites.

plan_hosted becomes plan_hosted_splices, returning CargoLockOutcome<RepointSplices> (generic outcome + PlannedRepoint with plan stamps). plan / commit separate planning from recording edits; stale plans are ignored. Refresh rules keep probe/plan answers aligned with a fresh parse: in-place model updates for block-local repoints, immediate re-parse for v1 metadata / full-id edits, and re-parse when spans overlap pending splices or a package is replanned.

The hosted redirect path wires probes through CargoHostedLock::model() instead of re-parsing lock strings. New equivalence and order tests assert byte-for-byte parity with the old crate-by-crate behavior and ~40–50% benchmark wins on large hosted scans (#761).

Reviewed by Cursor Bugbot for commit 6b436a9. Configure here.

@mikolalysenko

Copy link
Copy Markdown
Collaborator Author

[agent] PR shepherd: review brief for the approver

What it does
A hosted Cargo scan used to re-parse Cargo.lock several times for every patched crate. This PR holds the lock in one CargoHostedLock with a single lazy parse. Committed repoints are kept as pending splices and applied when the rewrite ends. On the bench fixture the change is about 40–50% faster, and no behaviour change is intended.

Risk: medium. This is the core hosted Cargo rewrite path, and the cached model has to match what a fresh parse of the partly rewritten lock would give. The PR handles that conservatively: a block-only ("local") repoint updates the cached source and checksum. Anything else forces a re-parse: a v1 [metadata] line, a full-id reference, re-planning an already-repointed package, or a splice touching a pending one. A randomized equivalence sweep compares every step against the crate-by-crate rewrite. Real-cargo e2e tests are green.

Look here

  • hosted.rs:212: when a repoint counts as local
  • [hosted.rs:413-470](https://github.com/SocketDev/socket-patch/blob/6b436a93e3530f423263e891193f6a44eec9c7a4/crates/socket-patch-core/src/formats/cargo/hosted.rs#L413-L470): plan and as_a_fresh_parse_would, the re-parse triggers
  • hosted.rs:483: commit (a stale plan records nothing; the in-model update happens only for local repoints)
  • [redirect/mod.rs:2268-2346](https://github.com/SocketDev/socket-patch/blob/6b436a93e3530f423263e891193f6a44eec9c7a4/crates/socket-patch-core/src/patch/redirect/mod.rs#L2268-L2346): the caller, plan → commit → into_text
  • [cargo_lock_equivalence_tests.rs:427](https://github.com/SocketDev/socket-patch/blob/6b436a93e3530f423263e891193f6a44eec9c7a4/crates/socket-patch-core/src/patch/redirect/cargo_lock_equivalence_tests.rs#L427): the equivalence sweep

Verified

  • I read the whole diff (5 files, all in socket-patch-core).
  • The cached LockedPackage fields that a local repoint can change are source and checksum, and both are updated. dependencies and replace are untouched by a block-only repoint.
  • Splices into the original text stay valid because the text is only spliced on re-parse or at the end.
  • lock_changed is equivalent to before, since a Rewritten plan always carries edits.
  • No CHANGELOG.md change, no debug leftovers, and no skipped or ignored tests.
  • I ran cargo test -p socket-patch-core --lib -- cargo on the head: 553 passed, 0 failed.
  • CI on the head is green, including ci-ok, clippy, the real-cargo cargo 1.93.1 lock-v4 job, hosted-e2e and coverage. Bugbot is clean and there are no review threads.

Changes I made: none.

Open questions: none blocking. The author left one asymmetry on purpose: cargo_unpinnable_dependents takes the lock holder while the other probes take Option<&CargoLock>. The description explains why.


Generated by Claude Code

@mikolalysenko Mikola Lysenko (mikolalysenko) added the Ready for review Agent-verified: mergeable, CI green, Bugbot clean — awaiting human review label Nov 18, 2026
Third review round of the one-parse rewrite.

- A planned repoint borrows the lock until it is committed or
  dropped, so no plan can come between the two and a commit cannot be
  stale. It had a silent no-op path for that case.
- A repoint is kept on the held parse only when it replaces the
  block's source and checksum values where they stand. One that adds
  a line can collide with a key that is a table and leave a lock that
  does not parse. That one is applied and parsed again, so the crates
  after it are refused as they were.
- A package's earlier repoint is checked before its plan is made, not
  after.
- splice() builds the text in one pass.

Tests: the sweep compares the whole model at every step, and a count
of CargoLock::parse pins one parse through the Cargo rewrite itself
and none for a rewrite refused before it reads the lock.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Merged via the queue into main with commit 1d3b443 Nov 18, 2026
50 checks passed
@mikolalysenko
Mikola Lysenko (mikolalysenko) deleted the perf/cargo-hosted-lock-parse-once branch November 18, 2026 23:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Ready for review Agent-verified: mergeable, CI green, Bugbot clean — awaiting human review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Slow scan: cargo hosted 3.8x median ms/pkg (per-patch Cargo.lock re-parse)

2 participants