Skip to content

Commit 9604b67

Browse files
committed
Speed up rescans of bun and yarn berry projects
A rescan of an already-patched project got about 20% slower on bun and yarn berry since early October. Most of it was work every scan repeats per pair: checking each patched package against every lock entry from other locks, rebuilding a canonical purl string for every crawled package several times over, keying every purl to look for PyPI spellings in projects with no PyPI pins, and re-reading every berry lock entry once per root `resolutions` selector. - The cross-lock contest looks up only the lock entries of the ref's own package, and each tree's wiring by tree. - canonical_base_purl returns an already canonical purl as is. - The PyPI-equivalence passes skip non-PyPI purls. - A berry lock builds its selector index once, on first use. Scan output is unchanged; the fast path is tested against the full rebuild. Refs #1606, #1607 Assisted-by: Claude Code:claude-opus-5-5
1 parent 90619d0 commit 9604b67

4 files changed

Lines changed: 187 additions & 47 deletions

File tree

‎crates/socket-patch-cli/src/commands/scan/mod.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,12 +104,15 @@ const BATCH_BODY_BYTE_CAP: usize = 256 * 1024;
104104
/// PEP 440 spellings of the same release (#604), deduplicated in order.
105105
fn with_pypi_equivalents(purls: &[String], lockfile_only: &HashSet<PurlKey>) -> Vec<String> {
106106
let mut out = purls.to_vec();
107-
let mut seen: HashSet<PurlKey> = purls.iter().map(|p| PurlKey::new(p)).collect();
107+
// Keyed only once some purl has an equivalent: most scans have no
108+
// PyPI pins, and keying every purl costs (#1606, #1607).
109+
let mut seen: Option<HashSet<PurlKey>> = None;
108110
for purl in purls {
109-
if !lockfile_only_contains(lockfile_only, purl) {
111+
if !is_pypi_purl(purl) || !lockfile_only_contains(lockfile_only, purl) {
110112
continue;
111113
}
112114
for spelling in socket_patch_core::utils::purl_key::pypi_equivalent_purls(purl) {
115+
let seen = seen.get_or_insert_with(|| purls.iter().map(|p| PurlKey::new(p)).collect());
113116
if seen.insert(PurlKey::new(&spelling)) {
114117
out.push(spelling);
115118
}
@@ -118,6 +121,14 @@ fn with_pypi_equivalents(purls: &[String], lockfile_only: &HashSet<PurlKey>) ->
118121
out
119122
}
120123

124+
/// Whether `purl` is a PyPI purl, in any case of its type (the spellings
125+
/// [`PurlKey`] folds together).
126+
fn is_pypi_purl(purl: &str) -> bool {
127+
purl.trim_start()
128+
.get(..9)
129+
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("pkg:pypi/"))
130+
}
131+
121132
/// Mark each API purl that names a lockfile-only PyPI pin under another
122133
/// PEP 440 spelling (`@1.16.0` for a lock's `@1.16`, #604) as lockfile-only
123134
/// too, so the `notInstalled` flag, the `[NOT INSTALLED]` marker and the
@@ -128,11 +139,14 @@ fn adopt_pypi_equivalents(
128139
scanned: &[String],
129140
lockfile_only: &mut HashSet<PurlKey>,
130141
) {
131-
let scanned_keys: HashSet<PurlKey> = scanned.iter().map(|p| PurlKey::new(p)).collect();
132142
let lock_only_pypi: Vec<&String> = scanned
133143
.iter()
134144
.filter(|p| p.starts_with("pkg:pypi/") && lockfile_only_contains(lockfile_only, p))
135145
.collect();
146+
if lock_only_pypi.is_empty() {
147+
return;
148+
}
149+
let scanned_keys: HashSet<PurlKey> = scanned.iter().map(|p| PurlKey::new(p)).collect();
136150
for pkg in packages {
137151
let key = PurlKey::new(&pkg.purl);
138152
if scanned_keys.contains(&key) {

‎crates/socket-patch-core/src/utils/purl_key.rs‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,31 @@ use crate::vendor::nuget_feed::normalize_nuget_version;
4949
/// release spellings still differ here; compare with [`PurlKey`], which
5050
/// folds them.
5151
pub fn canonical_base_purl(purl: &str) -> String {
52+
// Scans key thousands of crawled purls, nearly all already canonical:
53+
// skip the rebuild for those (#1606, #1607).
54+
if is_canonical_base(purl) {
55+
return purl.to_string();
56+
}
57+
rebuild_canonical_base_purl(purl)
58+
}
59+
60+
/// Whether [`canonical_base_purl`] would return `purl` unchanged: trimmed,
61+
/// no qualifiers, subpath or percent escapes, and a lowercase type whose
62+
/// names and versions keep their spelling.
63+
fn is_canonical_base(purl: &str) -> bool {
64+
if purl.trim().len() != purl.len() || purl.contains(['?', '#', '%']) {
65+
return false;
66+
}
67+
let Some((ty, _)) = purl
68+
.strip_prefix("pkg:")
69+
.and_then(|rest| rest.split_once('/'))
70+
else {
71+
return true;
72+
};
73+
!ty.bytes().any(|b| b.is_ascii_uppercase()) && !matches!(ty, "pypi" | "nuget" | "composer")
74+
}
75+
76+
fn rebuild_canonical_base_purl(purl: &str) -> String {
5277
let base = normalize_purl(strip_purl_qualifiers(purl.trim())).into_owned();
5378
let Some(rest) = base.strip_prefix("pkg:") else {
5479
return base;
@@ -219,6 +244,39 @@ mod tests {
219244
use super::*;
220245
use crate::utils::composer_version::composer_versions_equivalent;
221246

247+
#[test]
248+
fn canonical_fast_path_matches_the_rebuild() {
249+
for purl in [
250+
"pkg:npm/left-pad@1.3.0",
251+
"pkg:npm/@scope/name@1.0.0",
252+
"pkg:npm/%40scope/name@1.0.0",
253+
"pkg:NPM/left-pad@1.3.0",
254+
"pkg:Npm/left-pad@1.3.0",
255+
" pkg:npm/left-pad@1.3.0",
256+
"pkg:npm/left-pad@1.3.0\n",
257+
"pkg:npm/left-pad@1.3.0?vcs_url=x",
258+
"pkg:golang/github.com/Foo/Bar@v1.0.0#cmd/tool",
259+
"pkg:pypi/Six@1.16",
260+
"pkg:PyPI/six@1.16",
261+
"pkg:nuget/Newtonsoft.Json@13.0.3",
262+
"pkg:composer/Vendor/Name@v1.0",
263+
"pkg:maven/org.Example/Lib@1.0",
264+
"pkg:gem/nokogiri@1.16.5",
265+
"pkg:cargo/serde@1.0.0",
266+
"pkg:npm/no-version",
267+
"pkg:npm/@scope",
268+
"pkg:npm",
269+
"not-a-purl",
270+
"",
271+
] {
272+
assert_eq!(
273+
canonical_base_purl(purl),
274+
rebuild_canonical_base_purl(purl),
275+
"{purl:?}"
276+
);
277+
}
278+
}
279+
222280
#[test]
223281
fn canonical_base_purl_folds_only_insensitive_ecosystems() {
224282
assert_eq!(

‎crates/socket-patch-core/src/vendor/lock_inventory/yarn.rs‎

Lines changed: 68 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
//! `yarn.lock`, classic and berry: the entry models lockfile discovery
22
//! shares ([`classic_entries`], [`berry_entries`]) and the registry views.
33
4+
use std::collections::HashSet;
45
#[cfg(test)]
56
use std::path::Path;
7+
use std::sync::OnceLock;
68

79
use crate::formats::yarn::blocks::{
810
berry_field, classic_field, live_blocks, scan_blocks, LockBlock,
@@ -74,6 +76,56 @@ pub(crate) struct BerryLock {
7476
pub(crate) cache_key: Option<String>,
7577
/// Every block except the exact `__metadata` one, in lock order.
7678
pub(crate) entries: Vec<YarnEntry>,
79+
/// What [`berry_selector_routes_nothing`] asks of the live entries,
80+
/// built on its first call.
81+
selector_index: OnceLock<SelectorIndex>,
82+
}
83+
84+
/// The live entries of a [`BerryLock`] as [`berry_selector_routes_nothing`]
85+
/// reads them, collected once per lock instead of once per selector
86+
/// (#1607).
87+
#[derive(Default)]
88+
struct SelectorIndex {
89+
/// Every url a live entry resolves: its locator's reference, and an
90+
/// older pin's `__archiveUrl=` binding as written and percent-decoded.
91+
urls: HashSet<String>,
92+
/// The package names live entries are keyed by.
93+
names: HashSet<String>,
94+
/// `(name, descriptor)` of every live entry pattern, plus the
95+
/// descriptor without its `npm:` protocol.
96+
descriptors: HashSet<(String, String)>,
97+
}
98+
99+
impl SelectorIndex {
100+
fn new(entries: &[YarnEntry]) -> Self {
101+
let mut index = Self::default();
102+
for entry in entries.iter().filter(|e| e.live) {
103+
if let Some(locator) = entry.locator() {
104+
index.urls.insert(locator.reference.to_string());
105+
if let Some(archive) = locator.archive_url() {
106+
index.urls.insert(archive.to_string());
107+
index.urls.insert(
108+
crate::utils::purl::percent_decode_purl_component(archive).into_owned(),
109+
);
110+
}
111+
}
112+
for pattern in &entry.patterns {
113+
let Some((name, descriptor)) = split_pattern(pattern) else {
114+
continue;
115+
};
116+
index.names.insert(name.to_string());
117+
index
118+
.descriptors
119+
.insert((name.to_string(), descriptor.to_string()));
120+
if let Some(bare) = descriptor.strip_prefix("npm:") {
121+
index
122+
.descriptors
123+
.insert((name.to_string(), bare.to_string()));
124+
}
125+
}
126+
}
127+
index
128+
}
77129
}
78130

79131
/// A berry (yarn 2+) `yarn.lock` text — berry reuses the classic block
@@ -84,7 +136,11 @@ pub(crate) fn berry_entries(text: &str) -> BerryLock {
84136
let cache_key = crate::formats::yarn::berry_gates::cache_key(&blocks).map(str::to_string);
85137
let mut entries = yarn_entries(blocks, split_berry_key_patterns);
86138
entries.retain(|e| e.block.key != "__metadata");
87-
BerryLock { cache_key, entries }
139+
BerryLock {
140+
cache_key,
141+
entries,
142+
selector_index: OnceLock::new(),
143+
}
88144
}
89145

90146
/// Whether a root `package.json` `resolutions` selector routing to the
@@ -108,35 +164,18 @@ pub(crate) fn berry_selector_routes_nothing(lock: &BerryLock, selector: &str, ur
108164
.map(|i| &selector[i..])
109165
.unwrap_or(target);
110166
let range = split_pattern(last).map(|(_, range)| range);
111-
for entry in lock.entries.iter().filter(|e| e.live) {
112-
if let Some(locator) = entry.locator() {
113-
if locator.reference == url
114-
|| locator.archive_url().is_some_and(|archive| {
115-
archive == url
116-
|| crate::utils::purl::percent_decode_purl_component(archive) == url
117-
})
118-
{
119-
return false;
120-
}
121-
}
122-
for pattern in &entry.patterns {
123-
let Some((name, descriptor)) = split_pattern(pattern) else {
124-
continue;
125-
};
126-
if name != target {
127-
continue;
128-
}
129-
match range {
130-
None => return false,
131-
Some(want) => {
132-
if descriptor == want || descriptor.strip_prefix("npm:") == Some(want) {
133-
return false;
134-
}
135-
}
136-
}
137-
}
167+
let index = lock
168+
.selector_index
169+
.get_or_init(|| SelectorIndex::new(&lock.entries));
170+
if index.urls.contains(url) {
171+
return false;
172+
}
173+
match range {
174+
None => !index.names.contains(target),
175+
Some(want) => !index
176+
.descriptors
177+
.contains(&(target.to_string(), want.to_string())),
138178
}
139-
true
140179
}
141180

142181
/// A berry `checksum:` value as the pin yarn enforces: `<cacheKey>/<hex>`,

‎crates/socket-patch-core/src/vex/discover/mod.rs‎

Lines changed: 44 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1128,27 +1128,56 @@ impl Discovery {
11281128
/// pin of the same version in `requirements.txt` and its `-r` includes
11291129
/// to the reference (#1086).
11301130
fn contest_across_locks(&mut self) {
1131-
let wiring: BTreeSet<(String, PathBuf)> = self
1132-
.refs
1133-
.iter()
1134-
.map(|r| (r.purl.clone(), self.tree_of(&r.source_file).to_path_buf()))
1135-
.collect();
1131+
// The purls each install tree wires.
1132+
let mut wiring: BTreeMap<PathBuf, BTreeSet<String>> = BTreeMap::new();
1133+
for r in &self.refs {
1134+
wiring
1135+
.entry(self.tree_of(&r.source_file).to_path_buf())
1136+
.or_default()
1137+
.insert(r.purl.clone());
1138+
}
1139+
// Every entry a ref's purl can match ([`ResolvedElsewhere::covers`])
1140+
// is spelled either as that purl or as its versionless name, and a
1141+
// PyPI release match shares the name too. Index the entries under
1142+
// both spellings so each ref checks only its own package's entries
1143+
// instead of every entry of every lock (#1606, #1607).
1144+
let mut by_key: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
1145+
for (i, e) in self.elsewhere.iter().enumerate() {
1146+
by_key.entry(e.purl.as_str()).or_default().push(i);
1147+
if let Some(name) = purl_without_version(&e.purl) {
1148+
by_key.entry(name).or_default().push(i);
1149+
}
1150+
}
11361151
let mut contested = Vec::new();
11371152
let refs = std::mem::take(&mut self.refs);
11381153
for r in refs {
11391154
let other = (!is_script_lock(&r.source_file))
11401155
.then(|| {
11411156
let tree = self.tree_of(&r.source_file);
1142-
self.elsewhere.iter().find(|e| {
1143-
let other = self.tree_of(&e.file);
1144-
// A tree that wires the release itself, in any
1145-
// spelling, is no contester.
1146-
e.covers(&r.purl)
1147-
&& other != tree
1148-
&& !wiring.iter().any(|(purl, t)| {
1149-
t == other && (*purl == r.purl || same_pypi_release(purl, &r.purl))
1150-
})
1151-
})
1157+
let mut candidates: Vec<usize> =
1158+
[Some(r.purl.as_str()), purl_without_version(&r.purl)]
1159+
.into_iter()
1160+
.flatten()
1161+
.filter_map(|k| by_key.get(k))
1162+
.flatten()
1163+
.copied()
1164+
.collect();
1165+
candidates.sort_unstable();
1166+
candidates.dedup();
1167+
candidates
1168+
.into_iter()
1169+
.map(|i| &self.elsewhere[i])
1170+
.find(|e| {
1171+
let other = self.tree_of(&e.file);
1172+
// A tree that wires the release itself, in any
1173+
// spelling, is no contester.
1174+
e.covers(&r.purl)
1175+
&& other != tree
1176+
&& !wiring.get(other).is_some_and(|purls| {
1177+
purls.contains(&r.purl)
1178+
|| purls.iter().any(|purl| same_pypi_release(purl, &r.purl))
1179+
})
1180+
})
11521181
})
11531182
.flatten();
11541183
match other {

0 commit comments

Comments
 (0)