Skip to content

Commit 85a011b

Browse files
Fix rollback reinstall note for vendored gems (#2214) (#2215)
* Start fix for rollback note on vendored gems Refs #2214. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011f9aeQWcPFYLN6RCQyh8RM * Skip rollback note for an upstream gem install A gem that was only ever vendored has no patched byte in a gem home: Bundler loaded it from .socket/vendor. Rollback counted it as keeping its patched bytes anyway, because only a refreshed or in-place-restored copy was left out, and --json pushed reinstall_required whenever anything was unwired. The vendored gem unwind now reports the gems whose installed copies are proven to be the upstream build (the archive in the gem home has the verified upstream sha256 and no recorded patch is in the files) or that are not installed. Rollback leaves them out, and derives the --json warning from the same count as the human note. Fixes #2214. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011f9aeQWcPFYLN6RCQyh8RM * Require proof before dropping the gem note Review found the first cut too generous: a copy agent mode patched in place sits beside the upstream archive, a gem with no copy found may live in a gem home this run cannot see, and a partly patched copy does not hold the whole patch. A vendored gem is now left out of rollback's reinstall count only when it has an installed copy and every copy is proven upstream: its archive has the verified upstream sha256 and every file of the gem's ledger record is in its pre-patch state. Refs #2214. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011f9aeQWcPFYLN6RCQyh8RM * Pin the rollback note with a real Bundler The get-vendored capstone installs rack with a real Bundler and vendors it through a detached ledger entry. Roll it back at the end: the pair is restored byte for byte, Bundler's own install was upstream all along, and no reinstall_required warning is raised. Refs #2214. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011f9aeQWcPFYLN6RCQyh8RM * Count an added file that is present as patched verify_file_patch says Ready for a file the patch adds when it is there with other content, since apply overwrites it. For the proof that an installed gem never got its patch, only the file's absence counts. Refs #2214. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011f9aeQWcPFYLN6RCQyh8RM --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 74b3306 commit 85a011b

7 files changed

Lines changed: 439 additions & 72 deletions

File tree

‎crates/socket-patch-cli/CLI_CONTRACT.md‎

Lines changed: 2 additions & 2 deletions
Large diffs are not rendered by default.

‎crates/socket-patch-cli/src/commands/gem_refresh.rs‎

Lines changed: 155 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1039,6 +1039,12 @@ pub(crate) struct RestoreRefresh {
10391039
/// be) with none left on the patched build: nothing of theirs is left
10401040
/// for a reinstall.
10411041
pub(crate) refreshed_installs: BTreeSet<String>,
1042+
/// The upstream sha256 the refresh verified for each build it judged,
1043+
/// by leaf.
1044+
upstream_sha256: BTreeMap<String, String>,
1045+
/// A vendored unwind's gems whose installed copies are all proven to
1046+
/// be the upstream build ([`upstream_installs`]).
1047+
pub(crate) upstream_installs: BTreeSet<String>,
10421048
}
10431049

10441050
/// After a hosted unwind restored the gems of `pins` to their upstream
@@ -1240,6 +1246,7 @@ pub(crate) async fn after_vendored_unwind(
12401246
common: &GlobalArgs,
12411247
unwound: &[String],
12421248
records: &BTreeMap<String, PatchRecord>,
1249+
ledger: &BTreeMap<String, PatchRecord>,
12431250
) -> RestoreRefresh {
12441251
use socket_patch_core::patch::redirect::upstream::gem_upstream;
12451252

@@ -1250,24 +1257,89 @@ pub(crate) async fn after_vendored_unwind(
12501257
// lock asks no registry.
12511258
let lock = gem_upstream(&common.cwd, &BTreeMap::new(), true).await;
12521259
let builds = build_leaves(&named_builds(&lock, unwound), |_| true);
1253-
for copy in installed_builds(common, &builds).await {
1254-
if copy.archive.is_file() || holds_patch(&copy, records).await {
1255-
installed.insert(copy.purl);
1260+
let copies = installed_builds(common, &builds).await;
1261+
for copy in &copies {
1262+
if copy.archive.is_file() || holds_patch(copy, records).await {
1263+
installed.insert(copy.purl.clone());
12561264
}
12571265
}
1258-
if installed.is_empty() {
1259-
return RestoreRefresh::default();
1266+
let mut refresh = if installed.is_empty() {
1267+
RestoreRefresh::default()
1268+
} else {
1269+
let installed: Vec<String> = installed.into_iter().collect();
1270+
refresh_restored(
1271+
common,
1272+
&installed,
1273+
&BTreeMap::new(),
1274+
records,
1275+
None,
1276+
Scope::Installed,
1277+
)
1278+
.await
1279+
};
1280+
refresh.upstream_installs =
1281+
upstream_installs(unwound, &copies, &refresh.upstream_sha256, ledger).await;
1282+
refresh
1283+
}
1284+
1285+
/// The gems of `unwound` whose installed copies are proven to hold no
1286+
/// patched byte once the refresh ran (#2214): vendoring never wrote to a
1287+
/// gem home, so a gem that was only ever vendored is one of them.
1288+
/// `copies` is every installed copy of their builds. A gem is listed when
1289+
/// it has an installed copy and each one is proven to be the upstream
1290+
/// build twice over: the archive RubyGems installed it from hashes to the
1291+
/// build's verified upstream sha256 (`upstream`, by leaf), and every file
1292+
/// of the gem's ledger record (`ledger`, by purl) is in its pre-patch
1293+
/// state there. Anything short of that keeps the gem out: no copy found
1294+
/// (the gem home may be one this run cannot see), no verified sha256, an
1295+
/// unreadable archive, no record, a file that is patched, edited or
1296+
/// unreadable.
1297+
async fn upstream_installs(
1298+
unwound: &[String],
1299+
copies: &[InstalledCopy],
1300+
upstream: &BTreeMap<String, String>,
1301+
ledger: &BTreeMap<String, PatchRecord>,
1302+
) -> BTreeSet<String> {
1303+
use socket_patch_core::vendor::file_sha256_hex;
1304+
1305+
let mut proven: BTreeMap<&str, bool> = BTreeMap::new();
1306+
for copy in copies {
1307+
let is_upstream = match (upstream.get(&copy.leaf), ledger.get(&copy.purl)) {
1308+
(Some(sha), Some(record)) => {
1309+
file_sha256_hex(&copy.archive).await.as_ref() == Some(sha)
1310+
&& is_unpatched(&copy.dir, record).await
1311+
}
1312+
_ => false,
1313+
};
1314+
*proven.entry(copy.purl.as_str()).or_insert(true) &= is_upstream;
12601315
}
1261-
let installed: Vec<String> = installed.into_iter().collect();
1262-
refresh_restored(
1263-
common,
1264-
&installed,
1265-
&BTreeMap::new(),
1266-
records,
1267-
None,
1268-
Scope::Installed,
1269-
)
1270-
.await
1316+
unwound
1317+
.iter()
1318+
.filter(|purl| proven.get(purl.as_str()) == Some(&true))
1319+
.cloned()
1320+
.collect()
1321+
}
1322+
1323+
/// Whether every file `record` lists is in its pre-patch state in the
1324+
/// installed gem `dir`: it hashes to its `beforeHash`, or the patch adds
1325+
/// it and it is not there. A record that lists no file proves nothing.
1326+
async fn is_unpatched(dir: &Path, record: &PatchRecord) -> bool {
1327+
use socket_patch_core::patch::apply::{verify_file_patch, VerifyStatus};
1328+
1329+
if record.files.is_empty() {
1330+
return false;
1331+
}
1332+
for (name, info) in &record.files {
1333+
let verified = verify_file_patch(dir, name, info).await;
1334+
// `Ready` also covers a file the patch adds that is there with
1335+
// other content (apply overwrites it): only its absence proves
1336+
// the copy never got it.
1337+
let added_but_present = info.before_hash.is_empty() && verified.current_hash.is_some();
1338+
if verified.status != VerifyStatus::Ready || added_but_present {
1339+
return false;
1340+
}
1341+
}
1342+
true
12711343
}
12721344

12731345
/// The builds of each gem of `gems` that are this project's: the ones the
@@ -1440,8 +1512,15 @@ async fn refresh_restored(
14401512
Scope::Installed,
14411513
)
14421514
.await;
1515+
let upstream_sha256: BTreeMap<String, String> = shas
1516+
.iter()
1517+
.filter_map(|(leaf, build)| Some((leaf.clone(), build.sha256.clone()?)))
1518+
.collect();
14431519
if stale.is_empty() && unchecked.is_empty() && no_record.is_empty() {
1444-
return RestoreRefresh::default();
1520+
return RestoreRefresh {
1521+
upstream_sha256,
1522+
..RestoreRefresh::default()
1523+
};
14451524
}
14461525
let wanted = |gem: &StaleGem| {
14471526
Some(Wanted {
@@ -1499,6 +1578,8 @@ async fn refresh_restored(
14991578
}
15001579
RestoreRefresh {
15011580
refreshed_installs,
1581+
upstream_sha256,
1582+
upstream_installs: BTreeSet::new(),
15021583
report: report(direction, &installed, &pass, &policy),
15031584
replaced_archives: if policy.dry_run {
15041585
Vec::new()
@@ -1512,6 +1593,64 @@ async fn refresh_restored(
15121593
mod tests {
15131594
use super::*;
15141595

1596+
/// #2214: what proves an installed gem never got its patch. Each record
1597+
/// file is at its `beforeHash`, or the patch adds it and it is absent.
1598+
#[tokio::test]
1599+
async fn is_unpatched_needs_every_record_file_in_its_pre_patch_state() {
1600+
use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes as hash;
1601+
use socket_patch_core::manifest::schema::PatchFileInfo;
1602+
1603+
let record = |files: &[(&str, &[u8], &[u8])]| PatchRecord {
1604+
uuid: "u".into(),
1605+
exported_at: String::new(),
1606+
files: files
1607+
.iter()
1608+
.map(|(name, before, after)| {
1609+
let info = PatchFileInfo {
1610+
before_hash: if before.is_empty() {
1611+
String::new()
1612+
} else {
1613+
hash(before)
1614+
},
1615+
after_hash: hash(after),
1616+
};
1617+
(name.to_string(), info)
1618+
})
1619+
.collect(),
1620+
vulnerabilities: Default::default(),
1621+
description: String::new(),
1622+
license: String::new(),
1623+
tier: String::new(),
1624+
};
1625+
let tmp = tempfile::tempdir().unwrap();
1626+
let dir = tmp.path();
1627+
std::fs::write(dir.join("a.rb"), b"before").unwrap();
1628+
let changed = record(&[("a.rb", b"before", b"after")]);
1629+
let with_added = record(&[("a.rb", b"before", b"after"), ("new.rb", b"", b"added")]);
1630+
1631+
assert!(is_unpatched(dir, &changed).await);
1632+
assert!(
1633+
is_unpatched(dir, &with_added).await,
1634+
"the added file is absent"
1635+
);
1636+
assert!(!is_unpatched(dir, &record(&[])).await, "no file, no proof");
1637+
1638+
// The added file is there, with the patch's content or any other.
1639+
for leftover in [&b"added"[..], b"something else"] {
1640+
std::fs::write(dir.join("new.rb"), leftover).unwrap();
1641+
assert!(!is_unpatched(dir, &with_added).await, "{leftover:?}");
1642+
}
1643+
std::fs::remove_file(dir.join("new.rb")).unwrap();
1644+
1645+
// The changed file is patched, edited or gone.
1646+
for content in [&b"after"[..], b"edited"] {
1647+
std::fs::write(dir.join("a.rb"), content).unwrap();
1648+
assert!(!is_unpatched(dir, &changed).await, "{content:?}");
1649+
}
1650+
std::fs::remove_file(dir.join("a.rb")).unwrap();
1651+
assert!(!is_unpatched(dir, &changed).await, "a missing file");
1652+
}
1653+
15151654
fn policy(root: &Path, enabled: bool, shared: bool, dry_run: bool) -> Policy {
15161655
Policy {
15171656
enabled,

‎crates/socket-patch-cli/src/commands/rollback.rs‎

Lines changed: 35 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1108,10 +1108,10 @@ struct VendoredLegOutcome {
11081108
/// could not be saved.
11091109
failed: Vec<(String, &'static str, String)>,
11101110
warnings: Vec<(String, String)>,
1111-
/// The gems (ledger keys) whose installed copies the unwind brought
1112-
/// back to the upstream build: nothing of theirs is left for a
1113-
/// reinstall.
1114-
refreshed_installs: std::collections::BTreeSet<String>,
1111+
/// The gems (ledger keys) with no installed copy left on the patched
1112+
/// build, brought back to the upstream one or found to be it already:
1113+
/// nothing of theirs is left for a reinstall.
1114+
upstream_installs: std::collections::BTreeSet<String>,
11151115
/// `removed` / `vendor_orphan_removed` events for the orphan uuid
11161116
/// dirs (no ledger entry) swept, also on dry-run.
11171117
orphans_removed: Vec<PatchEvent>,
@@ -1144,13 +1144,13 @@ async fn run_vendored_leg(
11441144
key,
11451145
warnings,
11461146
progress,
1147-
gem_install_refreshed,
1147+
gem_install_upstream,
11481148
step,
11491149
..
11501150
} in reverted
11511151
{
1152-
if gem_install_refreshed {
1153-
out.refreshed_installs.insert(key.clone());
1152+
if gem_install_upstream {
1153+
out.upstream_installs.insert(key.clone());
11541154
}
11551155
for w in &warnings {
11561156
if loud {
@@ -2753,17 +2753,40 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 {
27532753
let gc_bytes_freed = gc.map_or(0, |gc| gc.bytes_freed);
27542754

27552755
// ── run-level warnings ───────────────────────────────────────
2756-
let unwired_any = !vendored_leg.reverted.is_empty()
2757-
|| !vendored_leg.preserved.is_empty()
2758-
|| !hosted_leg.reverted.is_empty();
27592756
let advised = ReinstallAdvised::of(
27602757
vendored_leg
27612758
.warnings
27622759
.iter()
27632760
.chain(hosted_leg.warnings.iter())
27642761
.map(|(code, _)| code.as_str()),
27652762
);
2766-
if unwired_any {
2763+
// Only packages that are NOT also handled in place keep
2764+
// patched bytes. A successful in-place result that verified
2765+
// files leaves the installed tree original: restored now,
2766+
// restorable (dry run), or already original (never
2767+
// patched). None of those has anything left to reinstall.
2768+
let restored = handled_in_place(&results);
2769+
let base_of = |key: &str| {
2770+
vendor_entries
2771+
.iter()
2772+
.find(|(k, _)| k == key)
2773+
.map(|(_, e)| e.base_purl.clone())
2774+
};
2775+
let still_patched = vendored_leg
2776+
.reverted
2777+
.iter()
2778+
.chain(vendored_leg.preserved.iter())
2779+
.chain(hosted_leg.reverted.iter())
2780+
.filter(|key| {
2781+
!restored.contains(strip_purl_qualifiers(key))
2782+
&& !base_of(key).is_some_and(|b| restored.contains(b.as_str()))
2783+
// A gem the unwind brought back to its upstream
2784+
// build, or found on it already (#2214).
2785+
&& !hosted_leg.refreshed_installs.contains(key.as_str())
2786+
&& !vendored_leg.upstream_installs.contains(key.as_str())
2787+
})
2788+
.count();
2789+
if still_patched > 0 {
27672790
run_warnings.push((
27682791
"reinstall_required".into(),
27692792
format!(
@@ -3060,32 +3083,6 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 {
30603083
}
30613084
println!("{}", format_gc_freed(gc_bytes_freed, args.common.dry_run));
30623085
}
3063-
// Only packages that are NOT also handled in place keep
3064-
// patched bytes. A successful in-place result that verified
3065-
// files leaves the installed tree original: restored now,
3066-
// restorable (dry run), or already original (never
3067-
// patched). None of those has anything left to reinstall.
3068-
let restored = handled_in_place(&results);
3069-
let base_of = |key: &str| {
3070-
vendor_entries
3071-
.iter()
3072-
.find(|(k, _)| k == key)
3073-
.map(|(_, e)| e.base_purl.clone())
3074-
};
3075-
let still_patched = vendored_leg
3076-
.reverted
3077-
.iter()
3078-
.chain(vendored_leg.preserved.iter())
3079-
.chain(hosted_leg.reverted.iter())
3080-
.filter(|key| {
3081-
!restored.contains(strip_purl_qualifiers(key))
3082-
&& !base_of(key).is_some_and(|b| restored.contains(b.as_str()))
3083-
// A gem the hosted leg already brought back to
3084-
// its upstream build.
3085-
&& !hosted_leg.refreshed_installs.contains(key.as_str())
3086-
&& !vendored_leg.refreshed_installs.contains(key.as_str())
3087-
})
3088-
.count();
30893086
if still_patched > 0 {
30903087
println!(
30913088
"\n{}",
@@ -7138,7 +7135,7 @@ mod tests {
71387135
"boom".to_string(),
71397136
)],
71407137
warnings: Vec::new(),
7141-
refreshed_installs: Default::default(),
7138+
upstream_installs: Default::default(),
71427139
orphans_removed: Vec::new(),
71437140
};
71447141
let hosted = HostedLegOutcome {

0 commit comments

Comments
 (0)