From 7a26ee3c205488b587a80446aac45a8a110c733e Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 4 Dec 2026 14:41:49 -0500 Subject: [PATCH 1/6] Skip a stale patch instead of failing apply A manifest record for a version of a package the project no longer uses (the project moved to another version and the record was never pruned) made every `apply` exit 1 with "matched no installed package". Nothing is wrong with the installed tree in that state: the record has nothing left to patch. Such a record is now a skip in a category of its own: - `apply` skips it with a warning that names the version the project uses and the command that removes the record, and exits 0. In `--json` it is a `skipped` event with `errorCode: "patch_stale"`. - A record is stale only on evidence: the project's lockfiles or its installed tree hold the same package at another version, and neither holds the record's own. With no evidence the run still fails as before. - `apply --check` and `scan` name stale records and the remedy. - Telemetry reports the per-patch outcome `stale` with the code `patch_stale`, counted under `outcomes.stale` and never under `failure_codes`. A run that succeeds now also reports the records no installed copy matched, which it left out before. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/apply.rs | 390 +++++++++++++--- crates/socket-patch-cli/src/commands/mod.rs | 1 + .../socket-patch-cli/src/commands/scan/gc.rs | 19 + .../socket-patch-cli/src/commands/scan/mod.rs | 33 ++ .../src/commands/stale_patch.rs | 434 ++++++++++++++++++ .../src/telemetry_outcomes.rs | 41 +- crates/socket-patch-core/src/telemetry.rs | 47 +- .../socket-patch-core/src/utils/purl_key.rs | 102 ++++ 8 files changed, 999 insertions(+), 68 deletions(-) create mode 100644 crates/socket-patch-cli/src/commands/stale_patch.rs diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 653ae7abc0..7a9a5d90f1 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -32,6 +32,7 @@ use std::time::Duration; use crate::args::{apply_env_toggles, is_local_go, GlobalArgs, RunApiClient}; use crate::commands::fetch_stage::{stage_patch_sources, StageOutcome}; use crate::commands::lock_cli::acquire_or_emit; +use crate::commands::stale_patch::{self, StalePatch}; use crate::commands::vex::{ generate_vex_from_manifest_path, generate_vex_without_manifest, ManifestlessVex, VexEmbedArgs, }; @@ -637,6 +638,13 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { checked += in_sync.len(); } drifts.sort(); + // A record with no installed copy whose package the project uses at + // another version is stale, which is said in so many words: a patch + // "not installed, skipped" reads as one the next install brings back. + // It is no drift, since `apply` skips it too. + let stale = Box::pin(stale_patch::detect(&args.common, ¬_installed)).await; + stale_patch::without(&mut not_installed, &stale); + print_stale_notice(args, &stale); // A drifting package the project patched itself is one a plain `apply` // skips, so the generic remedy cannot clear it: its drift names the @@ -656,6 +664,9 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { if args.common.json { let mut env = Envelope::new(Command::Apply); record_check_skips(&mut env, &in_sync, ¬_installed, &skipped_copies); + for patch in &stale { + env.record(patch.event(&args.common)); + } for event in not_supported { env.record(event); } @@ -670,6 +681,7 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { format_check_in_sync( checked, not_installed.len(), + stale.len(), only_skipped_copies, unchecked_events.len() ) @@ -686,6 +698,9 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { ); } record_check_skips(&mut env, &in_sync, ¬_installed, &skipped_copies); + for patch in &stale { + env.record(patch.event(&args.common)); + } for event in not_supported { env.record(event); } @@ -1108,12 +1123,15 @@ fn check_remedy(common: &GlobalArgs, user_patched: bool) -> String { /// The `apply --check` success line: how many patches were checked, and how /// many were skipped for having no installed copy, so a check over an -/// uninstalled tree never reads as a vacuous "in sync". With `unchecked` -/// records of an ecosystem this CLI does not support, the line claims "in -/// sync" only for the patches it did check. +/// uninstalled tree never reads as a vacuous "in sync". A `stale` patch +/// (the project uses another version of its package) is counted as such, +/// never as "not installed". With `unchecked` records of an ecosystem this +/// CLI does not support, the line claims "in sync" only for the patches it +/// did check. fn format_check_in_sync( checked: usize, not_installed: usize, + stale: usize, not_supported: usize, unchecked: usize, ) -> String { @@ -1124,6 +1142,12 @@ fn format_check_in_sync( plural(not_installed, "patch", "patches") )); } + if stale > 0 { + skipped.push_str(&format!( + "; {} stale, skipped", + plural(stale, "patch", "patches") + )); + } // Installed, and `apply` skips it too (a compiled conda build). if not_supported > 0 { skipped.push_str(&format!( @@ -1131,7 +1155,7 @@ fn format_check_in_sync( plural(not_supported, "patch", "patches") )); } - let nothing_checked = checked == 0 && not_installed == 0 && not_supported == 0; + let nothing_checked = checked == 0 && not_installed == 0 && stale == 0 && not_supported == 0; if unchecked == 0 { return if nothing_checked { "No patches to check.".to_string() @@ -1842,8 +1866,7 @@ fn collect_apply_failures( fn collect_apply_outcomes( results: &[ApplyResult], caveats: &GemCaveats, - unmatched: &[String], - lockfile_only: &HashSet, + absent: &[PatchEvent], mut skipped: Vec, dry_run: bool, ) -> (Vec, Vec) { @@ -1864,17 +1887,7 @@ fn collect_apply_outcomes( _ => {} } } - for purl in unmatched { - let detail = if lockfile_only.contains(purl) { - LOCKFILE_ONLY_DETAIL - } else { - not_installed_detail(purl) - }; - skipped.push( - PatchEvent::new(PatchAction::Skipped, purl) - .with_reason("package_not_installed", detail), - ); - } + skipped.extend(absent.iter().cloned()); let applied_keys: HashSet<&str> = applied.iter().map(String::as_str).collect(); let failed_keys: HashSet<&str> = results .iter() @@ -2085,6 +2098,7 @@ pub(crate) async fn run_locked( results, unmatched, lockfile_only, + stale, run_warnings, fallback_skips, unreported, @@ -2093,6 +2107,9 @@ pub(crate) async fn run_locked( show_summary, nuget, }) => { + // The manifest purls no installed copy matched, as events: + // the envelope's, a nested caller's and telemetry's are one. + let absent = absent_events(&args.common, &unmatched, &lockfile_only, &stale); let patched_count = results .iter() .filter(|r| r.success && !r.files_patched.is_empty()) @@ -2366,17 +2383,16 @@ pub(crate) async fn run_locked( if args.common.verbose && !results.is_empty() { print_verbose_verification(&results); } + let tally = ApplyTally { + stale: stale.len(), + ..tally_results(&results, &caveats) + }; if show_summary && compact { println!( "{}", - format_compact_summary( - &tally_results(&results, &caveats), - targeted, - unmatched.len() - ) + format_compact_summary(&tally, targeted, unmatched.len()) ); } else if show_summary { - let tally = tally_results(&results, &caveats); println!(); if args.common.dry_run { for line in format_dry_run_summary(&tally, unmatched.len()) { @@ -2457,17 +2473,11 @@ pub(crate) async fn run_locked( } // Manifest entries that targeted in-scope ecosystems but // had no installed package on disk — emit one Skipped - // event per purl so downstream consumers can surface them. - for purl in &unmatched { - let detail = if lockfile_only.contains(purl) { - LOCKFILE_ONLY_DETAIL - } else { - not_installed_detail(purl) - }; - env.record( - PatchEvent::new(PatchAction::Skipped, purl.clone()) - .with_reason("package_not_installed", detail), - ); + // event per purl so downstream consumers can surface them: + // `package_not_installed`, or `patch_stale` for a record + // whose package the project uses at another version. + for event in &absent { + env.record(event.clone()); } // Gem copies left as they were on purpose: one Skipped event // each, with the reason. Never an `applied` event with no @@ -2594,6 +2604,7 @@ pub(crate) async fn run_locked( &caveats, &failures, &unreported, + &absent, args.common.dry_run, &patch_uuids, ); @@ -2628,11 +2639,14 @@ pub(crate) async fn run_locked( .filter(|w| !is_stage_failure_code(&w.code)) .cloned(), ); + // A stale patch is rarely one the caller selected, so its + // skip would go unsaid in the caller's envelope: a warning + // each, which names the patch and the remedy. + warnings.extend(stale.iter().map(|patch| patch.warning(&args.common))); let (applied, skipped) = collect_apply_outcomes( &results, &caveats, - &unmatched, - &lockfile_only, + &absent, user_patch_skips, args.common.dry_run, ); @@ -2700,10 +2714,14 @@ fn telemetry_command(args: &ApplyArgs) -> &'static str { /// a refusal of the whole base stands beside its applied copies), and the /// patches that failed /// the run by not being installed (`failures`), each under the patch its -/// manifest record names. +/// manifest record names. Last come the records no installed copy matched +/// (`absent`, [`absent_events`]): a stale patch as `stale`, the others as +/// `skipped` / `package_not_installed`. A run that succeeded reports them +/// too; on one they failed, the failure above says more and stands. /// -/// `unreported` comes before `failures`: a copy no release variant matches -/// leaves its variants unmatched too, and that copy is installed. +/// `unreported` comes before `failures` and `absent`: a copy no release +/// variant matches leaves its variants unmatched too, and that copy is +/// installed. /// /// A plain fn, so the events it builds stay off the async frame of `run`. fn reported_patches( @@ -2711,6 +2729,7 @@ fn reported_patches( caveats: &GemCaveats, failures: &[ApplyFailure], unreported: &[(String, ApplyFailureCause)], + absent: &[PatchEvent], dry_run: bool, patch_uuids: &HashMap, ) -> Vec { @@ -2740,6 +2759,17 @@ fn reported_patches( .filter(|f| f.code == "package_not_installed" && !named.contains(f.purl.as_str())) .map(|f| f.event(&f.purl)), ) + .chain( + absent + .iter() + .filter(|event| { + event + .purl + .as_deref() + .is_none_or(|purl| !named.contains(purl)) + }) + .cloned(), + ) .collect(); crate::telemetry_outcomes::patch_outcomes( &events, @@ -2872,6 +2902,11 @@ struct ApplyOutcome { /// optional dependency, a devDependency under `--omit=dev`), so a calm /// skip that never fails the run (#403). lockfile_only: HashSet, + /// In-scope manifest purls for a version of a package the project no + /// longer uses: its lockfiles or its installed tree hold another one. + /// A skip of its own (`patch_stale`) that never fails the run, and + /// never one of [`Self::unmatched`]. + stale: Vec, /// Run-level advisories: JSON `warnings[]`, and one gated stderr line /// each on the human path (`--silent` = errors only) except the /// sources-unavailable codes (already printed by the stager): the gem @@ -3040,6 +3075,11 @@ struct ApplyTally { /// Every copy was skipped because patching it is not supported yet (a /// compiled conda build). The package is not patched. unsupported: usize, + /// The record is for a version of the package the project no longer + /// uses ([`StalePatch`]): nothing to patch, and never "not found on + /// disk". Set by `run`, which knows the run's stale patches; + /// [`tally_results`] counts results only. + stale: usize, } fn tally_results(results: &[ApplyResult], caveats: &GemCaveats) -> ApplyTally { @@ -3142,6 +3182,9 @@ fn format_summary_line(tally: &ApplyTally, targeted: usize, not_found: usize) -> if tally.failed > 0 { parts.push(format!("{} failed", tally.failed)); } + if tally.stale > 0 { + parts.push(format!("{} stale", tally.stale)); + } parts.push(format!("{not_found} not found on disk")); format!("Summary: {}", parts.join(", ")) } @@ -3158,6 +3201,7 @@ fn format_compact_summary(tally: &ApplyTally, targeted: usize, not_found: usize) (tally.not_in_effect, "not in effect"), (tally.unsupported, "not supported"), (tally.failed, "failed"), + (tally.stale, "stale"), (not_found, "not found on disk"), ] .into_iter() @@ -3215,6 +3259,12 @@ fn format_dry_run_summary(tally: &ApplyTally, not_found: usize) -> Vec { plural(tally.failed, "package", "packages") )); } + if tally.stale > 0 { + lines.push(format!( + " {} stale", + plural(tally.stale, "patch", "patches") + )); + } if not_found > 0 { lines.push(format!( " {} not found on disk", @@ -3665,6 +3715,7 @@ async fn apply_patches_inner( results: Vec::new(), unmatched: Vec::new(), lockfile_only: HashSet::new(), + stale: Vec::new(), run_warnings: vec![stage_failure_warning(args.common.offline)], fallback_skips: Vec::new(), unreported: Vec::new(), @@ -3709,6 +3760,7 @@ async fn apply_patches_inner( results: reconcile_failures, unmatched: Vec::new(), lockfile_only: HashSet::new(), + stale: Vec::new(), run_warnings: Vec::new(), fallback_skips: Vec::new(), unreported: Vec::new(), @@ -3860,6 +3912,11 @@ async fn apply_patches_inner( boxed(|| other_project_gem_copies(&args.common, &unresolved, &all_packages)).await; unmatched.retain(|purl| !other_project.iter().any(|copy| copy.purl == *purl)); let unresolved = unresolved_purls(&unmatched, &lockfile_only); + // A record for a version the project no longer uses is stale: a + // skip of its own, and no reason to fail either. + let stale = Box::pin(stale_patch::detect(&args.common, &unresolved)).await; + stale_patch::without(&mut unmatched, &stale); + let unresolved = unresolved_purls(&unmatched, &lockfile_only); // This diagnostic flips the exit code, so it is an error — and it // prints even under --silent ("errors only", never a mute exit 1); // `--json` @@ -3871,11 +3928,13 @@ async fn apply_patches_inner( } } print_lockfile_only_note(args, &unmatched, &lockfile_only); + print_stale_notice(args, &stale); return Ok(ApplyOutcome { success: unresolved.is_empty() && results.iter().all(|r| r.success), results, unmatched, lockfile_only, + stale, run_warnings, fallback_skips, unreported, @@ -4657,6 +4716,11 @@ async fn apply_patches_inner( boxed(|| other_project_gem_copies(&args.common, &unresolved, &all_packages)).await; unmatched.retain(|purl| !caveats.other_project.iter().any(|copy| copy.purl == *purl)); let unresolved = unresolved_purls(&unmatched, &lockfile_only); + // A record for a version the project no longer uses is stale: a skip + // of its own, which never fails the run, alone or beside a live patch. + let stale = Box::pin(stale_patch::detect(&args.common, &unresolved)).await; + stale_patch::without(&mut unmatched, &stale); + let unresolved = unresolved_purls(&unmatched, &lockfile_only); // Nothing matched and some purl has no lock evidence either: this // fails the run, so it is an error — and errors print even under @@ -4686,6 +4750,7 @@ async fn apply_patches_inner( } } print_lockfile_only_note(args, &unmatched, &lockfile_only); + print_stale_notice(args, &stale); // The human summary is printed by `run`, after the per-package list. @@ -4708,6 +4773,7 @@ async fn apply_patches_inner( results, unmatched, lockfile_only, + stale, run_warnings, fallback_skips, unreported, @@ -5512,6 +5578,44 @@ fn print_lockfile_only_note( } } +/// The human warning for stale patches (never an error; muted by +/// `--silent` and `--json`, whose `skipped` events carry it). +fn print_stale_notice(args: &ApplyArgs, stale: &[StalePatch]) { + if args.common.silent || args.common.json { + return; + } + for line in stale_patch::notice_lines(stale, &args.common) { + eprintln!("{line}"); + } +} + +/// The `skipped` events of the manifest purls no installed copy matched, +/// as `apply --json` prints them: `package_not_installed` for each of +/// `unmatched` (with the lockfile-only reason for the ones a lockfile +/// resolves), then `patch_stale` for each of `stale`. +/// +/// A plain fn, so the events it builds stay off the async frame of `run`. +fn absent_events( + common: &GlobalArgs, + unmatched: &[String], + lockfile_only: &HashSet, + stale: &[StalePatch], +) -> Vec { + unmatched + .iter() + .map(|purl| { + let detail = if lockfile_only.contains(purl) { + LOCKFILE_ONLY_DETAIL + } else { + not_installed_detail(purl) + }; + PatchEvent::new(PatchAction::Skipped, purl.clone()) + .with_reason("package_not_installed", detail) + }) + .chain(stale.iter().map(|patch| patch.event(common))) + .collect() +} + /// `Error: Failed to patch : ` (stderr, even under --silent). fn format_patch_failure(purl: &str, why: &str) -> String { format!("Error: Failed to patch {purl}: {why}") @@ -5920,11 +6024,21 @@ mod tests { already_patched.package_key = "pkg:npm/already@1.0.0".into(); unchanged_copy.package_path = "/another/node_modules/minimist".into(); let missing = "pkg:npm/missing@1.0.0".to_string(); + let stale = StalePatch { + purl: "pkg:npm/moved@1.0.0".to_string(), + version: "1.0.0".to_string(), + others: vec!["2.0.0".to_string()], + evidence: stale_patch::Evidence::Lockfile, + }; let (applied, skipped) = collect_apply_outcomes( &[unchanged_copy, changed_copy, vendored, already_patched], &GemCaveats::default(), - std::slice::from_ref(&missing), - &HashSet::from([missing.clone()]), + &absent_events( + &GlobalArgs::default(), + std::slice::from_ref(&missing), + &HashSet::from([missing.clone()]), + std::slice::from_ref(&stale), + ), Vec::new(), false, ); @@ -5938,6 +6052,7 @@ mod tests { vec![ ("pkg:npm/already@1.0.0", "already_patched"), ("pkg:npm/missing@1.0.0", "package_not_installed"), + ("pkg:npm/moved@1.0.0", "patch_stale"), ("pkg:npm/vendor@1.0.0", "vendored"), ] ); @@ -5997,6 +6112,7 @@ mod tests { &GemCaveats::default(), &failures, &unreported, + &[], false, &uuids, ); @@ -6014,6 +6130,129 @@ mod tests { ); } + fn stale_patch_of(purl: &str) -> StalePatch { + StalePatch { + purl: purl.to_string(), + version: "1.0.0".to_string(), + others: vec!["2.0.0".to_string()], + evidence: stale_patch::Evidence::Lockfile, + } + } + + /// A run that succeeds still names the records no installed copy + /// matched: a stale patch as `stale` under `patch_stale`, and the + /// others (resolved by a lockfile, or not installed beside a patch + /// that applied) as `skipped` / `package_not_installed`. Such a run + /// has no failures to carry them. + #[test] + fn a_successful_run_reports_its_stale_and_absent_patches() { + let uuids = HashMap::from([ + ("pkg:npm/minimist@1.2.2".to_string(), "u-live".to_string()), + ("pkg:npm/moved@1.0.0".to_string(), "u-stale".to_string()), + ("pkg:npm/optional@1.0.0".to_string(), "u-locked".to_string()), + ("pkg:npm/absent@1.0.0".to_string(), "u-absent".to_string()), + ]); + let unmatched = [ + "pkg:npm/absent@1.0.0".to_string(), + "pkg:npm/optional@1.0.0".to_string(), + ]; + let absent = absent_events( + &GlobalArgs::default(), + &unmatched, + &HashSet::from(["pkg:npm/optional@1.0.0".to_string()]), + &[stale_patch_of("pkg:npm/moved@1.0.0")], + ); + let reported = reported_patches( + &[sample_applied(VerifyStatus::Ready)], + &GemCaveats::default(), + &[], + &[], + &absent, + false, + &uuids, + ); + let named: Vec<(&str, &str, Option<&str>)> = reported + .iter() + .map(|p| (p.uuid.as_str(), p.outcome, p.code.as_deref())) + .collect(); + assert_eq!( + named, + [ + ("u-live", "applied", None), + ("u-absent", "skipped", Some("package_not_installed")), + ("u-locked", "skipped", Some("package_not_installed")), + ("u-stale", "stale", Some("patch_stale")), + ] + ); + + // A run of nothing but a stale patch reports it, and no failure. + let only_stale = absent_events( + &GlobalArgs::default(), + &[], + &HashSet::new(), + &[stale_patch_of("pkg:npm/moved@1.0.0")], + ); + let reported = reported_patches( + &[], + &GemCaveats::default(), + &[], + &[], + &only_stale, + false, + &uuids, + ); + assert_eq!(reported.len(), 1); + assert_eq!( + (reported[0].outcome, reported[0].code.as_deref()), + ("stale", Some("patch_stale")) + ); + } + + /// A record that failed the run by not being installed is reported + /// once, as the failure: its `skipped` event says less. A stale patch + /// beside it is still `stale`, and never a failure. + #[test] + fn a_failed_run_keeps_the_failure_beside_a_stale_patch() { + let uuids = HashMap::from([ + ("pkg:npm/gone@1.0.0".to_string(), "u-gone".to_string()), + ("pkg:npm/moved@1.0.0".to_string(), "u-stale".to_string()), + ]); + let unmatched = ["pkg:npm/gone@1.0.0".to_string()]; + let failures = + collect_apply_failures(&[], &GemCaveats::default(), &unmatched, &HashSet::new()); + assert_eq!( + failures.len(), + 1, + "a stale patch is no failure: {failures:?}" + ); + let absent = absent_events( + &GlobalArgs::default(), + &unmatched, + &HashSet::new(), + &[stale_patch_of("pkg:npm/moved@1.0.0")], + ); + let reported = reported_patches( + &[], + &GemCaveats::default(), + &failures, + &[], + &absent, + false, + &uuids, + ); + let named: Vec<(&str, &str, Option<&str>)> = reported + .iter() + .map(|p| (p.uuid.as_str(), p.outcome, p.code.as_deref())) + .collect(); + assert_eq!( + named, + [ + ("u-gone", "failed", Some("package_not_installed")), + ("u-stale", "stale", Some("patch_stale")), + ] + ); + } + /// A copy no variant matches leaves its variants unmatched too: they /// are reported as not matching (the copy is installed), not as not /// installed; once each however many copies missed; and never a @@ -6044,6 +6283,7 @@ mod tests { &GemCaveats::default(), &failures, &unreported, + &[], false, &uuids, ); @@ -6067,6 +6307,7 @@ mod tests { &GemCaveats::default(), &[], &refused, + &[], false, &uuids, ); @@ -6418,6 +6659,22 @@ mod tests { format_compact_summary(&partial, 3, 0), "Applied 1 of 3 patches: 1 not applicable, 1 not in effect." ); + // A stale patch has a bucket of its own, shown only when there is + // one: it is never counted as not found on disk. + let stale = ApplyTally { + applied: 1, + stale: 2, + ..ApplyTally::default() + }; + assert_eq!( + format_summary_line(&stale, 3, 0), + "Summary: 1 of 3 targeted patches applied, 0 already patched, 2 stale, 0 not found \ + on disk" + ); + assert_eq!( + format_compact_summary(&stale, 3, 0), + "Applied 1 of 3 patches: 2 stale." + ); } #[test] @@ -6461,6 +6718,7 @@ mod tests { not_applicable: 0, not_in_effect: 0, unsupported: 0, + stale: 0, } ); assert_eq!( @@ -6525,8 +6783,7 @@ mod tests { assert_eq!(v["reason"], "not part of it"); assert_eq!(v["purl"], GEM_PURL); // For a nested caller it is a skip of the patch as well. - let (applied, skipped) = - collect_apply_outcomes(&[], &caveats, &[], &HashSet::new(), Vec::new(), false); + let (applied, skipped) = collect_apply_outcomes(&[], &caveats, &[], Vec::new(), false); assert!(applied.is_empty()); assert_eq!(skipped.len(), 1); assert_eq!( @@ -6587,19 +6844,12 @@ mod tests { cause: None, }] ); - let (applied, skipped) = - collect_apply_outcomes(&results, &caveats, &[], &HashSet::new(), Vec::new(), false); + let (applied, skipped) = collect_apply_outcomes(&results, &caveats, &[], Vec::new(), false); assert!(applied.is_empty(), "{applied:?}"); assert!(skipped.is_empty()); // Without the caveat the same result is a patched package. - let (applied, _) = collect_apply_outcomes( - &results, - &GemCaveats::default(), - &[], - &HashSet::new(), - Vec::new(), - false, - ); + let (applied, _) = + collect_apply_outcomes(&results, &GemCaveats::default(), &[], Vec::new(), false); assert_eq!(applied, [GEM_PURL]); } @@ -6743,7 +6993,7 @@ mod tests { ); assert!(format_results_block(&results, &caveats, false, Path::new("/p")).is_empty()); let (applied, skipped) = - collect_apply_outcomes(&results, &caveats, &[], &HashSet::new(), Vec::new(), false); + collect_apply_outcomes(&results, &caveats, &[], Vec::new(), false); assert!(applied.is_empty(), "{applied:?}"); assert!(skipped.is_empty()); let failures = collect_apply_failures(&results, &caveats, &[], &HashSet::new()); @@ -6829,7 +7079,6 @@ mod tests { std::slice::from_ref(&applied), &two_envs, &[], - &HashSet::new(), Vec::new(), false, ); @@ -6854,12 +7103,12 @@ mod tests { // `apply --check` names it apart from a package that is not // installed. assert_eq!( - format_check_in_sync(1, 1, 2, 0), + format_check_in_sync(1, 1, 0, 2, 0), "Patches are in sync (1 patch checked; 1 patch not installed, skipped; \ 2 patches not supported, skipped)." ); assert_eq!( - format_check_in_sync(0, 0, 1, 0), + format_check_in_sync(0, 0, 0, 1, 0), "Patches are in sync (0 patches checked; 1 patch not supported, skipped)." ); } @@ -6875,6 +7124,7 @@ mod tests { not_applicable: 1, not_in_effect: 2, unsupported: 1, + stale: 2, }; assert_eq!( format_dry_run_summary(&t, 3), @@ -6886,6 +7136,7 @@ mod tests { " 2 packages would not take effect", " 1 package not supported", " 1 package cannot be patched", + " 2 patches stale", " 3 packages not found on disk", ] ); @@ -6997,33 +7248,44 @@ mod tests { #[test] fn check_in_sync_line() { - assert_eq!(format_check_in_sync(0, 0, 0, 0), "No patches to check."); + assert_eq!(format_check_in_sync(0, 0, 0, 0, 0), "No patches to check."); assert_eq!( - format_check_in_sync(1, 0, 0, 0), + format_check_in_sync(1, 0, 0, 0, 0), "Patches are in sync (1 patch checked)." ); assert_eq!( - format_check_in_sync(3, 0, 0, 0), + format_check_in_sync(3, 0, 0, 0, 0), "Patches are in sync (3 patches checked)." ); // A check that skipped uninstalled packages says so, never a bare // vacuous "in sync". assert_eq!( - format_check_in_sync(0, 2, 0, 0), + format_check_in_sync(0, 2, 0, 0, 0), "Patches are in sync (0 patches checked; 2 patches not installed, skipped)." ); + // A stale patch is counted as stale, never as not installed, and a + // check of nothing else still says what it skipped. + assert_eq!( + format_check_in_sync(0, 0, 1, 0, 0), + "Patches are in sync (0 patches checked; 1 patch stale, skipped)." + ); + assert_eq!( + format_check_in_sync(2, 1, 2, 0, 0), + "Patches are in sync (2 patches checked; 1 patch not installed, skipped; 2 patches \ + stale, skipped)." + ); // Records of an unsupported ecosystem were not checked: "in sync" // is claimed only for the ones that were. assert_eq!( - format_check_in_sync(0, 0, 0, 3), + format_check_in_sync(0, 0, 0, 0, 3), "No patches checked: 3 patches not checked (unsupported ecosystem)." ); assert_eq!( - format_check_in_sync(1, 0, 0, 1), + format_check_in_sync(1, 0, 0, 0, 1), "1 checked patch is in sync; 1 patch not checked (unsupported ecosystem)." ); assert_eq!( - format_check_in_sync(2, 1, 0, 2), + format_check_in_sync(2, 1, 0, 0, 2), "2 checked patches are in sync; 1 patch not installed, skipped; 2 patches not \ checked (unsupported ecosystem)." ); diff --git a/crates/socket-patch-cli/src/commands/mod.rs b/crates/socket-patch-cli/src/commands/mod.rs index 3565d3c19d..282ee53edc 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -20,6 +20,7 @@ pub mod report; pub mod rollback; pub mod scan; pub mod show; +pub(crate) mod stale_patch; pub mod update; pub(crate) mod user_patches; pub mod vendor; diff --git a/crates/socket-patch-cli/src/commands/scan/gc.rs b/crates/socket-patch-cli/src/commands/scan/gc.rs index ec21a6c1c3..abfc3b3ad4 100644 --- a/crates/socket-patch-cli/src/commands/scan/gc.rs +++ b/crates/socket-patch-cli/src/commands/scan/gc.rs @@ -915,6 +915,25 @@ fn detect_prunable( .collect() } +/// The stale records of `manifest`: the entries a `--prune` would drop +/// ([`detect_prunable`]) whose package the scan found at another version +/// (`scanned_purls`: installed, or resolved by a lockfile). Sorted. +/// +/// A scan that does not prune names them with the remedy, as `apply` does +/// for the ones it skips (see [`crate::commands::stale_patch`]); an entry +/// for a package the scan found no version of is not among them. +pub(super) fn stale_records( + manifest: &PatchManifest, + scanned_purls: &HashSet, + vendored: &HashSet, +) -> Vec { + use crate::commands::stale_patch::{classify, Evidence}; + let mut prunable = detect_prunable(manifest, scanned_purls, vendored); + prunable.sort(); + let scanned: Vec = scanned_purls.iter().map(|p| PurlKey::new(p)).collect(); + classify(&prunable, &scanned, Evidence::Project).0 +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index ba243b791f..5ae989eb1a 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2742,6 +2742,15 @@ async fn scan_project( // Read existing manifest once for update detection. let existing_manifest = ctx.ledgers().await.manifest; + // Records for a version of a package the project no longer uses. A + // pruning run removes them in its GC; every other run names them and + // the command that does (hosted mode runs no GC, whatever it was told). + let stale_records = match existing_manifest { + Some(manifest) if !prune || hosted => { + gc::stale_records(manifest, &scanned_purls, &vendored_purls) + } + _ => Vec::new(), + }; // A manifest that exists but cannot be loaded (rule shared by every // command: `manifest_invalid` / `manifest_unreadable`). Agent mode // reads and rewrites it (its dry run previews against it), so it fails @@ -4015,6 +4024,19 @@ async fn scan_project( .await; } + // A nested apply names the stale records it skipped; a run that + // applied nothing names them here. + if !env + .warnings + .iter() + .any(|w| w.code == crate::commands::stale_patch::PATCH_STALE) + { + env.warnings.extend( + stale_records + .iter() + .map(|patch| patch.warning(&args.common)), + ); + } finish_rollout_json(&stage, &mut env); let final_code = embed_vex_into_json( &args.common, @@ -4044,8 +4066,16 @@ async fn scan_project( let client_ref: &ApiClient = &api_client; let (scanned_ref, vendored_ref) = (&scanned_purls, &vendored_purls); let policy_ref: &ScanPolicy = &policy; + let stale_ref = &stale_records; let finish_human = move |code: i32| async move { policy_ref.print_human(silent, verbose); + // No apply ran on any exit that ends here, so nothing has named + // the stale records yet (a nested apply warns of its own). + if !silent && code == 0 { + for line in crate::commands::stale_patch::notice_lines(stale_ref, &args_ref.common) { + eprintln!("{line}"); + } + } if prune && !hosted && code == 0 { gc::run_human_gc( &args_ref.common, @@ -4468,6 +4498,9 @@ async fn scan_project( for line in render::report_only_hint(&args.common) { println!("{line}"); } + for line in crate::commands::stale_patch::notice_lines(&stale_records, &args.common) { + eprintln!("{line}"); + } } if prune { gc::run_human_gc( diff --git a/crates/socket-patch-cli/src/commands/stale_patch.rs b/crates/socket-patch-cli/src/commands/stale_patch.rs new file mode 100644 index 0000000000..a39974473f --- /dev/null +++ b/crates/socket-patch-cli/src/commands/stale_patch.rs @@ -0,0 +1,434 @@ +//! Stale patches: manifest records for a version of a package the project +//! no longer uses. +//! +//! A project that records a patch for `x@1.0.0` and later moves to +//! `x@2.0.0` keeps the record until something removes it. Nothing is wrong +//! with the installed tree: the record has nothing left to patch. `apply` +//! skips it under a code of its own ([`PATCH_STALE`]) and never fails the +//! run for it, `apply --check` and `scan` name it, and `scan --prune` +//! removes it. +//! +//! A record is stale only on evidence: the project's lockfiles or its +//! installed tree hold the same package at another version, and neither +//! holds the record's own. A record for a package the project shows no +//! sign of is not stale; it stays `package_not_installed`. + +use std::collections::{BTreeSet, HashMap}; + +use socket_patch_core::crawlers::Ecosystem; +use socket_patch_core::utils::purl::normalize_purl; +use socket_patch_core::utils::purl_key::PurlKey; + +use crate::args::GlobalArgs; +use crate::json_envelope::{PatchAction, PatchEvent, RunWarning}; +use crate::ui::plural; + +/// The `errorCode` of a stale patch's `skipped` event, the code of its run +/// warning, and its code in telemetry. +pub(crate) const PATCH_STALE: &str = "patch_stale"; + +/// How many other versions a line names before it counts the rest. +const NAMED_VERSIONS: usize = 3; + +/// Where the other version of a stale patch's package was found. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Evidence { + /// The project's lockfiles resolve it. + Lockfile, + /// It is installed. + Installed, + /// A scan found it: installed, or resolved by a lockfile. + Project, +} + +/// A manifest record whose package the project uses at another version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct StalePatch { + /// The manifest key. + pub(crate) purl: String, + /// The version the record patches. + pub(crate) version: String, + /// The versions the project uses instead: sorted, never empty. + pub(crate) others: Vec, + pub(crate) evidence: Evidence, +} + +impl StalePatch { + /// `the project lockfile resolves 2.0.0` / `2.0.0 is installed`. + fn found(&self) -> String { + let named = self.others[..self.others.len().min(NAMED_VERSIONS)].join(", "); + let versions = match self.others.len().saturating_sub(NAMED_VERSIONS) { + 0 => named, + more => format!("{named} and {more} more"), + }; + match self.evidence { + Evidence::Lockfile => format!("the project lockfile resolves {versions}"), + Evidence::Installed if self.others.len() == 1 => format!("{versions} is installed"), + Evidence::Installed => format!("{versions} are installed"), + Evidence::Project => format!("the project uses {versions}"), + } + } + + /// The reason of the `skipped` event: what the project uses instead, + /// and the command that removes the record. + pub(crate) fn detail(&self, common: &GlobalArgs) -> String { + format!( + "The patch is for {}, but {} (stale patch); run `{}` to remove it from the manifest", + self.version, + self.found(), + prune_command(common) + ) + } + + /// The patch's `skipped` event (`errorCode: "patch_stale"`). + pub(crate) fn event(&self, common: &GlobalArgs) -> PatchEvent { + PatchEvent::new(PatchAction::Skipped, self.purl.clone()) + .with_reason(PATCH_STALE, self.detail(common)) + } + + /// The patch as a run warning, for an envelope that has no event of + /// its own for it (a nested apply's caller, `scan`). + pub(crate) fn warning(&self, common: &GlobalArgs) -> RunWarning { + RunWarning::new( + PATCH_STALE, + format!("{}: {}", normalize_purl(&self.purl), self.detail(common)), + ) + } +} + +/// The command that removes stale records, scoped to the tree `common` +/// names so it can be pasted as printed. +pub(crate) fn prune_command(common: &GlobalArgs) -> String { + format!("socket-patch scan --prune{}", crate::ui::scope_args(common)) +} + +/// The human notice for `stale` (empty when there is none): what is stale, +/// what the project uses instead, and the remedy. +pub(crate) fn notice_lines(stale: &[StalePatch], common: &GlobalArgs) -> Vec { + if stale.is_empty() { + return Vec::new(); + } + let mut lines = vec![format!( + "Warning: {} stale (the project uses another version of the package; skipped):", + plural(stale.len(), "manifest patch is", "manifest patches are") + )]; + lines.extend( + stale + .iter() + .map(|patch| format!(" - {} ({})", normalize_purl(&patch.purl), patch.found())), + ); + lines.push(format!( + "Run `{}` to remove {} from the manifest.", + prune_command(common), + if stale.len() == 1 { "it" } else { "them" } + )); + lines +} + +/// Split `candidates` (manifest keys with no installed copy) by what +/// `known` (the purls of a lock inventory or of a crawl) says of them: +/// the stale ones, sorted, and the ones `known` says nothing about. A +/// candidate `known` holds at its own version is neither: the project +/// still uses that version. +/// +/// Packages are compared as [`PurlKey`]s, so a name's spelling, a purl's +/// qualifiers and a release's spelling never make two of one package. +pub(crate) fn classify( + candidates: &[String], + known: &[PurlKey], + evidence: Evidence, +) -> (Vec, Vec) { + let mut by_package: HashMap<&str, Vec<&PurlKey>> = HashMap::new(); + for key in known { + if let Some((package, _)) = key.package_and_version() { + by_package.entry(package).or_default().push(key); + } + } + let mut stale = Vec::new(); + let mut undecided = Vec::new(); + for purl in candidates { + let key = PurlKey::new(purl); + let Some((package, version)) = key.package_and_version() else { + undecided.push(purl.clone()); + continue; + }; + let Some(releases) = by_package.get(package) else { + undecided.push(purl.clone()); + continue; + }; + let others: Option> = releases + .iter() + .map(|release| key.other_release(release)) + .collect(); + // `None`: some release is the candidate's own version. + if let Some(others) = others.filter(|others| !others.is_empty()) { + stale.push(StalePatch { + purl: purl.clone(), + version: version.to_string(), + others: others.into_iter().map(str::to_string).collect(), + evidence, + }); + } + } + stale.sort_by(|a, b| a.purl.cmp(&b.purl)); + (stale, undecided) +} + +/// The stale ones among `candidates`: manifest keys no installed copy +/// matched and no lockfile resolves at their own version (sorted). +/// +/// The project's lockfiles are asked first. The installed tree is crawled +/// only for the candidates no lockfile names, and only in their +/// ecosystems: a project with no lockfile, a global run. +pub(crate) async fn detect(common: &GlobalArgs, candidates: &[String]) -> Vec { + if candidates.is_empty() { + return Vec::new(); + } + let mut stale = Vec::new(); + let mut undecided = candidates.to_vec(); + if !common.is_global() { + let ctx = crate::commands::context::ProjectContext::new(common); + let mut locked: Vec = ctx + .locks() + .await + .entries + .iter() + .map(|entry| PurlKey::new(&entry.purl)) + .collect(); + // A gem the lock resolves only as platform builds is left out of + // the inventory, and is resolved all the same. + locked.extend( + ctx.gem_platform_only_purls() + .await + .iter() + .map(|purl| PurlKey::new(purl)), + ); + let (found, rest) = classify(&undecided, &locked, Evidence::Lockfile); + stale.extend(found); + undecided = rest; + } + if !undecided.is_empty() { + let ecosystems: Vec = undecided + .iter() + .filter_map(|purl| Ecosystem::from_purl(purl)) + .map(|ecosystem| ecosystem.cli_name().to_string()) + .collect::>() + .into_iter() + .collect(); + if !ecosystems.is_empty() { + let (installed, _, _) = crate::ecosystem_dispatch::crawl_ecosystems_for_name( + &common.crawler_options(), + Some(&ecosystems), + ) + .await; + let installed: Vec = installed + .iter() + .map(|package| PurlKey::new(&package.purl)) + .collect(); + stale.extend(classify(&undecided, &installed, Evidence::Installed).0); + } + } + stale.sort_by(|a, b| a.purl.cmp(&b.purl)); + stale +} + +/// `purls` without the stale ones. +pub(crate) fn without(purls: &mut Vec, stale: &[StalePatch]) { + purls.retain(|purl| !stale.iter().any(|patch| patch.purl == *purl)); +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + #[derive(Parser)] + struct TestCli { + #[command(flatten)] + common: GlobalArgs, + } + + fn common(args: &[&str]) -> GlobalArgs { + TestCli::try_parse_from(std::iter::once("socket-patch").chain(args.iter().copied())) + .expect("arguments parse") + .common + } + + fn keys(purls: &[&str]) -> Vec { + purls.iter().map(|purl| PurlKey::new(purl)).collect() + } + + fn candidates(purls: &[&str]) -> Vec { + purls.iter().map(|purl| (*purl).to_string()).collect() + } + + #[test] + fn another_version_of_the_package_makes_a_record_stale() { + let (stale, undecided) = classify( + &candidates(&["pkg:npm/widget@1.0.0", "pkg:npm/@scope/gadget@2.1.0"]), + &keys(&[ + "pkg:npm/widget@2.0.0", + "pkg:npm/widget@3.0.0", + "pkg:npm/@scope/gadget@2.2.0", + "pkg:npm/unrelated@1.0.0", + ]), + Evidence::Lockfile, + ); + assert_eq!( + stale, + vec![ + StalePatch { + purl: "pkg:npm/@scope/gadget@2.1.0".to_string(), + version: "2.1.0".to_string(), + others: vec!["2.2.0".to_string()], + evidence: Evidence::Lockfile, + }, + StalePatch { + purl: "pkg:npm/widget@1.0.0".to_string(), + version: "1.0.0".to_string(), + others: vec!["2.0.0".to_string(), "3.0.0".to_string()], + evidence: Evidence::Lockfile, + }, + ] + ); + assert!(undecided.is_empty()); + } + + /// A package the project shows no sign of is not stale: the caller + /// keeps looking, and with nothing found it stays not installed. + #[test] + fn a_package_nothing_names_is_undecided() { + let (stale, undecided) = classify( + &candidates(&["pkg:npm/widget@1.0.0", "not-a-purl"]), + &keys(&["pkg:npm/widget-extra@1.0.0", "pkg:pypi/widget@2.0.0"]), + Evidence::Installed, + ); + assert!(stale.is_empty()); + assert_eq!( + undecided, + candidates(&["pkg:npm/widget@1.0.0", "not-a-purl"]) + ); + } + + /// The record's own version among the known purls settles it: the + /// project still uses that version (a crate that is locked and not + /// fetched yet), whatever other versions sit beside it. + #[test] + fn the_records_own_version_is_neither_stale_nor_undecided() { + let (stale, undecided) = classify( + &candidates(&["pkg:cargo/widget@1.0.0"]), + &keys(&["pkg:cargo/widget@1.0.0", "pkg:cargo/widget@2.0.0"]), + Evidence::Lockfile, + ); + assert!(stale.is_empty()); + assert!(undecided.is_empty()); + } + + /// Identity is the canonical purl's: a name spelled another way, a + /// qualifier and an equal PEP 440 spelling are the same release. + #[test] + fn spelling_does_not_make_a_record_stale() { + let (stale, undecided) = classify( + &candidates(&[ + "pkg:pypi/Widget_Kit@1.0?artifact_id=abc", + "pkg:pypi/gadget@2.0.0", + ]), + &keys(&["pkg:pypi/widget-kit@1.0.0", "pkg:pypi/Gadget@2.1"]), + Evidence::Lockfile, + ); + assert_eq!(stale.len(), 1, "{stale:?}"); + assert_eq!(stale[0].purl, "pkg:pypi/gadget@2.0.0"); + assert_eq!(stale[0].others, vec!["2.1".to_string()]); + assert!(undecided.is_empty()); + } + + fn stale(others: &[&str], evidence: Evidence) -> StalePatch { + StalePatch { + purl: "pkg:npm/widget@1.0.0".to_string(), + version: "1.0.0".to_string(), + others: others.iter().map(|v| (*v).to_string()).collect(), + evidence, + } + } + + #[test] + fn the_reason_names_the_other_version_and_the_remedy() { + let default = common(&[]); + assert_eq!( + stale(&["2.0.0"], Evidence::Lockfile).detail(&default), + "The patch is for 1.0.0, but the project lockfile resolves 2.0.0 (stale patch); \ + run `socket-patch scan --prune` to remove it from the manifest" + ); + assert_eq!( + stale(&["2.0.0"], Evidence::Installed).detail(&default), + "The patch is for 1.0.0, but 2.0.0 is installed (stale patch); run `socket-patch \ + scan --prune` to remove it from the manifest" + ); + assert_eq!( + stale(&["2.0.0", "3.0.0"], Evidence::Installed).found(), + "2.0.0, 3.0.0 are installed" + ); + assert_eq!( + stale(&["2", "3", "4", "5", "6"], Evidence::Lockfile).found(), + "the project lockfile resolves 2, 3, 4 and 2 more" + ); + assert_eq!( + stale(&["2.0.0"], Evidence::Project).found(), + "the project uses 2.0.0" + ); + } + + /// The remedy repeats the flags that pick the tree, so it prunes the + /// manifest the run read. + #[test] + fn the_remedy_is_scoped_to_the_tree_the_run_read() { + let scoped = common(&["--cwd", "app", "--ecosystems", "npm"]); + assert_eq!( + prune_command(&scoped), + "socket-patch scan --prune --cwd app --ecosystems npm" + ); + let event = stale(&["2.0.0"], Evidence::Lockfile).event(&scoped); + assert_eq!(event.action, PatchAction::Skipped); + assert_eq!(event.error_code.as_deref(), Some(PATCH_STALE)); + assert!( + event.reason.as_deref().is_some_and( + |r| r.contains("`socket-patch scan --prune --cwd app --ecosystems npm`") + ), + "{event:?}" + ); + } + + #[test] + fn the_notice_names_each_stale_patch_once() { + let default = common(&[]); + assert!(notice_lines(&[], &default).is_empty()); + assert_eq!( + notice_lines(&[stale(&["2.0.0"], Evidence::Lockfile)], &default), + vec![ + "Warning: 1 manifest patch is stale (the project uses another version of the \ + package; skipped):" + .to_string(), + " - pkg:npm/widget@1.0.0 (the project lockfile resolves 2.0.0)".to_string(), + "Run `socket-patch scan --prune` to remove it from the manifest.".to_string(), + ] + ); + let two = [ + stale(&["2.0.0"], Evidence::Lockfile), + StalePatch { + purl: "pkg:npm/gadget@0.1.0".to_string(), + ..stale(&["0.2.0"], Evidence::Installed) + }, + ]; + let lines = notice_lines(&two, &default); + assert_eq!( + lines[0], + "Warning: 2 manifest patches are stale (the project uses another version of the \ + package; skipped):" + ); + assert_eq!(lines[2], " - pkg:npm/gadget@0.1.0 (0.2.0 is installed)"); + assert_eq!( + lines[3], + "Run `socket-patch scan --prune` to remove them from the manifest." + ); + } +} diff --git a/crates/socket-patch-cli/src/telemetry_outcomes.rs b/crates/socket-patch-cli/src/telemetry_outcomes.rs index 23330627fd..9c64052117 100644 --- a/crates/socket-patch-cli/src/telemetry_outcomes.rs +++ b/crates/socket-patch-cli/src/telemetry_outcomes.rs @@ -9,9 +9,11 @@ use std::collections::HashMap; use socket_patch_core::telemetry::{ - PatchOutcome, MODE_AGENT, MODE_HOSTED, MODE_VENDORED, OUTCOME_FAILED, + PatchOutcome, MODE_AGENT, MODE_HOSTED, MODE_VENDORED, OUTCOME_FAILED, OUTCOME_STALE, }; +use crate::commands::stale_patch::PATCH_STALE; + use crate::json_envelope::{PatchAction, PatchEvent}; /// The ecosystem a purl names, as events spell it: the ecosystem's CLI @@ -92,6 +94,8 @@ fn mode_of(event: &PatchEvent, default: &'static str) -> &'static str { /// [`outcome_of`]. The `code` is that event's `errorCode`, and only a /// failure or a skip has one; a failure with a `cause` (an apply's, /// under the generic `apply_failed`) reports the cause instead. +/// * A skip coded `patch_stale` is reported as the outcome `stale`, not +/// `skipped`: a record for a version the project no longer uses. pub(crate) fn patch_outcomes<'a>( events: impl IntoIterator, default_mode: &'static str, @@ -103,6 +107,11 @@ pub(crate) fn patch_outcomes<'a>( let Some((outcome, rank)) = outcome_of(event.action) else { continue; }; + // A stale patch is a skip with an outcome of its own: the run did + // not fail for it, and it is not one of the ordinary skips either. + let stale = event.action == PatchAction::Skipped + && event.error_code.as_deref() == Some(PATCH_STALE); + let outcome = if stale { OUTCOME_STALE } else { outcome }; let purl = event.purl.as_deref(); let Some(uuid) = event.uuid.clone().or_else(|| purl.and_then(&uuid_of)) else { continue; @@ -240,6 +249,36 @@ mod tests { ); } + /// A stale patch has its own outcome word, with its code beside it; + /// every other skip stays `skipped`. + #[test] + fn a_stale_skip_is_reported_as_stale() { + let events = [ + PatchEvent::new(PatchAction::Skipped, "pkg:npm/a@1.0.0") + .with_uuid(A) + .with_reason( + PATCH_STALE, + "The patch is for 1.0.0, but 2.0.0 is installed", + ), + PatchEvent::new(PatchAction::Skipped, "pkg:npm/b@1.0.0") + .with_uuid(B) + .with_reason("package_not_installed", "No installed package matches"), + ]; + assert_eq!( + patch_outcomes_of(&events, MODE_AGENT), + [ + entry(A, "npm", MODE_AGENT, "stale", Some("patch_stale")), + entry( + B, + "npm", + MODE_AGENT, + "skipped", + Some("package_not_installed") + ), + ] + ); + } + #[test] fn the_mode_is_the_events_own_when_it_has_one() { let events = [ diff --git a/crates/socket-patch-core/src/telemetry.rs b/crates/socket-patch-core/src/telemetry.rs index 107f21ac7a..0b2b9fb35b 100644 --- a/crates/socket-patch-core/src/telemetry.rs +++ b/crates/socket-patch-core/src/telemetry.rs @@ -616,6 +616,12 @@ pub const MODE_VENDORED: &str = "vendored"; /// The [`PatchOutcome::outcome`] of a patch the run could not act on. pub const OUTCOME_FAILED: &str = "failed"; +/// The [`PatchOutcome::outcome`] of a stale patch: a record for a version +/// of a package the project no longer uses. The run skipped it and did not +/// fail for it, so it is counted under `outcomes.stale` and never under +/// `failure_codes`. +pub const OUTCOME_STALE: &str = "stale"; + /// How many patches one event names. A run over more names this many, /// the failed ones first, and says so (`patches_truncated`); the counts /// beside the list are of the whole run. @@ -646,10 +652,10 @@ pub struct PatchOutcome { /// patch the project does not hold has [`MODE_UNKNOWN`]. pub mode: &'static str, /// What happened: `applied`, `rolled_back`, `removed`, `downloaded`, - /// `failed`, `skipped`, … (the command's own vocabulary). + /// `failed`, `skipped`, `stale`, … (the command's own vocabulary). pub outcome: &'static str, - /// The stable code of a `failed` or `skipped` outcome - /// (`hash_mismatch`, `already_patched`, …). + /// The stable code of a `failed`, `skipped` or `stale` outcome + /// (`hash_mismatch`, `already_patched`, `patch_stale`, …). #[serde(skip_serializing_if = "Option::is_none")] pub code: Option, } @@ -2932,6 +2938,41 @@ mod tests { ); } + /// A stale patch is counted as its own outcome: it is no failure, so + /// it adds no `failure_codes`, alone or beside one. + #[test] + fn a_stale_patch_is_counted_apart_from_failures() { + let stale = outcome( + UUID_A, + "npm", + MODE_AGENT, + OUTCOME_STALE, + Some("patch_stale"), + ); + let alone = with_patches(serde_json::json!({}), std::slice::from_ref(&stale)); + assert_eq!(alone["outcomes"], serde_json::json!({ "stale": 1 })); + assert!(alone.get("failure_codes").is_none(), "{alone}"); + assert_eq!(alone["patches"][0]["outcome"], "stale"); + assert_eq!(alone["patches"][0]["code"], "patch_stale"); + + let failed = outcome( + UUID_B, + "npm", + MODE_AGENT, + OUTCOME_FAILED, + Some("hash_mismatch"), + ); + let mixed = with_patches(serde_json::json!({}), &[stale, failed]); + assert_eq!( + mixed["outcomes"], + serde_json::json!({ "failed": 1, "stale": 1 }) + ); + assert_eq!( + mixed["failure_codes"], + serde_json::json!({ "hash_mismatch": 1 }) + ); + } + /// An event names at most [`MAX_REPORTED_PATCHES`] patches, the failed /// ones first, and says when it dropped some; the counts beside the /// list stay those of the whole run. diff --git a/crates/socket-patch-core/src/utils/purl_key.rs b/crates/socket-patch-core/src/utils/purl_key.rs index d9ae5740c8..2a2f1a3214 100644 --- a/crates/socket-patch-core/src/utils/purl_key.rs +++ b/crates/socket-patch-core/src/utils/purl_key.rs @@ -159,6 +159,35 @@ impl PurlKey { pub fn into_string(self) -> String { self.0 } + + /// The key split into its package (`pkg:npm/@scope/x`) and its version + /// (`1.2.3`); `None` for a key with no version or no name. + pub fn package_and_version(&self) -> Option<(&str, &str)> { + let coordinate = self.0.strip_prefix("pkg:")?.split_once('/')?.1; + let at = coordinate.rfind('@').filter(|&at| at > 0)?; + let split = self.0.len() - coordinate.len() + at; + let (package, version) = (&self.0[..split], &self.0[split + 1..]); + (!version.is_empty()).then_some((package, version)) + } + + /// `other`'s version when it is another release of this key's package: + /// the same package (type, namespace and name, compared as keys + /// compare them) and a different release. `None` for the same release, + /// under PEP 440 equality for PyPI (`1.16` and `1.16.0`), and for + /// another package. + pub fn other_release<'a>(&self, other: &'a PurlKey) -> Option<&'a str> { + let (package, version) = self.package_and_version()?; + let (other_package, other_version) = other.package_and_version()?; + if package != other_package || version == other_version { + return None; + } + if package.starts_with("pkg:pypi/") + && crate::utils::pep440::versions_equal(version, other_version) + { + return None; + } + Some(other_version) + } } impl fmt::Display for PurlKey { @@ -255,6 +284,79 @@ mod tests { use super::*; use crate::utils::composer_version::composer_versions_equivalent; + #[test] + fn a_key_splits_into_package_and_version() { + let split = |purl: &str| { + PurlKey::new(purl) + .package_and_version() + .map(|(package, version)| (package.to_string(), version.to_string())) + }; + let pair = |package: &str, version: &str| Some((package.to_string(), version.to_string())); + assert_eq!( + split("pkg:npm/left-pad@1.3.0"), + pair("pkg:npm/left-pad", "1.3.0") + ); + assert_eq!( + split("pkg:npm/%40scope/x@1.0.0?artifact_id=a"), + pair("pkg:npm/@scope/x", "1.0.0") + ); + assert_eq!( + split("pkg:maven/org.example/lib@2.1"), + pair("pkg:maven/org.example/lib", "2.1") + ); + // No version, or a scope's `@` alone: nothing to split. + assert_eq!(split("pkg:npm/left-pad"), None); + assert_eq!(split("pkg:npm/@scope/x"), None); + assert_eq!(split("pkg:npm/left-pad@"), None); + assert_eq!(split("not a purl"), None); + } + + #[test] + fn other_release_names_another_version_of_the_same_package() { + let other = |a: &str, b: &str| { + PurlKey::new(a) + .other_release(&PurlKey::new(b)) + .map(str::to_string) + }; + assert_eq!( + other("pkg:npm/a@1.0.0", "pkg:npm/a@2.0.0").as_deref(), + Some("2.0.0") + ); + // The same release, in any spelling, is not another one. + assert_eq!(other("pkg:npm/a@1.0.0", "pkg:npm/a@1.0.0?x=y"), None); + assert_eq!(other("pkg:pypi/six@1.16", "pkg:pypi/Six@1.16.0"), None); + assert_eq!( + other( + "pkg:composer/psr/log@3.0.2", + "pkg:composer/psr/log@v3.0.2.0" + ), + None + ); + assert_eq!( + other( + "pkg:nuget/Newtonsoft.Json@13.0.3", + "pkg:nuget/newtonsoft.json@13.0.3.0" + ), + None + ); + // Names fold as keys fold them. + assert_eq!( + other( + "pkg:pypi/typing_extensions@4.0.0", + "pkg:pypi/typing-extensions@4.12.2" + ) + .as_deref(), + Some("4.12.2") + ); + // Another package, or another ecosystem's package of the same name. + assert_eq!(other("pkg:npm/a@1.0.0", "pkg:npm/ab@2.0.0"), None); + assert_eq!(other("pkg:npm/a@1.0.0", "pkg:pypi/a@2.0.0"), None); + assert_eq!(other("pkg:npm/a@1.0.0", "pkg:npm/@scope/a@2.0.0"), None); + // Nothing to compare without a version on both sides. + assert_eq!(other("pkg:npm/a", "pkg:npm/a@2.0.0"), None); + assert_eq!(other("pkg:npm/a@1.0.0", "pkg:npm/a"), None); + } + #[test] fn canonical_fast_path_matches_the_rebuild() { for purl in [ From 52751eb637a34e86cd06ebd70e36bb52f0a39a0a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 4 Dec 2026 14:51:47 -0500 Subject: [PATCH 2/6] Cover stale patches in scan, nested applies, tests and docs - A scan that prunes after its apply (`--prune` / `--sync`) removes the stale records in the same run, so the apply it runs no longer asks for them to be pruned. - The remedy an apply run by `get` or `scan` prints leaves out the absolute path of the default manifest it was handed. - Integration tests: apply (alone, beside a live patch, beside a record with no evidence, `--silent`, `--check`, a scoped remedy), scan (the notice, its `--json` warning, pruning, agent and sync runs) and the telemetry of an apply and of an agent scan. - CLI contract, usage and configuration docs describe the `patch_stale` skip, the run warning and the `stale` telemetry outcome. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 15 +- .../src/commands/agent_download.rs | 7 + crates/socket-patch-cli/src/commands/apply.rs | 28 +- crates/socket-patch-cli/src/commands/get.rs | 4 + .../socket-patch-cli/src/commands/scan/mod.rs | 1 + .../src/commands/stale_patch.rs | 33 +- crates/socket-patch-cli/tests/apply/main.rs | 1 + .../tests/apply/stale_patch_skip.rs | 311 ++++++++++++++++++ .../tests/cli/telemetry_e2e.rs | 144 ++++++++ .../socket-patch-cli/tests/get/get_fixture.rs | 1 + .../tests/in_process_agent_patch_replace.rs | 1 + .../tests/in_process_get_update_count.rs | 1 + crates/socket-patch-cli/tests/scan/main.rs | 1 + .../tests/scan/scan_stale_patches.rs | 197 +++++++++++ docs/configuration.md | 2 +- docs/usage.md | 18 +- 16 files changed, 749 insertions(+), 16 deletions(-) create mode 100644 crates/socket-patch-cli/tests/apply/stale_patch_skip.rs create mode 100644 crates/socket-patch-cli/tests/scan/scan_stale_patches.rs diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index fdb6df3ad8..5132de048d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -247,8 +247,8 @@ A missing referenced diff does not remove that protection. changed, and a skipped entry is not reconciled away as dropped. - Skipped events carry a stable `errorCode` and a human-readable `reason`. `user_patch_conflict` identifies project patch/replacement metadata and names - its source; `vendored`, `already_patched`, and `package_not_installed` explain - other apply skips. A conflict introduced after selection is still `skipped` + its source; `vendored`, `already_patched`, `package_not_installed`, and + `patch_stale` explain other apply skips. A conflict introduced after selection is still `skipped` by nested apply, with its selected purl and UUID, even on an otherwise successful run. It never contributes to `summary.applied`. Known selection-time skips are not emitted a second time by nested apply; newly discovered conflicts @@ -361,7 +361,7 @@ Beyond the globals above, each subcommand defines a small set of local arguments | Subcommand | Local arg | Env var | Purpose | |---|---|---|---| | `apply` | `--force` / `-f` | — | Bypass beforeHash check. A file of the patch that is missing on disk is skipped instead of failing the package, and named in a `patch_files_skipped` warning | -| `apply` | `--check` | — | Read-only audit that every in-scope (`--ecosystems`) manifest patch is in place, for CI / GitHub-App auditing (v5.0: previously Go-only, which passed on any unpatched non-Go tree). Local Go patches: the committed `.socket/go-patches/` copies and `go.mod` `replace` directives match the manifest (`go_redirect_drift`). Every other patch: each installed copy hashes to the record's `afterHash` — the `vex` verifier over the `vex` copy lookup; the copies are narrowed by `apply`'s own rules: a release variant (a qualified purl such as `?artifact_id=` / `?platform=`) is judged only on the copies holding its distribution, matched against every variant of its base as `apply` matches them, and an installed copy that holds none of them is drift of the base purl (`no_matching_variant`, the copy `apply` fails with "no matching variant found"; a Gradle / Ivy cache dir is exempt, as in `apply`); for gem, once a bundle-store copy exists the `gem env` fallback-home copies are not judged (`apply` treats them as best-effort). Drift is a `failed` event per patch with `errorCode` `not_applied` (still unpatched), `hash_mismatch` (neither the original nor the patched bytes), `file_not_found`, `no_matching_variant` or `multi_release_unpatched_copy` (Maven: every file of the patch is in place, and a multi-release jar holds a patched class again under `META-INF/versions//` without the patch; the drift line names the jar, the class and the copy, see [Other copies of a patched class](#other-copies-of-a-patched-class)), status `partialFailure`, exit 1, and the human `Error: Patches are OUT OF SYNC:` report (printed even under `--silent`), which ends with the remedy ``Run `socket-patch apply ` to regenerate them.`` (left out when every drift is a `no_matching_variant` or `multi_release_unpatched_copy` one, which `apply` does not change; a gem's drift line names `bundle pristine `): `` repeats the check's own `--cwd`, `--manifest-path`, `-g` / `--global-prefix` and `--ecosystems` (each shell-quoted when needed), so running it verbatim heals the tree that was checked (v5.0, #1219). In sync is exit 0: `Patches are in sync (N checked).` and, under `--json`, a `skipped` event per verified patch (`errorCode: already_patched`). A record of an ecosystem this CLI does not support is not checked and the line says so instead (`unsupported_ecosystem`); a key that is not a purl is drift (`invalid_purl`). A patch with no installed copy is skipped as `apply` skips it (`package_not_installed`; the human line adds `M not installed, skipped`). A copy `apply` skips as not supported yet (a compiled conda build of a Python package that does not hold the patch) is not drift either: a `Warning:` line per copy, a `skipped` event per record and copy (`errorCode: conda_build_not_pypi_release`), and `K not supported, skipped` on the human line for the records with no other copy (see "Agent-mode apply to a conda build"). Vendor-owned patches are excluded (`vendor --check` audits them). Lock-free, fetch-free, offline-safe; it never writes. An unreadable manifest is drift (`manifest_unreadable`, exit 1) | +| `apply` | `--check` | — | Read-only audit that every in-scope (`--ecosystems`) manifest patch is in place, for CI / GitHub-App auditing (v5.0: previously Go-only, which passed on any unpatched non-Go tree). Local Go patches: the committed `.socket/go-patches/` copies and `go.mod` `replace` directives match the manifest (`go_redirect_drift`). Every other patch: each installed copy hashes to the record's `afterHash` — the `vex` verifier over the `vex` copy lookup; the copies are narrowed by `apply`'s own rules: a release variant (a qualified purl such as `?artifact_id=` / `?platform=`) is judged only on the copies holding its distribution, matched against every variant of its base as `apply` matches them, and an installed copy that holds none of them is drift of the base purl (`no_matching_variant`, the copy `apply` fails with "no matching variant found"; a Gradle / Ivy cache dir is exempt, as in `apply`); for gem, once a bundle-store copy exists the `gem env` fallback-home copies are not judged (`apply` treats them as best-effort). Drift is a `failed` event per patch with `errorCode` `not_applied` (still unpatched), `hash_mismatch` (neither the original nor the patched bytes), `file_not_found`, `no_matching_variant` or `multi_release_unpatched_copy` (Maven: every file of the patch is in place, and a multi-release jar holds a patched class again under `META-INF/versions//` without the patch; the drift line names the jar, the class and the copy, see [Other copies of a patched class](#other-copies-of-a-patched-class)), status `partialFailure`, exit 1, and the human `Error: Patches are OUT OF SYNC:` report (printed even under `--silent`), which ends with the remedy ``Run `socket-patch apply ` to regenerate them.`` (left out when every drift is a `no_matching_variant` or `multi_release_unpatched_copy` one, which `apply` does not change; a gem's drift line names `bundle pristine `): `` repeats the check's own `--cwd`, `--manifest-path`, `-g` / `--global-prefix` and `--ecosystems` (each shell-quoted when needed), so running it verbatim heals the tree that was checked (v5.0, #1219). In sync is exit 0: `Patches are in sync (N checked).` and, under `--json`, a `skipped` event per verified patch (`errorCode: already_patched`). A record of an ecosystem this CLI does not support is not checked and the line says so instead (`unsupported_ecosystem`); a key that is not a purl is drift (`invalid_purl`). A patch with no installed copy is skipped as `apply` skips it (`package_not_installed`; the human line adds `M not installed, skipped`). A stale patch (no installed copy, and the project uses another version of its package) is not drift either and is said in so many words: a `skipped` event with `errorCode: patch_stale`, the `Warning:` block `apply` prints for it (which names the version in use and the `scan --prune` remedy; stderr, hidden by `--silent`), and `S stale, skipped` on the human line in place of "not installed". A copy `apply` skips as not supported yet (a compiled conda build of a Python package that does not hold the patch) is not drift either: a `Warning:` line per copy, a `skipped` event per record and copy (`errorCode: conda_build_not_pypi_release`), and `K not supported, skipped` on the human line for the records with no other copy (see "Agent-mode apply to a conda build"). Vendor-owned patches are excluded (`vendor --check` audits them). Lock-free, fetch-free, offline-safe; it never writes. An unreadable manifest is drift (`manifest_unreadable`, exit 1) | | `vendor` | `--force` / `-f` | — | Bypass the installed-variant probe for multi-release ecosystems. That is its only effect: vendoring commits the patch server's verified artifact and never reads the installed files' content, so a missing or mismatched installed file vendors the same with or without `--force` (no warning) | | `vendor` | `--revert` | `SOCKET_VENDOR_REVERT` | Undo vendoring: restore recorded original lockfile fragments + remove `.socket/vendor/` artifacts. Works without a manifest. A package vendored over a hosted pin returns to its upstream registry entry, never to hosted (see "Takeover reconciliation") | | `vendor` | `--check` | — | Offline, read-only artifact and wiring audit; exits 1 on drift. Conflicts with `--revert`. | @@ -484,7 +484,7 @@ The route is taken only when **all** of these hold; otherwise the run takes the **Hosted-state visibility (`redirectState`, additive/MINOR).** Every non-hosted-mode, non-vendored-mode `scan --json` SUCCESS envelope (report-only, `--mode agent`/`--sync`, and the zero-discovery envelope) carries an additive top-level `redirectState` object whenever the project's lockfiles pin ≥ 1 hosted patch: `{ mode, records: [{purl, uuid}], wiringLive: [purl] }`. It is a descriptive STATE block, not a warning. `mode` is the constant `"hosted"`. **v5.0 (MAJOR shape change)**: hosted mode keeps no ledger, so `records` lists the hosted pins lockfile discovery finds (one per `(purl, uuid)`, the same discovery `vex` uses: a hosted URL counts only on `https://patch.socket.dev` or the `--patch-server-url` origin), and the v4 `ledger` and `records[].ledgerKey` keys are gone. Each record's `purl` is CANONICALIZED (qualifiers stripped, percent-decoded — e.g. `pkg:npm/@scope/pkg@1.0.0`, `pkg:gem/nokogiri@1.13.3`) to the same spelling `wiringLive` carries, so the join is a plain string compare. `wiringLive` is the subset of those pins among this run's *counted* purls (post-`--ecosystems`-filter) — computed once per run, the same set that feeds `hosted_wiring_retained`. A record missing from `wiringLive` is still wired; it just was not crawled/queried this run (an `--ecosystems` filter, a zero discovery). The key is omitted when no lockfile pins a hosted patch (and under `--global`), and error envelopes (the `--offline` refusal, all-batches-failed) are deliberately minimal and never carry it. A pre-v5 `.socket/vendor/redirect-state.json` is not read. Hosted-mode runs carry their own `redirect` payload and `details.mode: "hosted"` events instead, and vendored-mode runs carry the takeover warnings (their takeovers may restore pins mid-run) — neither duplicates a pre-run snapshot that could go stale. -**Agent-flow run-level warnings (additive).** An agent-mode apply (`--mode agent` / `--sync`, `--json`) may add a top-level `warnings[]` array of `{code, detail}` entries to the scan envelope (absent when none fired; each is also mirrored to stderr unless `--silent`). They surface cross-mode state the apply cannot change — never a status or exit-code change (hosted refusals set the precedent: exit 0 + warning). Codes (stable; new codes are additive/MINOR): `vendored_ownership_retained` — vendor-owned package(s) were skipped before download (each is also a `skipped` / `vendored` event); the detail names the purls and the migration path (`remove `, or `vendor --revert` which unwinds every vendored package, then re-run). `hosted_wiring_retained` — the lockfiles still pin scanned package(s) to a hosted patch (the agent run does not unwind hosted wiring — as of v5.0 that is `socket-patch rollback`'s job, which restores the upstream registry entries, or `remove ` per package); the detail names the purls and the options (stay `--mode hosted`, migrate via `scan --mode vendored`, or `socket-patch rollback`). The warning keys on the hosted pins lockfile discovery finds at scan time, so a flow that restored the upstream entries retires it. The human path prints the same `hosted_wiring_retained` text to stderr after an apply; the vendored counterpart is already covered by its per-package `[skip] … (vendored …)` lines. `ownership_not_restored` (v5.0; `apply` and `rollback` `warnings[]` alike) — a file WAS patched (or restored) but could not be given its original uid/gid (its mode is kept; the group is kept when the caller belongs to it); the detail is `: : patched, but ownership could not be restored to uid N gid M: ` and the human line `Warning: ` (stderr, muted by `--silent`); never a status or exit change. `go_installed_tool_stale` (v5.0; `apply`, dry runs included) — a `--global` Go apply patched a module cache copy that a tool installed with `go install` was built from before the patch; the detail names the binary and the `go install @` remedy (or, when they can't be inspected, what could not be checked); never a status or exit change. `stale_bytecode_not_removed` (`apply` and `rollback` `warnings[]` alike) — a `.py` file WAS patched (or restored) but CPython bytecode compiled from its previous bytes (`__pycache__/.[.opt-N].pyc`) could not be deleted, so Python may keep running the old code until it is removed; the detail is `: could not remove stale Python bytecode (: , …); …` and the human line `Warning: `; never a status or exit change. `patch_files_skipped` (`apply --force`) — a file of the patch is not on disk and was skipped; the detail is `: N patch file(s) not found on disk and skipped (--force): , …` and the human line `Warning: `. The package's event is `applied` with the files that were written, or, when the run wrote none and the files that exist are patched, `skipped` / `already_patched`; never a status or exit change. `cargo_build_cache_stale` (v5.0; `apply` and `rollback` `warnings[]` alike) — a cargo crate's bytes changed but its compiled copy in a project build directory could not be invalidated (a fingerprint directory that could not be removed, or a `build.build-dir` with a `{workspace-path-hash}` template); the detail names the crates to `cargo clean -p` before the next build, which may otherwise link the stale code; never a status or exit change. `nuget_stale_output_copies` (`apply`, `rollback` and `remove` `warnings[]` alike, and those of an agent-mode `scan` / `get`, both from the apply it runs and from the rollback of a recorded patch it replaces) — agent mode patches a NuGet package where NuGet restored it, but an application loads the copy a build put in the project's output (`bin///`, a publish directory), and a project built before the run still holds the previous file there. One warning per package and per kind of stale copy: the detail is `: N copies of under this project's bin and publish directories still hold : . …`, with at most five paths relative to `--cwd` and then `+N more`. `` and `` are `the unpatched file` and `An application run from that output loads the unpatched code.` for a copy that holds a file's original bytes after an apply; `the patched file` and `The package was restored, not what was built from it.` after `rollback` / `remove`; and `the file this run replaced in the package` and `The package's file was replaced, not what was built from it.` for a copy that holds a file the run replaced with another one: the file of a recorded patch that another patch replaces (whether `scan` / `get` rolled the recorded patch back first or the apply wrote over its file), or other content `apply` was told to overwrite. The detail names the remedy (`dotnet build` / `dotnet publish` copy the package's file into the output they write, one configuration per run; rebuild or republish each output listed, or delete it) and says that output written to another directory was not searched. The human line is `Warning: `. A copy is matched by file name (ASCII case ignored), then by content: one holding bytes the package had before the run is stale, one holding the package's current bytes is not, and one with any other bytes (another version, an earlier patch's file, a trimmed or ReadyToRun-compiled output) is counted in the package's first detail as not judged. Searched: every directory named `bin` or `publish` below `--cwd`, eight levels deep, which covers the SDK's `artifacts/bin` and `artifacts/publish` layout; never through a symbolic link, and never under `obj`, `packages`, `node_modules` (names compared without regard to ASCII case), a hidden directory or the package folder itself (however its path and `--cwd` are spelled), inside a `bin` or `publish` directory as outside one. The project tree is walked breadth-first and a directory's own `bin` / `publish` is searched before the walk goes deeper, so output near the root is found first. The search stops after listing 10,000 project directories, listing 10,000 directories inside output trees, or hashing 512 same-named files. A search that stops there with directories left says so: a stale copy's detail ends `The search stopped at its limit, so more copies may exist.`, and when it had found no stale copy the run gets one warning of the same code instead: `NuGet: the search of this project's bin and publish directories for stale copies of stopped at its limit of and found none in the part it searched. Not searched, with what is below them: . Output built before this run may still hold the unpatched file: rebuild or republish it (`dotnet build`, `dotnet publish`).` (`the patched file` after a rollback; the rollback of a replaced patch never prints that line, since the apply that normally follows it searches the same tree and does: a `--save-only` replacement, which runs no apply, prints none). An output path set in a project file (`OutputPath`, `PublishDir`) is not evaluated, and a single-file bundle holds no separate copy to find. A package an earlier run patched is checked on every run, so the warning repeats until each output is rebuilt or deleted (a copy that holds a replaced file is known only to the run that replaced it: later runs count it as not judged); a dry run reports only packages that are already patched, and a `--global` / `--global-prefix` run, which has no project, searches nothing. Nothing is written, and it is never a status or exit change: `apply --check` and `vex` do not read build output. +**Agent-flow run-level warnings (additive).** An agent-mode apply (`--mode agent` / `--sync`, `--json`) may add a top-level `warnings[]` array of `{code, detail}` entries to the scan envelope (absent when none fired; each is also mirrored to stderr unless `--silent`). They surface cross-mode state the apply cannot change — never a status or exit-code change (hosted refusals set the precedent: exit 0 + warning). Codes (stable; new codes are additive/MINOR): `vendored_ownership_retained` — vendor-owned package(s) were skipped before download (each is also a `skipped` / `vendored` event); the detail names the purls and the migration path (`remove `, or `vendor --revert` which unwinds every vendored package, then re-run). `hosted_wiring_retained` — the lockfiles still pin scanned package(s) to a hosted patch (the agent run does not unwind hosted wiring — as of v5.0 that is `socket-patch rollback`'s job, which restores the upstream registry entries, or `remove ` per package); the detail names the purls and the options (stay `--mode hosted`, migrate via `scan --mode vendored`, or `socket-patch rollback`). The warning keys on the hosted pins lockfile discovery finds at scan time, so a flow that restored the upstream entries retires it. The human path prints the same `hosted_wiring_retained` text to stderr after an apply; the vendored counterpart is already covered by its per-package `[skip] … (vendored …)` lines. `ownership_not_restored` (v5.0; `apply` and `rollback` `warnings[]` alike) — a file WAS patched (or restored) but could not be given its original uid/gid (its mode is kept; the group is kept when the caller belongs to it); the detail is `: : patched, but ownership could not be restored to uid N gid M: ` and the human line `Warning: ` (stderr, muted by `--silent`); never a status or exit change. `go_installed_tool_stale` (v5.0; `apply`, dry runs included) — a `--global` Go apply patched a module cache copy that a tool installed with `go install` was built from before the patch; the detail names the binary and the `go install @` remedy (or, when they can't be inspected, what could not be checked); never a status or exit change. `stale_bytecode_not_removed` (`apply` and `rollback` `warnings[]` alike) — a `.py` file WAS patched (or restored) but CPython bytecode compiled from its previous bytes (`__pycache__/.[.opt-N].pyc`) could not be deleted, so Python may keep running the old code until it is removed; the detail is `: could not remove stale Python bytecode (: , …); …` and the human line `Warning: `; never a status or exit change. `patch_files_skipped` (`apply --force`) — a file of the patch is not on disk and was skipped; the detail is `: N patch file(s) not found on disk and skipped (--force): , …` and the human line `Warning: `. The package's event is `applied` with the files that were written, or, when the run wrote none and the files that exist are patched, `skipped` / `already_patched`; never a status or exit change. `cargo_build_cache_stale` (v5.0; `apply` and `rollback` `warnings[]` alike) — a cargo crate's bytes changed but its compiled copy in a project build directory could not be invalidated (a fingerprint directory that could not be removed, or a `build.build-dir` with a `{workspace-path-hash}` template); the detail names the crates to `cargo clean -p` before the next build, which may otherwise link the stale code; never a status or exit change. `nuget_stale_output_copies` (`apply`, `rollback` and `remove` `warnings[]` alike, and those of an agent-mode `scan` / `get`, both from the apply it runs and from the rollback of a recorded patch it replaces) — agent mode patches a NuGet package where NuGet restored it, but an application loads the copy a build put in the project's output (`bin///`, a publish directory), and a project built before the run still holds the previous file there. One warning per package and per kind of stale copy: the detail is `: N copies of under this project's bin and publish directories still hold : . …`, with at most five paths relative to `--cwd` and then `+N more`. `` and `` are `the unpatched file` and `An application run from that output loads the unpatched code.` for a copy that holds a file's original bytes after an apply; `the patched file` and `The package was restored, not what was built from it.` after `rollback` / `remove`; and `the file this run replaced in the package` and `The package's file was replaced, not what was built from it.` for a copy that holds a file the run replaced with another one: the file of a recorded patch that another patch replaces (whether `scan` / `get` rolled the recorded patch back first or the apply wrote over its file), or other content `apply` was told to overwrite. The detail names the remedy (`dotnet build` / `dotnet publish` copy the package's file into the output they write, one configuration per run; rebuild or republish each output listed, or delete it) and says that output written to another directory was not searched. The human line is `Warning: `. A copy is matched by file name (ASCII case ignored), then by content: one holding bytes the package had before the run is stale, one holding the package's current bytes is not, and one with any other bytes (another version, an earlier patch's file, a trimmed or ReadyToRun-compiled output) is counted in the package's first detail as not judged. Searched: every directory named `bin` or `publish` below `--cwd`, eight levels deep, which covers the SDK's `artifacts/bin` and `artifacts/publish` layout; never through a symbolic link, and never under `obj`, `packages`, `node_modules` (names compared without regard to ASCII case), a hidden directory or the package folder itself (however its path and `--cwd` are spelled), inside a `bin` or `publish` directory as outside one. The project tree is walked breadth-first and a directory's own `bin` / `publish` is searched before the walk goes deeper, so output near the root is found first. The search stops after listing 10,000 project directories, listing 10,000 directories inside output trees, or hashing 512 same-named files. A search that stops there with directories left says so: a stale copy's detail ends `The search stopped at its limit, so more copies may exist.`, and when it had found no stale copy the run gets one warning of the same code instead: `NuGet: the search of this project's bin and publish directories for stale copies of stopped at its limit of and found none in the part it searched. Not searched, with what is below them: . Output built before this run may still hold the unpatched file: rebuild or republish it (`dotnet build`, `dotnet publish`).` (`the patched file` after a rollback; the rollback of a replaced patch never prints that line, since the apply that normally follows it searches the same tree and does: a `--save-only` replacement, which runs no apply, prints none). An output path set in a project file (`OutputPath`, `PublishDir`) is not evaluated, and a single-file bundle holds no separate copy to find. A package an earlier run patched is checked on every run, so the warning repeats until each output is rebuilt or deleted (a copy that holds a replaced file is known only to the run that replaced it: later runs count it as not judged); a dry run reports only packages that are already patched, and a `--global` / `--global-prefix` run, which has no project, searches nothing. Nothing is written, and it is never a status or exit change: `apply --check` and `vex` do not read build output. `patch_stale` (`scan` and `get` `warnings[]`) — the manifest holds a stale patch: a record for a version of a package the project no longer uses (see the `patch_stale` skip code). The detail is `: The patch is for , but (stale patch); run `socket-patch scan --prune ` to remove it from the manifest`, one warning per record. It comes from the apply an agent-mode run ends with (which skips the record; the standalone `apply --json` reports it as a `skipped` event instead), or, when the run applied nothing (report-only, `--dry-run`, nothing found or selected), from the scan itself, which compares the manifest with what it found installed or resolved by a lockfile (`the project uses `); never both in one run. A run that prunes (`--prune` / `--sync`, hosted mode aside) removes the record in its GC and reports no warning for it. The human path prints the same `Warning: N manifest patch(es) … stale …:` block as `apply`, once, on stderr (hidden by `--silent`). Never a status or exit change. `scan --prune` opts into garbage collection. When set, `scan` removes manifest entries for packages no longer present in the crawl, then deletes orphan blob files, and every obsolete diff and package archive, from `.socket/`. A blob is an orphan when no patch left in the manifest references it: the afterHash and beforeHash blobs of every remaining patch are kept, the same retention policy `repair` uses (the beforeHash blobs are an offline rollback's only restore data, and `repair` downloads afterHash blobs only). Diff and legacy package archives are never kept, even for a remaining patch: nothing reads them any more. Off by default (v3.0) so a temporary uninstall doesn't silently destroy manifest state. Under `--global`/`--global-prefix` the crawl covers only the global installs while the manifest is still `--cwd`'s, so the prune also keeps every entry the `--cwd` project accounts for (its installed packages and its lockfile-listed ones, exactly what the project's own `--prune` keeps): a global prune removes only entries neither scope has. Only entries whose ecosystem this run actually crawled are eligible: a `pkg:/` with no crawler in this build (a newer CLI's ecosystem in the committed manifest) is exempt — the crawl never looked for them, so their absence is not evidence of removal (same fail-safe as the `--ecosystems` filter, which narrows the query but never the prune's installed set). A Cargo entry is also exempt while its agent-mode copy is still patched: the project crawl looks up only the crates `Cargo.lock` resolves, but a crate the lock bumped or dropped keeps its patched copy in the machine-wide `$CARGO_HOME/registry/src` cache (nothing deletes it), and the entry holds the only blobs that can restore that copy. The wet pass keeps it with a `cargo_cache_patch_kept` warning naming the `socket-patch rollback ` that restores the copy and drops the entry; the `--dry-run` preview reports no event (and no warning) for it. A PyPI entry is exempt the same way: a project with no environment of its own is crawled only for the packages it declares, in the one interpreter it installs into, so a package it stopped declaring, or one an earlier release patched in another interpreter or a tool's environment, drops out of the crawl with its copy still patched. The copies `rollback ` restores are looked up by PURL, and for a project that installs into a shared interpreter so are the ones `rollback --global` restores (a project with an environment of its own never patched a copy outside it). The wet pass keeps an entry with a still-patched copy with a `pypi_installed_patch_kept` warning. A prune that an empty crawl skips drops no record, and reports the same warning for each recorded PyPI patch that is still on disk. The pass also reconciles vendored state (runs FIRST, under ONE apply-lock acquisition shared with the manifest prune — lock contention skips the whole pass without failing the scan; `--lock-timeout` is honored and a lock I/O error is reported rather than swallowed; the existence gate — a manifest file OR the vendor ledger's directory `.socket/vendor/`, which holds the artifacts too (a lost ledger leaves them), both cheap stats; one that cannot be stat'd is not absent, and the pass goes on to the read that reports it — runs BEFORE the lock, so a bare project never gets a `.socket/`; in the vendored scan arms the pass runs AFTER the vendor step): (a) ledger entries still tracked by a manifest record (manifest-mode entries written by standalone `vendor`) whose patch is gone from the manifest are reverted — `detached` entries (every `scan`/`get --mode vendored` entry, v5.0) have no manifest record to lose and are exempt from this leg; (b) EVERY ledger entry whose dependency is no longer in the lockfile graph is reverted and any manifest entry it still had dropped (v5.0: the check is about the lockfile, not the manifest, so embedded-record entries are no longer exempt; a missing or undeterminable lockfile keeps the entry, fail-safe); and (c) orphan `.socket/vendor//` dirs with no ledger entry are swept, except one a project file still installs from, which is kept with a `vendor_orphan_still_wired` warning (with no ledger entry at all the pass deletes no vendor dir, and only warns). A vendor ledger that cannot be read stops the vendored half before (a): nothing is reverted or swept, the pass carries a `vendor_state_unreadable` warning, and the manifest half still runs (the scan recovers the vendored purls it exempts from the committed artifacts). The pass also takes out the entries of hosted mode's pnpm registry route that no lockfile uses any more (see "pnpm registry route", *Cleanup*): from pnpm-workspace.yaml and the pnpm locks alone, under the same lock, for a project that holds something of a route (which then passes the existence gate without a manifest or a ledger; the lock's `.socket/` is removed again when it stays empty); never under `--global`. A run whose crawl found nothing still does this half and the vendored one; where the ledger names no entry the lock no longer wires, the vendored half reverts and sweeps nothing and only reports, read-only, what it could not reconcile (`vendor_state_unreadable`, `vendor_orphan_still_wired`; human mode: `Warning:` lines on stderr). The prune never deletes a zero-patch `.socket/manifest.json` (its `{"patches": {}}` + `setup` block stay). Under `--json` (v5.0, MAJOR) the pass is recorded into the scan envelope: each pruned manifest entry is a `removed` event with `details.manifest: true`, each reverted vendored entry a `removed` event (`errorCode: "vendor_reverted"`, `details.mode: "vendored"`), each kept entry a `skipped` / `vendor_revert_kept` event whose reason says why it was kept (a drift, or a project file that still installs from the artifact) and each entry whose revert failed a `skipped` / `vendor_revert_failed` event whose reason carries the revert's own (a GC revert failure never fails the run); a `--dry-run` preview reports the removals as `verified`. The artifact sweep is the envelope's `gc` (`summary.bytesFreed` mirrors it), the orphan vendor dirs swept are the top-level `removedVendorOrphanDirs` count, and each registry entry taken out is a `registry_entry_unused` event counted in `gc.removedRegistryEntries`. The pass's warnings join the top-level `warnings[]`: `vendor_state_unreadable` (the vendor ledger could not be read, so the vendored half did nothing; `status` and the exit code are the scan's own), `vendor_orphan_still_wired` (a vendor dir no ledger entry owns was kept because a project file still installs from it; the detail names the dir and the two ways out, restoring the missing ledger entries from version control, or pointing the lockfile back at the registry release and deleting the dir), `vendor_state_write_failed` (entries were reverted but the ledger rewrite failed), `manifest_write_failed` (the pruned manifest could not be written: no entry was pruned and no blob, diff or package archive was swept, since the manifest on disk still references them), `cleanup_failed` (an orphan sweep failed mid-way, or `.socket/` or one of its `blobs/`, `diffs/`, `packages/` directories is a symlink, which is never swept), `cargo_cache_patch_kept` (see above), `registry_cleanup_skipped` / `registry_cleanup_failed` (the registry-route half could not read or write the pnpm files), the reinstall advisories of the vendored reverts (`vendor_bun_reinstall_required`, `vendor_vlt_reinstall_required`, `vendor_pypi_reinstall_required`), and `vendor_revert_residual_reference` for an entry kept because a project file still installs from its artifact: its detail starts with the entry's purl and names that file (a revert's other warnings, such as `vendor_lock_entry_removed` or a drift keep's, are not repeated). A pass skipped at the lock (`lock_held` | `lock_io`) has no `gc` and no events, only a `gc_skipped` warning whose detail ends with the code. Human mode prints `GC: skipped: .`, one `GC: .` line per warning, and `GC: failed to revert N vendored entries: …` (singular for one), each purl followed by the revert's reason in parentheses. A drift keep is an entry the revert deliberately preserved (`vendor_artifact_kept` — undo the drift and re-run `vendor --revert` to finish). A keep for a project file that still installs from the artifact is not a drift (#1184): the revert restored its recorded wiring, and the way out is to point the file named by `vendor_revert_residual_reference` back at the registry release (or re-export it from the restored lock) and prune again. The preview runs no revert, so it sees neither keep and its `verified` reverts may over-promise what a wet run will actually reclaim. @@ -2485,7 +2485,7 @@ Telemetry is **on by default**. Each command reports its outcome as one JSON eve **What is sent.** `{event_sender_created_at, event_type, context: {version, platform, arch, command, ci, channel?}, session_id, metadata?, error?: {type, message}}`; no `event_kind`, so the backend stores it as a required event. `context` is the client version, `std::env::consts::OS` / `ARCH`, the subcommand, `ci` (a boolean: `CI` is set to anything but empty, `0` or `false`, or `GITHUB_ACTIONS` is set; never which provider, repository or job), and `channel`: the install channel of the running binary (`npm`, `cargo`, `homebrew`, `pypi`, `launcher_cache`, or `standalone` for any location none of those owns; the same detection `--update` uses, from the binary's canonical path, read from environment variables alone and resolved before `--update` swaps the binary), omitted when that path cannot be read. `session_id` is a random UUID generated per process and never stored, so it links the events of one run and nothing else. `metadata` holds only the per-event fields in the table. `error.message` (failure events) has every URL redacted (userinfo, grant tokens, signed query values), the home directory replaced by `~`, and is cut to 1,000 characters; it can otherwise quote a package name or a path. The request carries `User-Agent: SocketPatchCLI/` and, on the org route, `Authorization: Bearer `. Nothing else is sent: no package name, no file contents, no machine identifier. The patches an event names are named by patch UUID (see below), which identifies a patched package version to Socket. -**Patches.** An event about specific patches (the rows marked *patches*) adds to `metadata`: `patches`, at most 50 `{uuid, ecosystem, mode, outcome, code?}` entries, one per patch and mode, failed ones first (`mode`: `agent` / `hosted` / `vendored`; `outcome`: `applied`, `downloaded`, `rolled_back`, `removed`, `rebuilt`, `verified` (a dry run), `skipped`, `failed`; `code` is the event's `errorCode`, on `skipped` and `failed` only, and the event's `cause` where a failed apply event has one); `patches_truncated: true` when the cap dropped entries; `outcomes`, the count of patches per outcome over the whole run; `failure_codes`, the count of failed patches per `code` (`none` for one without) over the whole run, left out when none failed; and `ecosystems` / `modes`, their distinct values. They are derived from the run's `--json` events, so the two cannot disagree: several events for one patch (one per installed copy) fold into the one that says most (a failure over a change, a change over a preview, a preview over a skip). A run that named no patch adds none of these. The event body stays under 9,000 bytes (the server's dashboards cannot read one past 10,000 characters): an event that would not fit gives up the tail of its error message, down to 200 characters, and then entries off the end of its patch list. +**Patches.** An event about specific patches (the rows marked *patches*) adds to `metadata`: `patches`, at most 50 `{uuid, ecosystem, mode, outcome, code?}` entries, one per patch and mode, failed ones first (`mode`: `agent` / `hosted` / `vendored`; `outcome`: `applied`, `downloaded`, `rolled_back`, `removed`, `rebuilt`, `verified` (a dry run), `skipped`, `stale`, `failed`; `code` is the event's `errorCode`, on `skipped`, `stale` and `failed` only, and the event's `cause` where a failed apply event has one; `stale` is a `skipped` event coded `patch_stale`, a record for a version of a package the project no longer uses, which never makes the run's event `patch_apply_failed` and is never counted in `failure_codes`); `patches_truncated: true` when the cap dropped entries; `outcomes`, the count of patches per outcome over the whole run; `failure_codes`, the count of failed patches per `code` (`none` for one without) over the whole run, left out when none failed; and `ecosystems` / `modes`, their distinct values. They are derived from the run's `--json` events, so the two cannot disagree (an `apply` names every manifest entry no installed copy matched, as `stale` or as `skipped` / `package_not_installed`, on a run that succeeds as on one that fails): several events for one patch (one per installed copy) fold into the one that says most (a failure over a change, a change over a preview, a preview over a skip). A run that named no patch adds none of these. The event body stays under 9,000 bytes (the server's dashboards cannot read one past 10,000 characters): an event that would not fit gives up the tail of its error message, down to 200 characters, and then entries off the end of its patch list. **Failures.** Every failure event carries `error_code`: the code the run's `--json` envelope reports as its `error.code` (`patch_not_found`, `rollback_failed`, `vendor_revert_kept`, …), so a mistyped target is distinguishable from a patch that failed. It is the same with and without `--json`. A run whose envelope has failed events and no top-level error reports `apply_failed`, `vendor_failed`, `hosted_failed` or `repair_failed`. Two kinds of run report nothing, in every command: one that exits 2 on a usage error, and one that could not take the apply lock. @@ -2790,7 +2790,8 @@ command's integration tests check its output. | `not_in_platform_build` | `skipped` | apply (gem): the installed copy is the JRuby (`java`) build of the gem and no file of the patch is part of that build (a patch to the C extension or a library it packs). Nothing was written and nothing is left to do: the code the patch changes is not in that build, `apply --check` is in sync and `vex` attests the package (`vulnerable_code_not_present`), and a nested `scan --mode agent` counts the patch among those in place, as it counts `already_patched`. `reason` says so in plain words. rollback (gem): the same copy; nothing of the patch was applied to it, so nothing was restored. See "The JRuby build of a gem". | | `gem_fallback_home_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: a best-effort copy in a `gem env` home (the system gems, `~/.gem`, an rbenv or asdf home) was left unpatched, because it matched no variant or could not be written, while a bundle-path copy of the gem applied. The patch IS in effect on the copy bundler loads. Keyed by the base purl; the detail names the copy's path and the reason. Never flips status or exit. See "Copy classes". | | `gem_other_project_copy_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: the record is for another project's gem. Its every copy sits in a `gem env` home Bundler does not load the project's gems from, and the project's Bundler lock, which was read, does not list it. Nothing was applied. Keyed by the manifest key; the detail names the copy and gives `socket-patch rollback `, which drops the record and restores the copy if an earlier release patched it. Never flips status or exit; the human summary counts the patch as `not applicable`. With no lock read the gem is `package_not_installed` instead. See "Copy classes". | -| `package_not_installed` | `skipped` | apply: manifest entry has no matching installed package (an installed gem or PyPI copy that holds a patched file with content no record of its release was made for is `no_matching_variant` instead). When the project's lockfiles resolve the purl (a platform-gated optional dependency, a devDependency under `--omit=dev`), the detail says it is lockfile-only and the entry never fails the run, even when no other patch matched; only an all-miss run with an unmatched purl that no lock resolves exits 1 (`partialFailure`). **Cargo is never lockfile-only (v5.0, #616)**: `cargo fetch` unpacks every `Cargo.lock` entry (target-gated ones included), so a locked crate missing from `$CARGO_HOME/registry/src` was simply not fetched yet (a cold CI cache, a pruned `registry/src`) and the next `cargo build` would compile it unpatched; it counts as an unresolved purl (an all-miss run exits 1, as in 4.x) and its detail, the human error and the human warning say to run `cargo fetch` first. A crate `Cargo.lock` takes from a path, git, `[patch]` or `[replace]` source is never looked up in the registry cache (#506): cargo does not build that copy, so the same detail also names that case. | +| `patch_stale` | `skipped` | apply, `apply --check`, and the apply that `get` / `scan --mode agent` run: a stale patch. The manifest entry has no installed copy, no lockfile resolves its version, and the project's lockfiles or its installed tree hold the same package at another version (compared as canonical purls, so a name's spelling, a qualifier or an equal PEP 440 spelling is not another version): the project moved off the version the record patches, and nothing pruned the record. The lockfiles are asked first; the installed tree is crawled only for the entries no lockfile names (a project with no lockfile, a global run). The `reason` names the record's version, the version in use and where it was found (`the project lockfile resolves 2.0.0` / `2.0.0 is installed`), and the remedy ``socket-patch scan --prune ``, where `` repeats the run's `--cwd`, `--manifest-path`, `-g` / `--global-prefix` and `--ecosystems`. **Never a failure**: the status stays `success` and the exit 0, even when it is the only manifest entry or no other entry matched (such a run exited 1 as `package_not_installed` before); a `package_not_installed` entry with no such evidence beside it still fails an all-miss run. Human path: one `Warning: N manifest patch(es) … stale (the project uses another version of the package; skipped):` block on stderr that lists each purl with the version in use and ends with the remedy (hidden by `--silent`; under `--json` the events are the channel), and an `S stale` bucket in the summary line, shown only when non-zero, in place of counting the entry as `not found on disk`. `scan` names the same entries when it does not prune (see the `patch_stale` warning). Telemetry reports the patch with the outcome `stale`, not `skipped` or `failed`. | +| `package_not_installed` | `skipped` | apply: manifest entry has no matching installed package (a record whose package the project uses at another version is `patch_stale` instead; an installed gem or PyPI copy that holds a patched file with content no record of its release was made for is `no_matching_variant` instead). When the project's lockfiles resolve the purl (a platform-gated optional dependency, a devDependency under `--omit=dev`), the detail says it is lockfile-only and the entry never fails the run, even when no other patch matched; only an all-miss run with an unmatched purl that no lock resolves exits 1 (`partialFailure`). **Cargo is never lockfile-only (v5.0, #616)**: `cargo fetch` unpacks every `Cargo.lock` entry (target-gated ones included), so a locked crate missing from `$CARGO_HOME/registry/src` was simply not fetched yet (a cold CI cache, a pruned `registry/src`) and the next `cargo build` would compile it unpatched; it counts as an unresolved purl (an all-miss run exits 1, as in 4.x) and its detail, the human error and the human warning say to run `cargo fetch` first. A crate `Cargo.lock` takes from a path, git, `[patch]` or `[replace]` source is never looked up in the registry cache (#506): cargo does not build that copy, so the same detail also names that case. | | `apply_failed` | `failed` | apply: hash mismatch, write error, archive read error. Also a manifest key that is not a purl (see `invalid_purl`). The copy is left as it was: every file is staged (its blob read and hash-checked, with the file's final mode and owner) before the first is renamed into place, and a rename that fails puts the files already replaced back. The `error` names the file (`Cannot apply patch: - `); a blob that does not hold its hash's bytes is named with the remedy (`blob is corrupt … Run \`socket-patch repair\``). Only when putting a file back fails too does the `error` end with the files left changed; the original of such a file is kept beside it as `.socket-kept--`, a name no later run removes. A run killed between two renames can still leave some files patched; the next `apply` finishes it. A killed run also leaves `.socket-stage--` / `.socket-orig--` files beside the patch's files (staged content and the second names of the files being replaced, never the package's own content); an `apply` or `rollback` of that package removes them once they are ten minutes old. For a PyPI distribution it may also leave `.socket-optional-stage-RECORD-` / `.socket-optional-orig-RECORD-` in the `.dist-info`, from the rewrite of its `RECORD` rows; the next `apply`, `rollback` or `remove` of the package removes those at once (see "PyPI `.dist-info/RECORD` in agent mode"). | | `native_extension_not_rebuilt` | `failed` | apply (gem), and the apply that `get` / `scan --mode agent` run: the patch is incomplete. Its files were written into the installed copy and are left there (unlike `apply_failed`, where the copy is as it was), and the compiled code the copy runs is not the patch's: the build compiled nothing of it, or, on the JRuby build of a gem, the patch changes sources of the gem's jars and does not bring the jars. `error` says what was written and what is not in effect; `files` lists what this run wrote. The run exits 1 (`partialFailure`), the patch stays recorded, `apply --check` is out of sync and `vex` does not attest it; `rollback` restores the files. The same code is a `warnings[]` entry of the run, and the `apply --check` / `vex` tag of such a copy. See "A build that builds nothing of the patch". | | `multi_release_unpatched_copy` | `failed` (apply, `apply --check`); `skipped` (vex); run-level `warnings[]` | Maven, a record keyed by jar members: every member the patch lists is in place, and its jar, a multi-release jar, holds one of them again under `META-INF/versions//` without the patch, which a Java runtime of release `` or later loads instead of the patched member. apply, and the apply that `get` / `scan --mode agent` run: the patch is incomplete, as with `native_extension_not_rebuilt`. The jar was swapped and is left swapped (the base member is patched), the copy's event is `failed` under this code, the run exits 1 (`partialFailure`), the patch stays recorded and `rollback` restores the jar. `apply --check`: drift under this code. vex: the package is omitted under this code wherever `vex` reads the jar, which for a hosted pin is only where a local cache holds the suffixed jar (the section says when it is not read). In each, a `warnings[]` entry (for `apply --check`, the drift's `reason`) names the jar, the member and the versioned paths. The same code covers a jar that could not be checked for such a copy (the text then says "could not be checked"): one that is not checked is not taken for patched. Vendored mode vendors the jar and reports the same as a `vendor_jvm_degraded` warning with `reason: multi_release_unpatched_copy`, exit 0. No command clears it by being run again: it takes a patch that lists the versioned copy. See [Other copies of a patched class](#other-copies-of-a-patched-class). | @@ -3168,7 +3169,7 @@ outcome for a selected record, rather than inferring a write from exit 0. | Subcommand | Emits | |--------------|---| -| `apply` | `Applied` · `Skipped` (already_patched / package_not_installed / vendored) · `Failed` · `Verified` (dry-run) | +| `apply` | `Applied` · `Skipped` (already_patched / package_not_installed / patch_stale / vendored) · `Failed` · `Verified` (dry-run) | | `vendor` | `Applied` (= vendored; `command` routes) · `Rebuilt` (a reused artifact restored) · `Skipped` (refusals, warnings, unsupported ecosystems) · `Failed` · `Removed` (reconcile + `--revert`) · `Verified` (dry-run) | | `list` | `Discovered` (with `details.vulnerabilities`, `details.tier`, `details.license`, `details.description`, `details.exportedAt`; hosted pins (v5.0: one per `(purl, uuid)` the lockfiles wire) additionally carry `details.mode: "hosted"` and `details.lockfiles: []` (no `details.ledger` — hosted mode keeps no ledger; the human listing labels them `Mode: hosted (wired in )`), both additive and absent on manifest entries; v5.0: vendor-ledger records carry `details.mode: "vendored"` + `details.ledger: ".socket/vendor/state.json"` the same way, and the human listing labels them `Mode: vendored (recorded in .socket/vendor/state.json)`; a `state.json` that cannot be read or parsed degrades to nothing-to-consult with the stderr line `Warning: unreadable vendor ledger (); its vendored patches are not listed` — muted by `--silent`, exit unchanged). Above patched project directories, with no patch at `--cwd`: the additive top-level `projects[]`, each element `path` plus that directory's own `list` envelope | | `repair` | `Downloaded` (or `Verified` on dry-run; `details: {count, downloadMode: "file"}` — `downloadMode` is always `"file"` since v5.0 removed the diff download path; `details.corrupt` when some of the blobs replaced corrupt cache entries) · `Rebuilt` (vendored artifacts; `Verified` previews on dry-run; every vendored-phase event carries `details.mode: "vendored"`) · `Skipped` (vendor_uuid_mismatch, cleanup_failed) · artifact-level `Removed` (or `Verified`) GC carrier (`details.count`, `details.checked`, `bytes`) · `Failed` events (`download_failed`; `--offline`: one `offline_missing_sources` / `blob_corrupt` per blob it could not restore) · top-level `gc` (absent under `--download-only`) | diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 02661a20d2..2e554e8cb8 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -364,6 +364,10 @@ pub struct DownloadParams { /// gate holds (`scan`), so the nested apply need not repeat the /// manifest entries it skips for them. `get` checks only its selection. pub user_patch_skips_reported: bool, + /// The caller prunes the manifest right after the nested apply + /// (`scan --prune` / `--sync`), so the apply does not ask the user to + /// prune the stale records it skips: they are about to be removed. + pub prune_follows: bool, /// `--ecosystems` forwarded to the nested apply, so it never touches /// other ecosystems' packages the user filtered out. pub ecosystems: Option>, @@ -2047,6 +2051,7 @@ pub(crate) async fn run_nested_apply( common: GlobalArgs, json: bool, report_user_patch_skips: bool, + prune_follows: bool, recorded: &[(String, String)], client: &ApiClient, lock: LockGuard, @@ -2062,6 +2067,7 @@ pub(crate) async fn run_nested_apply( caller_json: json, report_user_patch_skips, command, + prune_follows, }), }; // The nested apply runs on the host's client: seeded, never rebuilt. @@ -2596,6 +2602,7 @@ pub async fn download_and_apply_patches_into( nested_apply_args_from_params(params, run, &manifest_path), params.json, !params.user_patch_skips_reported, + params.prune_follows, &recorded, run.api_client, lock, diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 7a9a5d90f1..70bcc4ac86 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -194,6 +194,19 @@ pub struct NestedApply { /// The command the user ran (`scan`, `get`): what the nested run's /// telemetry reports as its command. pub command: &'static str, + /// The caller prunes the manifest right after this apply (`scan + /// --prune` / `--sync`): the stale records it skips are about to be + /// removed, so it does not ask the user to remove them. + pub prune_follows: bool, +} + +impl ApplyArgs { + /// Whether this run names the stale patches it skips with the command + /// that removes them: not when the command that runs it prunes them + /// next. Their `skipped` events and telemetry stand either way. + fn announces_stale(&self) -> bool { + !self.nested.is_some_and(|nested| nested.prune_follows) + } } impl ApplyArgs { @@ -642,7 +655,7 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { // another version is stale, which is said in so many words: a patch // "not installed, skipped" reads as one the next install brings back. // It is no drift, since `apply` skips it too. - let stale = Box::pin(stale_patch::detect(&args.common, ¬_installed)).await; + let stale = boxed(|| stale_patch::detect(&args.common, ¬_installed)).await; stale_patch::without(&mut not_installed, &stale); print_stale_notice(args, &stale); @@ -2641,8 +2654,11 @@ pub(crate) async fn run_locked( ); // A stale patch is rarely one the caller selected, so its // skip would go unsaid in the caller's envelope: a warning - // each, which names the patch and the remedy. - warnings.extend(stale.iter().map(|patch| patch.warning(&args.common))); + // each, which names the patch and the remedy. Not when the + // caller prunes it next. + if args.announces_stale() { + warnings.extend(stale.iter().map(|patch| patch.warning(&args.common))); + } let (applied, skipped) = collect_apply_outcomes( &results, &caveats, @@ -3914,7 +3930,7 @@ async fn apply_patches_inner( let unresolved = unresolved_purls(&unmatched, &lockfile_only); // A record for a version the project no longer uses is stale: a // skip of its own, and no reason to fail either. - let stale = Box::pin(stale_patch::detect(&args.common, &unresolved)).await; + let stale = boxed(|| stale_patch::detect(&args.common, &unresolved)).await; stale_patch::without(&mut unmatched, &stale); let unresolved = unresolved_purls(&unmatched, &lockfile_only); // This diagnostic flips the exit code, so it is an error — and it @@ -4718,7 +4734,7 @@ async fn apply_patches_inner( let unresolved = unresolved_purls(&unmatched, &lockfile_only); // A record for a version the project no longer uses is stale: a skip // of its own, which never fails the run, alone or beside a live patch. - let stale = Box::pin(stale_patch::detect(&args.common, &unresolved)).await; + let stale = boxed(|| stale_patch::detect(&args.common, &unresolved)).await; stale_patch::without(&mut unmatched, &stale); let unresolved = unresolved_purls(&unmatched, &lockfile_only); @@ -5581,7 +5597,7 @@ fn print_lockfile_only_note( /// The human warning for stale patches (never an error; muted by /// `--silent` and `--json`, whose `skipped` events carry it). fn print_stale_notice(args: &ApplyArgs, stale: &[StalePatch]) { - if args.common.silent || args.common.json { + if args.common.silent || args.common.json || !args.announces_stale() { return; } for line in stale_patch::notice_lines(stale, &args.common) { diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index ac3e1fd395..8b631f9ac7 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -2491,6 +2491,7 @@ async fn save_and_apply_patch( nested_apply_args(&args.common, &manifest_path, quiet), args.common.json, true, + false, &recorded, client, lock, @@ -2588,6 +2589,7 @@ fn get_download_params(args: &GetArgs, save_only: bool, persist_blobs: bool) -> strict: args.common.strict, allow_patch_conflicts: args.common.allow_patch_conflicts, user_patch_skips_reported: false, + prune_follows: false, ecosystems: args.common.ecosystems.clone(), persist_blobs, patch_server_url: args.common.patch_server_url.clone(), @@ -4525,6 +4527,7 @@ mod tests { strict: false, allow_patch_conflicts: false, user_patch_skips_reported: false, + prune_follows: false, ecosystems: None, persist_blobs: false, patch_server_url: None, @@ -5410,6 +5413,7 @@ mod tests { strict: false, allow_patch_conflicts: false, user_patch_skips_reported: false, + prune_follows: false, ecosystems: None, // The vendor-detached posture this fn exists for. persist_blobs: false, diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 5ae989eb1a..fa5cc8ed75 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -1047,6 +1047,7 @@ fn download_params(args: &ScanArgs, save_only: bool, json: bool, silent: bool) - strict: args.common.strict, allow_patch_conflicts: args.common.allow_patch_conflicts, user_patch_skips_reported: true, + prune_follows: args.prune || args.sync, ecosystems: args.common.ecosystems.clone(), persist_blobs: args.mode != Some(ScanMode::Vendored), patch_server_url: args.common.patch_server_url.clone(), diff --git a/crates/socket-patch-cli/src/commands/stale_patch.rs b/crates/socket-patch-cli/src/commands/stale_patch.rs index a39974473f..eae48624ac 100644 --- a/crates/socket-patch-cli/src/commands/stale_patch.rs +++ b/crates/socket-patch-cli/src/commands/stale_patch.rs @@ -98,8 +98,24 @@ impl StalePatch { /// The command that removes stale records, scoped to the tree `common` /// names so it can be pasted as printed. +/// +/// An apply that `get` or `scan` runs is handed its manifest path made +/// absolute. When that path is the default manifest of `--cwd`, the +/// command leaves the flag out, as the one the user typed did. pub(crate) fn prune_command(common: &GlobalArgs) -> String { - format!("socket-patch scan --prune{}", crate::ui::scope_args(common)) + use socket_patch_core::constants::DEFAULT_PATCH_MANIFEST_PATH; + let absolute = |path: std::path::PathBuf| std::path::absolute(&path).unwrap_or(path); + let is_default = absolute(common.resolved_manifest_path()) + == absolute(common.cwd.join(DEFAULT_PATCH_MANIFEST_PATH)); + let scope = if is_default { + crate::ui::scope_args(&GlobalArgs { + manifest_path: DEFAULT_PATCH_MANIFEST_PATH.to_string(), + ..common.clone() + }) + } else { + crate::ui::scope_args(common) + }; + format!("socket-patch scan --prune{scope}") } /// The human notice for `stale` (empty when there is none): what is stale, @@ -387,6 +403,21 @@ mod tests { prune_command(&scoped), "socket-patch scan --prune --cwd app --ecosystems npm" ); + // A nested apply's absolute path to the default manifest of + // `--cwd` is left out; any other manifest is named. + let nested = GlobalArgs { + manifest_path: std::path::absolute("app/.socket/manifest.json") + .unwrap() + .display() + .to_string(), + ..scoped.clone() + }; + assert_eq!(prune_command(&nested), prune_command(&scoped)); + let elsewhere = common(&["--manifest-path", "other/manifest.json"]); + assert_eq!( + prune_command(&elsewhere), + "socket-patch scan --prune --manifest-path other/manifest.json" + ); let event = stale(&["2.0.0"], Evidence::Lockfile).event(&scoped); assert_eq!(event.action, PatchAction::Skipped); assert_eq!(event.error_code.as_deref(), Some(PATCH_STALE)); diff --git a/crates/socket-patch-cli/tests/apply/main.rs b/crates/socket-patch-cli/tests/apply/main.rs index 26193840b1..e9108d19e1 100644 --- a/crates/socket-patch-cli/tests/apply/main.rs +++ b/crates/socket-patch-cli/tests/apply/main.rs @@ -40,3 +40,4 @@ mod lockfile_only_skip; mod nuget_output_and_signing; mod pnpm_global_virtual_store; mod pypi_release_variants; +mod stale_patch_skip; diff --git a/crates/socket-patch-cli/tests/apply/stale_patch_skip.rs b/crates/socket-patch-cli/tests/apply/stale_patch_skip.rs new file mode 100644 index 0000000000..e5e6d11c00 --- /dev/null +++ b/crates/socket-patch-cli/tests/apply/stale_patch_skip.rs @@ -0,0 +1,311 @@ +//! `apply` on a manifest that still records a patch for a version of a +//! package the project no longer uses: the project moved to another +//! version, and nothing pruned the record. +//! +//! The installed tree is in its correct end state, so the record is a +//! stale patch: a `skipped` event coded `patch_stale` that never fails the +//! run, a warning that names the version the project uses and the command +//! that removes the record, and a bucket of its own in the summary. A +//! record for a package the project shows no sign of still fails the +//! all-miss run (the wrong-`--cwd` guard). + +use std::path::Path; + +use serde_json::json; + +use super::apply_fixture::{ + index_js_patches, install_npm_pkg, run_apply, stage_blob, write_manifest, MM_AFTER, MM_BEFORE, +}; +use crate::common::envelope::{event_for, events}; +use crate::common::{git_sha256, parse_json_envelope}; + +const STALE: &str = "pkg:npm/widget@1.0.0"; +const LIVE: &str = "pkg:npm/gadget@1.0.0"; +const PRUNE: &str = "`socket-patch scan --prune`"; + +/// `.socket/manifest.json` holding one record per purl, with the after +/// blob staged so the offline source guard is never what fires. +fn write_patches(root: &Path, purls: &[&str]) { + write_manifest( + root, + index_js_patches(purls, "57a1e000", MM_BEFORE, MM_AFTER), + ); + stage_blob(root, &git_sha256(MM_AFTER), MM_AFTER); +} + +/// A project that moved `widget` from 1.0.0 to 2.0.0: the lock resolves +/// 2.0.0 and 2.0.0 is installed. `gadget@1.0.0` is installed beside it. +fn write_moved_project(root: &Path, with_lock: bool) { + std::fs::write( + root.join("package.json"), + r#"{ "name": "app", "version": "1.0.0", + "dependencies": { "widget": "2.0.0", "gadget": "1.0.0" } }"#, + ) + .unwrap(); + if with_lock { + std::fs::write( + root.join("package-lock.json"), + serde_json::to_vec_pretty(&json!({ + "name": "app", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "app", "version": "1.0.0", + "dependencies": { "widget": "2.0.0", "gadget": "1.0.0" } + }, + "node_modules/gadget": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gadget/-/gadget-1.0.0.tgz" + }, + "node_modules/widget": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/widget/-/widget-2.0.0.tgz" + } + } + })) + .unwrap(), + ) + .unwrap(); + } + install_npm_pkg(root, "widget", "2.0.0", Some(MM_BEFORE)); + install_npm_pkg(root, "gadget", "1.0.0", Some(MM_BEFORE)); +} + +fn assert_stale_event(v: &serde_json::Value, found: &str) { + let ev = event_for(v, STALE); + assert_eq!(ev["action"], "skipped", "{ev}"); + assert_eq!(ev["errorCode"], "patch_stale", "{ev}"); + let reason = ev["reason"].as_str().unwrap_or_default(); + assert!( + reason.contains("The patch is for 1.0.0") && reason.contains(found), + "the reason names both versions; {ev}" + ); + assert!(reason.contains(PRUNE), "the reason names the remedy; {ev}"); +} + +/// The only manifest patch is stale and the lockfile says so. `apply` +/// exits 0 with a `patch_stale` skip: the run that used to fail every +/// install. +#[test] +fn a_stale_patch_alone_is_a_skip_and_the_run_succeeds() { + let tmp = tempfile::tempdir().unwrap(); + write_moved_project(tmp.path(), true); + write_patches(tmp.path(), &[STALE]); + + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline", "--json"], &[]); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 0, "a stale patch must not fail; {v}\n{stderr}"); + assert_eq!(v["status"], "success", "{v}"); + assert_eq!(events(&v).len(), 1, "{v}"); + assert_stale_event(&v, "the project lockfile resolves 2.0.0"); + assert!( + stderr.trim().is_empty(), + "--json keeps the notice in the envelope; {stderr}" + ); + + // Human path: a warning that names the patch, the version in use and + // the remedy, and never the exit-flipping error. + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline"], &[]); + assert_eq!(code, 0, "{stderr}"); + assert!(!stderr.contains("Error:"), "{stderr}"); + assert_eq!( + stderr.trim(), + "Warning: 1 manifest patch is stale (the project uses another version of the package; \ + skipped):\n - pkg:npm/widget@1.0.0 (the project lockfile resolves 2.0.0)\n\ + Run `socket-patch scan --prune` to remove it from the manifest.", + "{stderr}" + ); + assert!( + stdout.contains( + "Summary: 0 of 1 targeted patch applied, 0 already patched, 1 stale, 0 not found on \ + disk" + ), + "a stale patch is not counted as not found on disk; {stdout}" + ); +} + +/// The hook shape, `apply --silent`: exit 0 and nothing printed. +#[test] +fn silent_apply_on_a_stale_patch_exits_zero_and_prints_nothing() { + let tmp = tempfile::tempdir().unwrap(); + write_moved_project(tmp.path(), true); + write_patches(tmp.path(), &[STALE]); + + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline", "--silent"], &[]); + assert_eq!(code, 0, "{stderr}"); + assert!(stdout.trim().is_empty(), "{stdout}"); + assert!( + stderr.trim().is_empty(), + "--silent prints errors only; {stderr}" + ); +} + +/// A project with no lockfile: the installed tree is the evidence. +#[test] +fn an_installed_other_version_makes_the_patch_stale_without_a_lockfile() { + let tmp = tempfile::tempdir().unwrap(); + write_moved_project(tmp.path(), false); + write_patches(tmp.path(), &[STALE]); + + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline", "--json"], &[]); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 0, "{v}\n{stderr}"); + assert_eq!(v["status"], "success", "{v}"); + assert_stale_event(&v, "2.0.0 is installed"); + + let (code, _stdout, stderr) = run_apply(tmp.path(), &["--offline"], &[]); + assert_eq!(code, 0, "{stderr}"); + assert!( + stderr.contains(" - pkg:npm/widget@1.0.0 (2.0.0 is installed)"), + "{stderr}" + ); +} + +/// A stale patch beside a live one: the live patch is applied, the stale +/// one is its own skip, and the run succeeds. +#[test] +fn a_stale_patch_beside_a_live_one_does_not_change_the_run() { + let tmp = tempfile::tempdir().unwrap(); + write_moved_project(tmp.path(), true); + write_patches(tmp.path(), &[STALE, LIVE]); + + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline", "--json"], &[]); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 0, "{v}\n{stderr}"); + assert_eq!(v["status"], "success", "{v}"); + assert_eq!(event_for(&v, LIVE)["action"], "applied", "{v}"); + assert_stale_event(&v, "the project lockfile resolves 2.0.0"); + assert_eq!( + std::fs::read(tmp.path().join("node_modules/gadget/index.js")).unwrap(), + MM_AFTER + ); + assert_eq!( + std::fs::read(tmp.path().join("node_modules/widget/index.js")).unwrap(), + MM_BEFORE, + "the version the project uses is not the record's and stays as it is" + ); + + // A second, human run: the live patch is in place, the stale one is + // still named, and the summary counts it apart. + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline"], &[]); + assert_eq!(code, 0, "{stderr}"); + assert!( + stderr.contains("Warning: 1 manifest patch is stale") && stderr.contains(PRUNE), + "{stderr}" + ); + assert!( + !stderr.contains("had no matching installed package"), + "a stale patch is not the not-installed warning; {stderr}" + ); + assert!( + stdout.contains( + "Summary: 0 of 2 targeted patches applied, 1 already patched, 1 stale, 0 not found \ + on disk" + ), + "{stdout}" + ); + + // The dry run counts it apart too. + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline", "--dry-run"], &[]); + assert_eq!(code, 0, "{stderr}"); + assert!(stdout.contains(" 1 patch stale"), "{stdout}"); + assert!(!stdout.contains("not found on disk"), "{stdout}"); +} + +/// Control: a stale patch does not excuse a record the project shows no +/// sign of. The all-miss run still fails, and the error names only that +/// record. +#[test] +fn a_record_with_no_evidence_still_fails_beside_a_stale_one() { + let tmp = tempfile::tempdir().unwrap(); + write_moved_project(tmp.path(), true); + write_patches(tmp.path(), &[STALE, "pkg:npm/ghost@1.0.0"]); + + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline", "--json"], &[]); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 1, "{v}\n{stderr}"); + assert_eq!(v["status"], "partialFailure", "{v}"); + assert_eq!( + event_for(&v, "pkg:npm/ghost@1.0.0")["errorCode"], + "package_not_installed", + "{v}" + ); + assert_stale_event(&v, "the project lockfile resolves 2.0.0"); + + let (code, _stdout, stderr) = run_apply(tmp.path(), &["--offline"], &[]); + assert_eq!(code, 1, "{stderr}"); + let error_block: String = stderr + .lines() + .skip_while(|l| !l.starts_with("Error:")) + .take_while(|l| !l.starts_with("Check that")) + .collect::>() + .join("\n"); + assert!( + error_block.contains(" - pkg:npm/ghost@1.0.0") && !error_block.contains("widget"), + "the error names the record with no evidence only; {stderr}" + ); + assert!( + stderr.contains("Warning: 1 manifest patch is stale"), + "the stale patch is still named; {stderr}" + ); +} + +/// The remedy repeats the flags that pick the tree, so running it as +/// printed prunes the manifest this run read. +#[test] +fn the_remedy_is_scoped_to_the_project_the_run_read() { + let tmp = tempfile::tempdir().unwrap(); + let project = tmp.path().join("app"); + std::fs::create_dir_all(&project).unwrap(); + write_moved_project(&project, true); + write_patches(&project, &[STALE]); + + let (code, _stdout, stderr) = run_apply( + tmp.path(), + &["--offline", "--cwd", "app", "--ecosystems", "npm"], + &[], + ); + assert_eq!(code, 0, "{stderr}"); + assert!( + stderr.contains( + "Run `socket-patch scan --prune --cwd app --ecosystems npm` to remove it from the \ + manifest." + ), + "{stderr}" + ); +} + +/// `apply --check` names a stale patch as stale, not as "not installed, +/// skipped" (which reads as a patch the next install brings back), and +/// still exits 0: `apply` skips it too, so it is no drift. +#[test] +fn check_reports_a_stale_patch_and_stays_in_sync() { + let tmp = tempfile::tempdir().unwrap(); + write_moved_project(tmp.path(), true); + write_patches(tmp.path(), &[STALE]); + + let (code, stdout, stderr) = run_apply(tmp.path(), &["--check"], &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!( + stdout.trim(), + "Patches are in sync (0 patches checked; 1 patch stale, skipped)." + ); + assert!( + stderr.contains(" - pkg:npm/widget@1.0.0 (the project lockfile resolves 2.0.0)") + && stderr.contains(PRUNE), + "{stderr}" + ); + + let (code, stdout, stderr) = run_apply(tmp.path(), &["--check", "--json"], &[]); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 0, "{v}\n{stderr}"); + assert_eq!(v["status"], "success", "{v}"); + assert_stale_event(&v, "the project lockfile resolves 2.0.0"); + + // `--silent`: nothing, and still exit 0. + let (code, stdout, stderr) = run_apply(tmp.path(), &["--check", "--silent"], &[]); + assert_eq!(code, 0, "{stderr}"); + assert!(stdout.trim().is_empty() && stderr.trim().is_empty()); +} diff --git a/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs b/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs index b490be8d22..375edf3b85 100644 --- a/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs +++ b/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs @@ -1734,6 +1734,150 @@ async fn a_patch_whose_package_is_not_installed_is_named() { ); } +/// A patch for a version of a package the project moved off is stale: the +/// run succeeds (it failed as `package_not_installed` before), and its +/// `patch_applied` event names the patch as `stale` under `patch_stale`, +/// counted on its own and never among the failure codes. +#[tokio::test] +async fn a_stale_patch_is_reported_as_stale_and_never_as_a_failure() { + let mock = telemetry_only_mock().await; + let tmp = tempfile::tempdir().expect("tempdir"); + write_agent_project(tmp.path(), ORIGINAL); + // The project moved to another version; nothing pruned the record. + write_npm_package(tmp.path(), "tpkg", "2.0.0"); + + let (code, stdout, stderr) = run_cmd(tmp.path(), &mock.uri(), "apply", &[], &[]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + + let bodies = telemetry_bodies(&mock).await; + let types: Vec<&str> = bodies + .iter() + .map(|b| b["event_type"].as_str().unwrap()) + .collect(); + assert_eq!(types, ["patch_applied"], "{bodies:#?}"); + let event = &bodies[0]; + assert_eq!(event["context"]["command"], "apply"); + assert_eq!(event["metadata"]["patches_count"], 0, "{event:#}"); + assert_eq!( + only_patch(event), + &serde_json::json!({ + "uuid": PATCHED_UUID, + "ecosystem": "npm", + "mode": "agent", + "outcome": "stale", + "code": "patch_stale", + }) + ); + assert_eq!( + event["metadata"]["outcomes"], + serde_json::json!({ "stale": 1 }), + "{event:#}" + ); + assert!( + event["metadata"].get("failure_codes").is_none(), + "{event:#}" + ); + assert!(!event.to_string().contains("tpkg"), "{event:#}"); +} + +/// A stale record in the manifest of an agent-mode `scan`: the apply the +/// scan runs reports it once, under `scan`, beside the patch the scan +/// applied. The scan does not fail, and reports no second apply event. +#[tokio::test] +async fn an_agent_mode_scan_reports_a_stale_record_once() { + const PURL: &str = "pkg:npm/gadget@1.0.0"; + const UUID: &str = "12345678-1234-4123-8123-123456789abc"; + let batch = serde_json::json!({ + "packages": [{ + "purl": PURL, + "patches": [{ + "uuid": UUID, "purl": PURL, "tier": "free", + "cveIds": [], "ghsaIds": [], "severity": "high", + "title": "telemetry agent fixture" + }] + }], + "canAccessPaidPatches": false, + }); + // A new-file patch: afterHash is the git-blob sha256 of "patched\n". + let view = serde_json::json!({ + "uuid": UUID, + "purl": PURL, + "tier": "free", + "publishedAt": "2024-06-01T00:00:00Z", + "license": "MIT", + "description": "test patch", + "files": { + "package/index.js": { + "afterHash": "d2802877eb1c2f442d30d18abcb281cb2830875571624544f2f1acb36480997e", + "blobContent": "cGF0Y2hlZAo=", + } + }, + "vulnerabilities": {}, + }); + let mock = setup_mock(batch, Some(view)).await; + Mock::given(method("GET")) + .and(wiremock::matchers::path_regex(format!( + "^/v0/orgs/{ORG_SLUG}/patches/by-package/.+$" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": [{ + "uuid": UUID, "purl": PURL, + "publishedAt": "2024-06-01T00:00:00Z", + "description": "test patch", "license": "MIT", "tier": "free", + "vulnerabilities": {} + }], + "canAccessPaidPatches": false, + }))) + .mount(&mock) + .await; + let tmp = tempfile::tempdir().expect("tempdir"); + // `tpkg@1.0.0` is recorded, and the project now installs 2.0.0. + write_agent_project(tmp.path(), ORIGINAL); + write_npm_package(tmp.path(), "tpkg", "2.0.0"); + write_npm_package(tmp.path(), "gadget", "1.0.0"); + + let (code, stdout, stderr) = run_cmd( + tmp.path(), + &mock.uri(), + "scan", + &["--mode", "agent", "--yes"], + &[], + ); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + + let bodies = telemetry_bodies(&mock).await; + let types: Vec<&str> = bodies + .iter() + .map(|b| b["event_type"].as_str().unwrap()) + .collect(); + assert_eq!( + types, + ["patch_scanned", "patch_fetched", "patch_applied"], + "{bodies:#?}" + ); + let applied = &bodies[2]; + assert_eq!(applied["context"]["command"], "scan"); + assert_eq!(applied["metadata"]["patches_count"], 1, "{applied:#}"); + assert_eq!( + applied["metadata"]["outcomes"], + serde_json::json!({ "applied": 1, "stale": 1 }), + "{applied:#}" + ); + assert!( + applied["metadata"].get("failure_codes").is_none(), + "{applied:#}" + ); + let stale: Vec<&serde_json::Value> = applied["metadata"]["patches"] + .as_array() + .expect("patches[]") + .iter() + .filter(|p| p["outcome"] == "stale") + .collect(); + assert_eq!(stale.len(), 1, "{applied:#}"); + assert_eq!(stale[0]["uuid"], PATCHED_UUID); + assert_eq!(stale[0]["code"], "patch_stale"); +} + /// A run that could not get the patched content (the blob is gone and the /// download fails) reports the stage that stopped it as its `error_code`. #[tokio::test] diff --git a/crates/socket-patch-cli/tests/get/get_fixture.rs b/crates/socket-patch-cli/tests/get/get_fixture.rs index a4563372c1..b6a5bc3d19 100644 --- a/crates/socket-patch-cli/tests/get/get_fixture.rs +++ b/crates/socket-patch-cli/tests/get/get_fixture.rs @@ -295,6 +295,7 @@ pub fn engine_params(root: &Path) -> DownloadParams { strict: false, allow_patch_conflicts: false, user_patch_skips_reported: false, + prune_follows: false, ecosystems: None, persist_blobs: true, patch_server_url: None, diff --git a/crates/socket-patch-cli/tests/in_process_agent_patch_replace.rs b/crates/socket-patch-cli/tests/in_process_agent_patch_replace.rs index b4b77827dc..4465230200 100644 --- a/crates/socket-patch-cli/tests/in_process_agent_patch_replace.rs +++ b/crates/socket-patch-cli/tests/in_process_agent_patch_replace.rs @@ -556,6 +556,7 @@ async fn engine_get( strict: false, allow_patch_conflicts: false, user_patch_skips_reported: false, + prune_follows: false, ecosystems: None, persist_blobs: true, patch_server_url: None, diff --git a/crates/socket-patch-cli/tests/in_process_get_update_count.rs b/crates/socket-patch-cli/tests/in_process_get_update_count.rs index d5dc3850e0..8c3ea962f8 100644 --- a/crates/socket-patch-cli/tests/in_process_get_update_count.rs +++ b/crates/socket-patch-cli/tests/in_process_get_update_count.rs @@ -93,6 +93,7 @@ fn params(root: &Path) -> DownloadParams { strict: false, allow_patch_conflicts: false, user_patch_skips_reported: false, + prune_follows: false, ecosystems: None, persist_blobs: true, patch_server_url: None, diff --git a/crates/socket-patch-cli/tests/scan/main.rs b/crates/socket-patch-cli/tests/scan/main.rs index b68542255b..dc622bc27b 100644 --- a/crates/socket-patch-cli/tests/scan/main.rs +++ b/crates/socket-patch-cli/tests/scan/main.rs @@ -45,6 +45,7 @@ mod scan_project_discovery_e2e; mod scan_proxy_fallback_e2e; mod scan_prune_corrupt_vendor_ledger; mod scan_render; +mod scan_stale_patches; mod scan_sync_e2e; #[cfg(unix)] mod scan_tty; diff --git a/crates/socket-patch-cli/tests/scan/scan_stale_patches.rs b/crates/socket-patch-cli/tests/scan/scan_stale_patches.rs new file mode 100644 index 0000000000..5cd2f4f2cf --- /dev/null +++ b/crates/socket-patch-cli/tests/scan/scan_stale_patches.rs @@ -0,0 +1,197 @@ +//! `scan` over a project whose manifest still records a patch for a +//! version of a package the project no longer uses (a stale patch). +//! +//! A scan that does not prune names the record and the command that +//! removes it: before, it said "No patches available for installed +//! packages" and left the record for `apply` to fail on. `--json` carries +//! it as a `patch_stale` warning. A pruning scan removes the record and +//! has nothing to name; an agent scan leaves the naming to the apply it +//! runs, once. + +use crate::common::envelope::parse_json_envelope; +use crate::scan_fixture::{ + mount_empty_batch, mount_one_patch_api, read_manifest, run_scan_agent, run_scan_api, + seed_manifest, write_npm_package, write_root_package_json, MINIMIST, +}; + +use wiremock::MockServer; + +const STALE: &str = "pkg:npm/widget@1.0.0"; +const STALE_UUID: &str = "57a1e000-0000-4000-8000-000000000001"; +const NOTICE: &str = + "Warning: 1 manifest patch is stale (the project uses another version of the package; \ + skipped):"; +const REMEDY: &str = "Run `socket-patch scan --prune` to remove it from the manifest."; + +/// `widget@2.0.0` installed, and a manifest record for `widget@1.0.0`. +fn moved_project() -> tempfile::TempDir { + let tmp = tempfile::tempdir().unwrap(); + write_root_package_json(tmp.path()); + write_npm_package(tmp.path(), "widget", "2.0.0", b"before\n"); + seed_manifest(tmp.path(), &[(STALE, STALE_UUID)]); + tmp +} + +fn stale_warnings(v: &serde_json::Value) -> Vec<&str> { + v["warnings"] + .as_array() + .map(|warnings| { + warnings + .iter() + .filter(|w| w["code"] == "patch_stale") + .filter_map(|w| w["detail"].as_str()) + .collect() + }) + .unwrap_or_default() +} + +/// A scan that finds nothing to patch still names the stale record and +/// how to remove it, on stderr; `--silent` keeps quiet. +#[tokio::test] +async fn a_scan_names_a_stale_record_and_the_remedy() { + let mock = MockServer::start().await; + mount_empty_batch(&mock).await; + let tmp = moved_project(); + + let (code, stdout, stderr) = run_scan_api(tmp.path(), &mock.uri(), &[]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("No patches available for installed packages."), + "{stdout}" + ); + assert!( + stderr.contains(NOTICE) + && stderr.contains(" - pkg:npm/widget@1.0.0 (the project uses 2.0.0)") + && stderr.contains(REMEDY), + "{stderr}" + ); + // Naming it changes nothing: the record is still there. + assert!(read_manifest(tmp.path())["patches"][STALE].is_object()); + + let (code, stdout, stderr) = run_scan_api(tmp.path(), &mock.uri(), &["--silent"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(!stderr.contains("stale"), "{stderr}"); +} + +/// `--json`: one `patch_stale` warning that names the record, the version +/// in use and the remedy. Never an event or a failure of the scan. +#[tokio::test] +async fn a_json_scan_carries_the_stale_record_as_a_warning() { + let mock = MockServer::start().await; + mount_empty_batch(&mock).await; + let tmp = moved_project(); + + let (code, stdout, stderr) = run_scan_api(tmp.path(), &mock.uri(), &["--json"]); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 0, "{v}\n{stderr}"); + assert_eq!(v["status"], "success", "{v}"); + assert_eq!( + stale_warnings(&v), + [ + "pkg:npm/widget@1.0.0: The patch is for 1.0.0, but the project uses 2.0.0 (stale \ + patch); run `socket-patch scan --prune` to remove it from the manifest" + ], + "{v}" + ); +} + +/// The remedy does what the notice says: the record is gone, the scan +/// that removed it names nothing, and neither does the next one. +#[tokio::test] +async fn a_pruning_scan_removes_the_record_and_names_nothing() { + let mock = MockServer::start().await; + mount_empty_batch(&mock).await; + let tmp = moved_project(); + + let (code, stdout, stderr) = run_scan_api(tmp.path(), &mock.uri(), &["--prune"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(!stderr.contains("stale"), "{stderr}"); + assert!(stdout.contains("GC: pruned 1 manifest entry"), "{stdout}"); + assert!(read_manifest(tmp.path())["patches"][STALE].is_null()); + + let (code, stdout, stderr) = run_scan_api(tmp.path(), &mock.uri(), &["--json"]); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 0, "{v}\n{stderr}"); + assert!(stale_warnings(&v).is_empty(), "{v}"); +} + +/// An agent scan that patches something runs `apply` over the manifest: +/// the apply names the stale record, and the scan does not name it a +/// second time, on stderr or in the envelope. The run still succeeds. +#[tokio::test] +async fn an_agent_scan_names_a_stale_record_once() { + let before = b"before\n"; + let mock = MockServer::start().await; + mount_one_patch_api(&mock, MINIMIST, before).await; + let tmp = moved_project(); + write_npm_package(tmp.path(), "minimist", "1.2.2", before); + + let (code, stdout, stderr) = run_scan_agent(tmp.path(), &mock.uri(), &["--json", "--yes"]); + let v = parse_json_envelope(&stdout); + assert_eq!( + code, 0, + "a stale record must not fail the scan; {v}\n{stderr}" + ); + assert_eq!(v["status"], "success", "{v}"); + assert_eq!( + std::fs::read(tmp.path().join("node_modules/minimist/index.js")).unwrap(), + b"after\n" + ); + let warnings = stale_warnings(&v); + assert_eq!(warnings.len(), 1, "{v}"); + assert_eq!( + warnings[0], + "pkg:npm/widget@1.0.0: The patch is for 1.0.0, but 2.0.0 is installed (stale patch); \ + run `socket-patch scan --prune` to remove it from the manifest", + "{v}" + ); + // The selected patch is the run's only event for a patch: the stale + // record is not one this run selected. + assert!( + v["events"] + .as_array() + .unwrap() + .iter() + .all(|e| e["purl"] != STALE), + "{v}" + ); + + // The human run over the same tree (the patch is already in place): + // one notice, from the apply. + let (code, stdout, stderr) = run_scan_agent(tmp.path(), &mock.uri(), &["--yes"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!( + stderr.matches("manifest patch is stale").count(), + 1, + "{stderr}" + ); +} + +/// `scan --sync` applies and then prunes: the stale record is removed in +/// the same run, so nothing asks the user to remove it, on stderr or in +/// the envelope. +#[tokio::test] +async fn a_syncing_scan_prunes_the_record_without_asking_for_it() { + let before = b"before\n"; + let mock = MockServer::start().await; + mount_one_patch_api(&mock, MINIMIST, before).await; + + let tmp = moved_project(); + write_npm_package(tmp.path(), "minimist", "1.2.2", before); + let (code, stdout, stderr) = run_scan_api(tmp.path(), &mock.uri(), &["--sync", "--yes"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(!stderr.contains("stale"), "{stderr}"); + assert!(!stderr.contains("scan --prune"), "{stderr}"); + let manifest = read_manifest(tmp.path()); + assert!(manifest["patches"][STALE].is_null(), "{manifest}"); + assert!(manifest["patches"][MINIMIST].is_object(), "{manifest}"); + + let tmp = moved_project(); + write_npm_package(tmp.path(), "minimist", "1.2.2", before); + let (code, stdout, stderr) = + run_scan_api(tmp.path(), &mock.uri(), &["--sync", "--yes", "--json"]); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 0, "{v}\n{stderr}"); + assert!(stale_warnings(&v).is_empty(), "{v}"); + assert!(read_manifest(tmp.path())["patches"][STALE].is_null()); +} diff --git a/docs/configuration.md b/docs/configuration.md index cb0ce2a9c0..29bf026d4e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -158,7 +158,7 @@ patch fails to apply, or is rolled back, far more often than the others: | Field | Value | | --- | --- | -| `patches` | Up to 50 entries, failed ones first. Each is `{uuid, ecosystem, mode, outcome}`: the patch UUID, the ecosystem name (`npm`, `pypi`, …), the mode it was patched in (`agent`, `hosted`, `vendored`), and what the run did (`applied`, `downloaded`, `rolled_back`, `removed`, `rebuilt`, `verified` on a dry run, `skipped`, `failed`). A `skipped` or `failed` entry adds `code`, the reason code `--json` reports (for example `already_patched`) | +| `patches` | Up to 50 entries, failed ones first. Each is `{uuid, ecosystem, mode, outcome}`: the patch UUID, the ecosystem name (`npm`, `pypi`, …), the mode it was patched in (`agent`, `hosted`, `vendored`), and what the run did (`applied`, `downloaded`, `rolled_back`, `removed`, `rebuilt`, `verified` on a dry run, `skipped`, `stale`, `failed`). A `skipped`, `stale` or `failed` entry adds `code`, the reason code `--json` reports (for example `already_patched`). `stale` is a patch for a version of a package the project no longer uses (`patch_stale`): the run skipped it and didn't fail | | `patches_truncated` | `true` when the run acted on more than 50 patches | | `outcomes` | How many patches ended each way, over the whole run | | `failure_codes` | How many failed patches had each `code`, over the whole run; left out when none failed | diff --git a/docs/usage.md b/docs/usage.md index c55d97c8e0..f670fd43ab 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -379,6 +379,22 @@ Once the required patch data is committed, `socket-patch apply --offline` works without downloading it again. `get --save-only` records a patch without applying it. `apply` skips packages owned by the vendor ledger. +A recorded patch is for one version of a package. When the project moves to another +version, the record is left with nothing to patch: a stale patch. `apply` skips it +with a warning and still exits 0, so the hook that runs after every install doesn't +fail. The warning names the version the project uses now and the command that +removes the record: + +```sh +socket-patch scan --prune +``` + +`apply --check` and `scan` name stale patches too, and `--silent` hides the warning. +A record is stale only when the project's lockfiles or its installed packages hold the +same package at another version. A record for a package the project doesn't have at +all still fails a run in which no patch matched, since that usually means the wrong +directory. + Deno uses agent mode. Cargo agent patches can affect a shared registry cache; so do Maven ones in `~/.m2` and the Coursier and Ivy caches sbt, Mill and scala-cli resolve into (restart a running sbt server, Bloop or Metals after @@ -404,7 +420,7 @@ lists it. | `report ...` | Tell Socket that a patch broke the build, the tests or the application | | `vendor --revert` | Undo vendoring from its recorded edits and remove the vendored artifacts | | `repair` | Restore missing or corrupt agent patch data and vendored artifacts using existing records, and clean unused data, including the pnpm registry entries of hosted patches that no lockfile uses any more | -| `scan --mode agent --prune` | Patch discovered packages and remove records for dependencies that left the project | +| `scan --mode agent --prune` | Patch discovered packages and remove records for dependencies that left the project, or moved to another version (stale patches) | | `scan` (hosted mode) | Also removes, on every run, the pnpm registry entries of hosted patches that are no longer needed | `show` reads the patch from the patch service and changes nothing. In a terminal it From dfcf655de35152b1a16de2f52b19aab0f45ae3ba Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 4 Dec 2026 15:06:11 -0500 Subject: [PATCH 3/6] Name the rollback that clears a stale patch whose old copy is still patched `scan --prune` keeps a Cargo or PyPI record while a copy of the record's version is still patched on the machine: a crate in the shared registry cache, a Python package in another interpreter or a tool's environment. For such a stale record the prune is not a remedy, so the warning, the event's reason and the run warning name `socket-patch rollback ` instead, with `-g` when the copy is one only a global rollback reaches. The rule is the one the prune keeps the record by, read from the same copies. Tests run the command as printed on a Cargo and a PyPI project: the copy is restored and the record is gone. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- crates/socket-patch-cli/src/commands/apply.rs | 12 +- .../socket-patch-cli/src/commands/scan/gc.rs | 18 +- .../socket-patch-cli/src/commands/scan/mod.rs | 11 +- .../src/commands/stale_patch.rs | 220 ++++++++++++++++-- .../src/ecosystem_dispatch.rs | 20 +- .../tests/apply/stale_patch_skip.rs | 154 +++++++++++- .../tests/e2e_pypi_multi_copy.rs | 89 +++++++ docs/usage.md | 11 + 9 files changed, 509 insertions(+), 28 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 5132de048d..9c56d06aae 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2790,7 +2790,7 @@ command's integration tests check its output. | `not_in_platform_build` | `skipped` | apply (gem): the installed copy is the JRuby (`java`) build of the gem and no file of the patch is part of that build (a patch to the C extension or a library it packs). Nothing was written and nothing is left to do: the code the patch changes is not in that build, `apply --check` is in sync and `vex` attests the package (`vulnerable_code_not_present`), and a nested `scan --mode agent` counts the patch among those in place, as it counts `already_patched`. `reason` says so in plain words. rollback (gem): the same copy; nothing of the patch was applied to it, so nothing was restored. See "The JRuby build of a gem". | | `gem_fallback_home_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: a best-effort copy in a `gem env` home (the system gems, `~/.gem`, an rbenv or asdf home) was left unpatched, because it matched no variant or could not be written, while a bundle-path copy of the gem applied. The patch IS in effect on the copy bundler loads. Keyed by the base purl; the detail names the copy's path and the reason. Never flips status or exit. See "Copy classes". | | `gem_other_project_copy_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: the record is for another project's gem. Its every copy sits in a `gem env` home Bundler does not load the project's gems from, and the project's Bundler lock, which was read, does not list it. Nothing was applied. Keyed by the manifest key; the detail names the copy and gives `socket-patch rollback `, which drops the record and restores the copy if an earlier release patched it. Never flips status or exit; the human summary counts the patch as `not applicable`. With no lock read the gem is `package_not_installed` instead. See "Copy classes". | -| `patch_stale` | `skipped` | apply, `apply --check`, and the apply that `get` / `scan --mode agent` run: a stale patch. The manifest entry has no installed copy, no lockfile resolves its version, and the project's lockfiles or its installed tree hold the same package at another version (compared as canonical purls, so a name's spelling, a qualifier or an equal PEP 440 spelling is not another version): the project moved off the version the record patches, and nothing pruned the record. The lockfiles are asked first; the installed tree is crawled only for the entries no lockfile names (a project with no lockfile, a global run). The `reason` names the record's version, the version in use and where it was found (`the project lockfile resolves 2.0.0` / `2.0.0 is installed`), and the remedy ``socket-patch scan --prune ``, where `` repeats the run's `--cwd`, `--manifest-path`, `-g` / `--global-prefix` and `--ecosystems`. **Never a failure**: the status stays `success` and the exit 0, even when it is the only manifest entry or no other entry matched (such a run exited 1 as `package_not_installed` before); a `package_not_installed` entry with no such evidence beside it still fails an all-miss run. Human path: one `Warning: N manifest patch(es) … stale (the project uses another version of the package; skipped):` block on stderr that lists each purl with the version in use and ends with the remedy (hidden by `--silent`; under `--json` the events are the channel), and an `S stale` bucket in the summary line, shown only when non-zero, in place of counting the entry as `not found on disk`. `scan` names the same entries when it does not prune (see the `patch_stale` warning). Telemetry reports the patch with the outcome `stale`, not `skipped` or `failed`. | +| `patch_stale` | `skipped` | apply, `apply --check`, and the apply that `get` / `scan --mode agent` run: a stale patch. The manifest entry has no installed copy, no lockfile resolves its version, and the project's lockfiles or its installed tree hold the same package at another version (compared as canonical purls, so a name's spelling, a qualifier or an equal PEP 440 spelling is not another version): the project moved off the version the record patches, and nothing pruned the record. The lockfiles are asked first; the installed tree is crawled only for the entries no lockfile names (a project with no lockfile, a global run). The `reason` names the record's version, the version in use and where it was found (`the project lockfile resolves 2.0.0` / `2.0.0 is installed`), and the remedy ``socket-patch scan --prune ``, where `` repeats the run's `--cwd`, `--manifest-path`, `-g` / `--global-prefix` and `--ecosystems`. A Cargo or PyPI record whose copy of the old version is still patched on this machine (the shared registry cache, an environment that still holds the old release) is one `scan --prune` keeps, so its `reason` and its line in the warning name ``socket-patch rollback `` instead, which restores that copy and removes the record; `` gains `-g` when the copy is one only a global rollback reaches (a Python package in another interpreter or a tool's environment, a crate in the registry cache that a `cargo vendor` directory hides). In the warning those lines come first, and the `scan --prune` line then covers the rest. **Never a failure**: the status stays `success` and the exit 0, even when it is the only manifest entry or no other entry matched (such a run exited 1 as `package_not_installed` before); a `package_not_installed` entry with no such evidence beside it still fails an all-miss run. Human path: one `Warning: N manifest patch(es) … stale (the project uses another version of the package; skipped):` block on stderr that lists each purl with the version in use and ends with the remedy (hidden by `--silent`; under `--json` the events are the channel), and an `S stale` bucket in the summary line, shown only when non-zero, in place of counting the entry as `not found on disk`. `scan` names the same entries when it does not prune (see the `patch_stale` warning). Telemetry reports the patch with the outcome `stale`, not `skipped` or `failed`. | | `package_not_installed` | `skipped` | apply: manifest entry has no matching installed package (a record whose package the project uses at another version is `patch_stale` instead; an installed gem or PyPI copy that holds a patched file with content no record of its release was made for is `no_matching_variant` instead). When the project's lockfiles resolve the purl (a platform-gated optional dependency, a devDependency under `--omit=dev`), the detail says it is lockfile-only and the entry never fails the run, even when no other patch matched; only an all-miss run with an unmatched purl that no lock resolves exits 1 (`partialFailure`). **Cargo is never lockfile-only (v5.0, #616)**: `cargo fetch` unpacks every `Cargo.lock` entry (target-gated ones included), so a locked crate missing from `$CARGO_HOME/registry/src` was simply not fetched yet (a cold CI cache, a pruned `registry/src`) and the next `cargo build` would compile it unpatched; it counts as an unresolved purl (an all-miss run exits 1, as in 4.x) and its detail, the human error and the human warning say to run `cargo fetch` first. A crate `Cargo.lock` takes from a path, git, `[patch]` or `[replace]` source is never looked up in the registry cache (#506): cargo does not build that copy, so the same detail also names that case. | | `apply_failed` | `failed` | apply: hash mismatch, write error, archive read error. Also a manifest key that is not a purl (see `invalid_purl`). The copy is left as it was: every file is staged (its blob read and hash-checked, with the file's final mode and owner) before the first is renamed into place, and a rename that fails puts the files already replaced back. The `error` names the file (`Cannot apply patch: - `); a blob that does not hold its hash's bytes is named with the remedy (`blob is corrupt … Run \`socket-patch repair\``). Only when putting a file back fails too does the `error` end with the files left changed; the original of such a file is kept beside it as `.socket-kept--`, a name no later run removes. A run killed between two renames can still leave some files patched; the next `apply` finishes it. A killed run also leaves `.socket-stage--` / `.socket-orig--` files beside the patch's files (staged content and the second names of the files being replaced, never the package's own content); an `apply` or `rollback` of that package removes them once they are ten minutes old. For a PyPI distribution it may also leave `.socket-optional-stage-RECORD-` / `.socket-optional-orig-RECORD-` in the `.dist-info`, from the rewrite of its `RECORD` rows; the next `apply`, `rollback` or `remove` of the package removes those at once (see "PyPI `.dist-info/RECORD` in agent mode"). | | `native_extension_not_rebuilt` | `failed` | apply (gem), and the apply that `get` / `scan --mode agent` run: the patch is incomplete. Its files were written into the installed copy and are left there (unlike `apply_failed`, where the copy is as it was), and the compiled code the copy runs is not the patch's: the build compiled nothing of it, or, on the JRuby build of a gem, the patch changes sources of the gem's jars and does not bring the jars. `error` says what was written and what is not in effect; `files` lists what this run wrote. The run exits 1 (`partialFailure`), the patch stays recorded, `apply --check` is out of sync and `vex` does not attest it; `rollback` restores the files. The same code is a `warnings[]` entry of the run, and the `apply --check` / `vex` tag of such a copy. See "A build that builds nothing of the patch". | diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 70bcc4ac86..5ecd68bd40 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -655,7 +655,9 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { // another version is stale, which is said in so many words: a patch // "not installed, skipped" reads as one the next install brings back. // It is no drift, since `apply` skips it too. - let stale = boxed(|| stale_patch::detect(&args.common, ¬_installed)).await; + let socket_dir = args.common.socket_dir(); + let stale = + boxed(|| stale_patch::detect(&args.common, &manifest, &socket_dir, ¬_installed)).await; stale_patch::without(&mut not_installed, &stale); print_stale_notice(args, &stale); @@ -3930,7 +3932,8 @@ async fn apply_patches_inner( let unresolved = unresolved_purls(&unmatched, &lockfile_only); // A record for a version the project no longer uses is stale: a // skip of its own, and no reason to fail either. - let stale = boxed(|| stale_patch::detect(&args.common, &unresolved)).await; + let stale = + boxed(|| stale_patch::detect(&args.common, &manifest, &socket_dir, &unresolved)).await; stale_patch::without(&mut unmatched, &stale); let unresolved = unresolved_purls(&unmatched, &lockfile_only); // This diagnostic flips the exit code, so it is an error — and it @@ -4734,7 +4737,8 @@ async fn apply_patches_inner( let unresolved = unresolved_purls(&unmatched, &lockfile_only); // A record for a version the project no longer uses is stale: a skip // of its own, which never fails the run, alone or beside a live patch. - let stale = boxed(|| stale_patch::detect(&args.common, &unresolved)).await; + let stale = + boxed(|| stale_patch::detect(&args.common, &manifest, &socket_dir, &unresolved)).await; stale_patch::without(&mut unmatched, &stale); let unresolved = unresolved_purls(&unmatched, &lockfile_only); @@ -6045,6 +6049,7 @@ mod tests { version: "1.0.0".to_string(), others: vec!["2.0.0".to_string()], evidence: stale_patch::Evidence::Lockfile, + still_patched: None, }; let (applied, skipped) = collect_apply_outcomes( &[unchanged_copy, changed_copy, vendored, already_patched], @@ -6152,6 +6157,7 @@ mod tests { version: "1.0.0".to_string(), others: vec!["2.0.0".to_string()], evidence: stale_patch::Evidence::Lockfile, + still_patched: None, } } diff --git a/crates/socket-patch-cli/src/commands/scan/gc.rs b/crates/socket-patch-cli/src/commands/scan/gc.rs index abfc3b3ad4..2f8d66e519 100644 --- a/crates/socket-patch-cli/src/commands/scan/gc.rs +++ b/crates/socket-patch-cli/src/commands/scan/gc.rs @@ -915,23 +915,31 @@ fn detect_prunable( .collect() } -/// The stale records of `manifest`: the entries a `--prune` would drop +/// The stale records of `manifest`: the entries a `--prune` would judge /// ([`detect_prunable`]) whose package the scan found at another version -/// (`scanned_purls`: installed, or resolved by a lockfile). Sorted. +/// (`scanned_purls`: installed, or resolved by a lockfile). Sorted. The +/// ones the prune keeps for a copy that is still patched are marked, and +/// name `rollback` (see [`keep_patched_cargo_copies`]). /// /// A scan that does not prune names them with the remedy, as `apply` does /// for the ones it skips (see [`crate::commands::stale_patch`]); an entry /// for a package the scan found no version of is not among them. -pub(super) fn stale_records( +pub(super) async fn stale_records( + common: &GlobalArgs, manifest: &PatchManifest, + socket_dir: &Path, scanned_purls: &HashSet, vendored: &HashSet, ) -> Vec { - use crate::commands::stale_patch::{classify, Evidence}; + use crate::commands::stale_patch::{classify, mark_still_patched, Evidence}; let mut prunable = detect_prunable(manifest, scanned_purls, vendored); prunable.sort(); let scanned: Vec = scanned_purls.iter().map(|p| PurlKey::new(p)).collect(); - classify(&prunable, &scanned, Evidence::Project).0 + let mut stale = classify(&prunable, &scanned, Evidence::Project).0; + if !stale.is_empty() { + mark_still_patched(common, manifest, socket_dir, &mut stale).await; + } + stale } #[cfg(test)] diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index fa5cc8ed75..db6f9365e2 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2748,7 +2748,16 @@ async fn scan_project( // the command that does (hosted mode runs no GC, whatever it was told). let stale_records = match existing_manifest { Some(manifest) if !prune || hosted => { - gc::stale_records(manifest, &scanned_purls, &vendored_purls) + boxed(|| { + gc::stale_records( + &args.common, + manifest, + &socket_dir, + &scanned_purls, + &vendored_purls, + ) + }) + .await } _ => Vec::new(), }; diff --git a/crates/socket-patch-cli/src/commands/stale_patch.rs b/crates/socket-patch-cli/src/commands/stale_patch.rs index eae48624ac..1341af9f50 100644 --- a/crates/socket-patch-cli/src/commands/stale_patch.rs +++ b/crates/socket-patch-cli/src/commands/stale_patch.rs @@ -8,6 +8,13 @@ //! run for it, `apply --check` and `scan` name it, and `scan --prune` //! removes it. //! +//! One kind of record `scan --prune` keeps: a copy of the record's version +//! is still patched on the machine (a crate in the shared Cargo registry +//! cache, a Python package in a shared interpreter), and the record holds +//! what restores it. For such a record the remedy is the `rollback` that +//! restores the copy and then drops the record ([`StalePatch::still_patched`]), +//! with `-g` when the copy is one only a global rollback reaches. +//! //! A record is stale only on evidence: the project's lockfiles or its //! installed tree hold the same package at another version, and neither //! holds the record's own. A record for a package the project shows no @@ -16,6 +23,7 @@ use std::collections::{BTreeSet, HashMap}; use socket_patch_core::crawlers::Ecosystem; +use socket_patch_core::manifest::schema::PatchManifest; use socket_patch_core::utils::purl::normalize_purl; use socket_patch_core::utils::purl_key::PurlKey; @@ -41,6 +49,17 @@ pub(crate) enum Evidence { Project, } +/// Which `rollback` reaches a copy that is still patched. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum PatchedCopy { + /// `rollback ` with the run's own scope. + InScope, + /// Only `rollback -g`: a Python package in another interpreter + /// or a tool's environment, a crate in the registry cache that a + /// `cargo vendor` directory hides. + Global, +} + /// A manifest record whose package the project uses at another version. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct StalePatch { @@ -51,6 +70,11 @@ pub(crate) struct StalePatch { /// The versions the project uses instead: sorted, never empty. pub(crate) others: Vec, pub(crate) evidence: Evidence, + /// A copy of the record's version outside what the project uses is + /// still patched (or could not be read to tell): `scan --prune` keeps + /// the record, whose blobs are what restores that copy, and `rollback` + /// is what removes it ([`mark_still_patched`]). + pub(crate) still_patched: Option, } impl StalePatch { @@ -72,11 +96,22 @@ impl StalePatch { /// The reason of the `skipped` event: what the project uses instead, /// and the command that removes the record. pub(crate) fn detail(&self, common: &GlobalArgs) -> String { + let remedy = match self.still_patched { + Some(copy) => format!( + "a copy of {} on this machine is still patched, so run `{}` to restore it and \ + remove the patch from the manifest", + self.version, + rollback_command(common, &self.purl, copy) + ), + None => format!( + "run `{}` to remove it from the manifest", + prune_command(common) + ), + }; format!( - "The patch is for {}, but {} (stale patch); run `{}` to remove it from the manifest", + "The patch is for {}, but {} (stale patch); {remedy}", self.version, self.found(), - prune_command(common) ) } @@ -103,23 +138,49 @@ impl StalePatch { /// absolute. When that path is the default manifest of `--cwd`, the /// command leaves the flag out, as the one the user typed did. pub(crate) fn prune_command(common: &GlobalArgs) -> String { + format!("socket-patch scan --prune{}", scope(common)) +} + +/// The command that restores the copy of `purl` that is still patched and +/// then drops its record, scoped like [`prune_command`], with `-g` added +/// for a copy only a global rollback reaches. +fn rollback_command(common: &GlobalArgs, purl: &str, copy: PatchedCopy) -> String { + let scope = match copy { + PatchedCopy::Global if !common.global && common.global_prefix.is_none() => { + scope(&GlobalArgs { + global: true, + ..common.clone() + }) + } + _ => scope(common), + }; + format!( + "socket-patch rollback {}{scope}", + crate::ui::shell_word(purl) + ) +} + +/// The flags that pick the tree `common` names, as a pasteable suffix +/// (see [`crate::ui::scope_args`]), without a `--manifest-path` that is +/// the default manifest of `--cwd` spelled as an absolute path. +fn scope(common: &GlobalArgs) -> String { use socket_patch_core::constants::DEFAULT_PATCH_MANIFEST_PATH; let absolute = |path: std::path::PathBuf| std::path::absolute(&path).unwrap_or(path); let is_default = absolute(common.resolved_manifest_path()) == absolute(common.cwd.join(DEFAULT_PATCH_MANIFEST_PATH)); - let scope = if is_default { + if is_default { crate::ui::scope_args(&GlobalArgs { manifest_path: DEFAULT_PATCH_MANIFEST_PATH.to_string(), ..common.clone() }) } else { crate::ui::scope_args(common) - }; - format!("socket-patch scan --prune{scope}") + } } /// The human notice for `stale` (empty when there is none): what is stale, -/// what the project uses instead, and the remedy. +/// what the project uses instead, and the remedy. The records `scan +/// --prune` removes share one remedy line; a record it keeps has its own. pub(crate) fn notice_lines(stale: &[StalePatch], common: &GlobalArgs) -> Vec { if stale.is_empty() { return Vec::new(); @@ -133,14 +194,72 @@ pub(crate) fn notice_lines(stale: &[StalePatch], common: &GlobalArgs) -> Vec 0 { + lines.push(format!( + "Run `{}` to remove {} from the manifest.", + prune_command(common), + match (prunable == stale.len(), prunable) { + (true, 1) => "it", + (true, _) => "them", + (false, _) => "the rest", + } + )); + } lines } +/// Mark the `stale` patches whose record `scan --prune` keeps: a Cargo or +/// PyPI record with a copy of its version that is still patched (or cannot +/// be read to tell) where the project crawl no longer looks, by the very +/// rule the prune keeps it by, and which `rollback` reaches that copy. +/// Reads those copies, and only when a Cargo or PyPI record is stale. +pub(crate) async fn mark_still_patched( + common: &GlobalArgs, + manifest: &PatchManifest, + socket_dir: &std::path::Path, + stale: &mut [StalePatch], +) { + use crate::ecosystem_dispatch::{cargo_copies_still_patched, pypi_copies_still_patched_within}; + let purls: Vec = stale.iter().map(|patch| patch.purl.clone()).collect(); + let options = common.crawler_options(); + let blobs = socket_dir.join("blobs"); + // The copies a plain `rollback ` restores, then every copy the + // prune keeps a record for. + let mut reach = [Vec::new(), Vec::new()]; + for (kept, global) in reach.iter_mut().zip([false, true]) { + *kept = cargo_copies_still_patched(manifest, purls.iter(), &options, &blobs, global).await; + kept.extend( + pypi_copies_still_patched_within(manifest, purls.iter(), &options, &blobs, global) + .await, + ); + } + let [in_scope, anywhere] = reach; + for patch in stale.iter_mut() { + patch.still_patched = if in_scope.contains(&patch.purl) { + Some(PatchedCopy::InScope) + } else if anywhere.contains(&patch.purl) { + Some(PatchedCopy::Global) + } else { + None + }; + } +} + /// Split `candidates` (manifest keys with no installed copy) by what /// `known` (the purls of a lock inventory or of a crawl) says of them: /// the stale ones, sorted, and the ones `known` says nothing about. A @@ -183,6 +302,7 @@ pub(crate) fn classify( version: version.to_string(), others: others.into_iter().map(str::to_string).collect(), evidence, + still_patched: None, }); } } @@ -195,8 +315,15 @@ pub(crate) fn classify( /// /// The project's lockfiles are asked first. The installed tree is crawled /// only for the candidates no lockfile names, and only in their -/// ecosystems: a project with no lockfile, a global run. -pub(crate) async fn detect(common: &GlobalArgs, candidates: &[String]) -> Vec { +/// ecosystems: a project with no lockfile, a global run. `manifest` and +/// `socket_dir` tell which of them `scan --prune` keeps +/// ([`mark_still_patched`]). +pub(crate) async fn detect( + common: &GlobalArgs, + manifest: &PatchManifest, + socket_dir: &std::path::Path, + candidates: &[String], +) -> Vec { if candidates.is_empty() { return Vec::new(); } @@ -245,6 +372,7 @@ pub(crate) async fn detect(common: &GlobalArgs, candidates: &[String]) -> Vec( purls: impl IntoIterator, options: &CrawlerOptions, blobs_path: &std::path::Path, +) -> Vec { + pypi_copies_still_patched_within(manifest, purls, options, blobs_path, true).await +} + +/// [`pypi_copies_still_patched`], with `machine: false` leaving out the +/// copies only `rollback --global` restores: what is left is what a plain +/// `rollback ` reaches. +pub async fn pypi_copies_still_patched_within<'a>( + manifest: &socket_patch_core::manifest::schema::PatchManifest, + purls: impl IntoIterator, + options: &CrawlerOptions, + blobs_path: &std::path::Path, + machine: bool, ) -> Vec { let pypi = manifest_purls_of(manifest, purls, Ecosystem::Pypi); if pypi.is_empty() { @@ -86,9 +99,10 @@ pub async fn pypi_copies_still_patched<'a>( } let partitioned = HashMap::from([(Ecosystem::Pypi, pypi)]); let mut found = find_all_packages_for_rollback(&partitioned, options, true).await; - if PythonCrawler::new() - .installs_into_a_shared_interpreter(options) - .await + if machine + && PythonCrawler::new() + .installs_into_a_shared_interpreter(options) + .await { let machine = CrawlerOptions { cwd: options.cwd.clone(), diff --git a/crates/socket-patch-cli/tests/apply/stale_patch_skip.rs b/crates/socket-patch-cli/tests/apply/stale_patch_skip.rs index e5e6d11c00..15b7850353 100644 --- a/crates/socket-patch-cli/tests/apply/stale_patch_skip.rs +++ b/crates/socket-patch-cli/tests/apply/stale_patch_skip.rs @@ -14,10 +14,11 @@ use std::path::Path; use serde_json::json; use super::apply_fixture::{ - index_js_patches, install_npm_pkg, run_apply, stage_blob, write_manifest, MM_AFTER, MM_BEFORE, + index_js_patches, install_npm_pkg, one_file, patch_record, run_apply, stage_blob, + write_manifest, MM_AFTER, MM_BEFORE, }; use crate::common::envelope::{event_for, events}; -use crate::common::{git_sha256, parse_json_envelope}; +use crate::common::{git_sha256, parse_json_envelope, run_with_env}; const STALE: &str = "pkg:npm/widget@1.0.0"; const LIVE: &str = "pkg:npm/gadget@1.0.0"; @@ -309,3 +310,152 @@ fn check_reports_a_stale_patch_and_stays_in_sync() { assert_eq!(code, 0, "{stderr}"); assert!(stdout.trim().is_empty() && stderr.trim().is_empty()); } + +const CRATE_STALE: &str = "pkg:cargo/gadget@1.0.0"; +const CRATE_BEFORE: &[u8] = b"pub fn fmt() {}\n"; +const CRATE_AFTER: &[u8] = b"pub fn fmt() {}\npub fn socket_patched() {}\n"; + +/// A Cargo project that moved `gadget` from 1.0.0 to 1.1.0, with a +/// project-local `CARGO_HOME` under `.cargo`. `old_copy` is what the +/// registry cache still holds of 1.0.0 (`None`: nothing). The manifest +/// still records the 1.0.0 patch. Returns the `CARGO_HOME` path. +fn write_moved_cargo_project(root: &Path, old_copy: Option<&[u8]>) -> String { + std::fs::write( + root.join("Cargo.toml"), + "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[dependencies]\ngadget = \"=1.1.0\"\n", + ) + .unwrap(); + std::fs::write( + root.join("Cargo.lock"), + "version = 3\n\n[[package]]\nname = \"app\"\nversion = \"0.1.0\"\ndependencies = [\n \"gadget\",\n]\n\n[[package]]\nname = \"gadget\"\nversion = \"1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n", + ) + .unwrap(); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap(); + + let cargo_home = root.join(".cargo"); + let registry = cargo_home.join("registry/src/index.crates.io-test"); + let unpack = |version: &str, lib: &[u8]| { + let dir = registry.join(format!("gadget-{version}")); + std::fs::create_dir_all(dir.join("src")).unwrap(); + std::fs::write( + dir.join("Cargo.toml"), + format!("[package]\nname = \"gadget\"\nversion = \"{version}\"\n"), + ) + .unwrap(); + std::fs::write(dir.join("src/lib.rs"), lib).unwrap(); + }; + unpack("1.1.0", CRATE_BEFORE); + if let Some(lib) = old_copy { + unpack("1.0.0", lib); + } + + write_manifest( + root, + json!({ CRATE_STALE: patch_record( + "57a1e001-0000-4000-8000-000000000000", + one_file("src/lib.rs", CRATE_BEFORE, CRATE_AFTER), + ) }), + ); + stage_blob(root, &git_sha256(CRATE_BEFORE), CRATE_BEFORE); + stage_blob(root, &git_sha256(CRATE_AFTER), CRATE_AFTER); + cargo_home.to_string_lossy().into_owned() +} + +/// The registry cache is shared, so `scan --prune` keeps a record whose +/// old-version copy there is still patched. The notice names the command +/// that does clear it, `rollback`, and running it as printed restores the +/// copy and removes the record. +#[test] +fn a_stale_cargo_patch_whose_cache_copy_is_still_patched_names_rollback() { + let tmp = tempfile::tempdir().unwrap(); + let cargo_home = write_moved_cargo_project(tmp.path(), Some(CRATE_AFTER)); + let env = [("CARGO_HOME", cargo_home.as_str())]; + + let (code, _stdout, stderr) = + run_apply(tmp.path(), &["--offline", "--ecosystems", "cargo"], &env); + assert_eq!(code, 0, "{stderr}"); + assert_eq!( + stderr.trim(), + "Warning: 1 manifest patch is stale (the project uses another version of the package; \ + skipped):\n - pkg:cargo/gadget@1.0.0 (the project lockfile resolves 1.1.0)\n\ + A copy of pkg:cargo/gadget@1.0.0 on this machine is still patched: run `socket-patch \ + rollback pkg:cargo/gadget@1.0.0 --ecosystems cargo` to restore it and remove the patch \ + from the manifest.", + "{stderr}" + ); + assert!( + !stderr.contains("scan --prune"), + "prune keeps this record, so it is not the remedy; {stderr}" + ); + + let (code, stdout, stderr) = run_apply( + tmp.path(), + &["--offline", "--ecosystems", "cargo", "--json"], + &env, + ); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 0, "{v}\n{stderr}"); + let ev = event_for(&v, CRATE_STALE); + assert_eq!(ev["errorCode"], "patch_stale", "{ev}"); + let reason = ev["reason"].as_str().unwrap_or_default(); + assert!( + reason.contains("`socket-patch rollback pkg:cargo/gadget@1.0.0 --ecosystems cargo`") + && !reason.contains("scan --prune"), + "{ev}" + ); + + // The remedy as printed. + let (code, stdout, stderr) = run_with_env( + tmp.path(), + &[ + "rollback", + CRATE_STALE, + "--ecosystems", + "cargo", + "--offline", + ], + &env, + ); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!( + std::fs::read( + tmp.path() + .join(".cargo/registry/src/index.crates.io-test/gadget-1.0.0/src/lib.rs") + ) + .unwrap(), + CRATE_BEFORE, + "rollback restores the cache copy" + ); + let manifest: serde_json::Value = + serde_json::from_slice(&std::fs::read(tmp.path().join(".socket/manifest.json")).unwrap()) + .unwrap(); + assert!( + manifest["patches"].get(CRATE_STALE).is_none(), + "rollback removes the record; {manifest}" + ); +} + +/// The old copy in the cache is pristine, or gone: prune removes the +/// record, so prune is the remedy named. +#[test] +fn a_stale_cargo_patch_with_no_patched_copy_names_prune() { + for old_copy in [Some(CRATE_BEFORE), None] { + let tmp = tempfile::tempdir().unwrap(); + let cargo_home = write_moved_cargo_project(tmp.path(), old_copy); + let env = [("CARGO_HOME", cargo_home.as_str())]; + + let (code, _stdout, stderr) = + run_apply(tmp.path(), &["--offline", "--ecosystems", "cargo"], &env); + assert_eq!(code, 0, "{stderr}"); + assert!( + stderr.contains(" - pkg:cargo/gadget@1.0.0 (the project lockfile resolves 1.1.0)") + && stderr.contains( + "Run `socket-patch scan --prune --ecosystems cargo` to remove it from the \ + manifest." + ) + && !stderr.contains("rollback"), + "old copy {old_copy:?}: {stderr}" + ); + } +} diff --git a/crates/socket-patch-cli/tests/e2e_pypi_multi_copy.rs b/crates/socket-patch-cli/tests/e2e_pypi_multi_copy.rs index cfc7f3d23c..4e6b987d71 100644 --- a/crates/socket-patch-cli/tests/e2e_pypi_multi_copy.rs +++ b/crates/socket-patch-cli/tests/e2e_pypi_multi_copy.rs @@ -376,6 +376,95 @@ fn a_skipped_prune_names_a_patch_still_installed_outside_the_projects_interprete ); } +/// A stale patch whose old copy is still patched in a tool's environment: +/// the project moved to `dupkit 2.0.0`, which the interpreter on `PATH` +/// holds, and a pipx environment still holds the patched 1.0.0. `apply` +/// skips the record without failing, and names the one command that +/// clears it: a global `rollback`, since `scan --prune` keeps the record +/// and a plain `rollback` does not reach that copy. Run as printed, it +/// restores the copy and removes the record. +#[cfg(unix)] +#[test] +fn a_stale_patch_still_installed_in_a_tool_environment_names_the_global_rollback() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let home = root.join("home"); + let project = root.join("work"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write(project.join("requirements.txt"), "dupkit==2.0.0\n").unwrap(); + stage_patch(&project); + // The interpreter on PATH holds the version the project uses now. + let system_site = root.join("usr/lib/python3/dist-packages"); + let dist = system_site.join("dupkit-2.0.0.dist-info"); + std::fs::create_dir_all(&dist).unwrap(); + std::fs::write( + dist.join("METADATA"), + "Metadata-Version: 2.1\nName: dupkit\nVersion: 2.0.0\n", + ) + .unwrap(); + std::fs::create_dir_all(system_site.join("dupkit")).unwrap(); + std::fs::write(system_site.join(FILE), ORIGINAL).unwrap(); + let bin = root.join("bin"); + stub_python(&bin, &[&system_site]); + // A pipx app's environment still holds the patched 1.0.0. + let tool_site = home.join(".local/pipx/venvs/sometool/lib/python3.12/site-packages"); + let tool_copy = install_dupkit(&tool_site); + std::fs::write(&tool_copy, PATCHED).unwrap(); + + let path = format!("{}:/usr/bin:/bin", bin.display()); + let env = [("PATH", path.as_str()), ("HOME", home.to_str().unwrap())]; + let remedy = "`socket-patch rollback pkg:pypi/dupkit@1.0.0 -g --ecosystems pypi`"; + + let (code, _stdout, stderr) = run( + &project, + &["apply", "--offline", "--ecosystems", "pypi"], + &env, + ); + assert_eq!(code, 0, "a stale patch must not fail the run:\n{stderr}"); + assert!( + stderr.contains("Warning: 1 manifest patch is stale") + && stderr.contains(&format!( + "A copy of pkg:pypi/dupkit@1.0.0 on this machine is still patched: run {remedy}" + )) + && !stderr.contains("scan --prune"), + "{stderr}" + ); + + let (code, stdout, stderr) = run( + &project, + &["apply", "--offline", "--ecosystems", "pypi", "--json"], + &env, + ); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let json = envelope(&stdout, &stderr); + let events = json["events"].as_array().cloned().unwrap_or_default(); + assert!( + events.iter().any(|e| e["purl"] == PURL + && e["action"] == "skipped" + && e["errorCode"] == "patch_stale" + && e["reason"].as_str().is_some_and(|r| r.contains(remedy))), + "{json:#}" + ); + + // The remedy as printed. + let (code, stdout, stderr) = run( + &project, + &["rollback", PURL, "-g", "--ecosystems", "pypi", "--offline"], + &env, + ); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!(std::fs::read(&tool_copy).unwrap(), ORIGINAL); + let manifest: Value = + serde_json::from_slice(&std::fs::read(project.join(".socket/manifest.json")).unwrap()) + .unwrap(); + assert!(manifest["patches"].get(PURL).is_none(), "{manifest:#}"); + assert_eq!( + std::fs::read(system_site.join(FILE)).unwrap(), + ORIGINAL, + "the version the project uses is never touched" + ); +} + /// When a scan finds nothing because every package in the interpreter on /// `PATH` was left out as not the project's, it says so: "install first" /// alone would send the user to install what is already there. diff --git a/docs/usage.md b/docs/usage.md index f670fd43ab..056e451df4 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -389,6 +389,17 @@ removes the record: socket-patch scan --prune ``` +`scan --prune` keeps a Cargo or PyPI record while a copy of the old version on the +machine is still patched, such as one in Cargo's shared registry cache. For such a +record the warning names the command that restores the copy and removes the record: + +```sh +socket-patch rollback +``` + +The command printed adds `-g` when the copy is outside the project, such as a Python +package in another interpreter or a tool's environment. + `apply --check` and `scan` name stale patches too, and `--silent` hides the warning. A record is stale only when the project's lockfiles or its installed packages hold the same package at another version. A record for a package the project doesn't have at From 96f797c9b5ae347418fff05fe9d7fab41b27ed7b Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 4 Dec 2026 15:11:54 -0500 Subject: [PATCH 4/6] Say a stale patch that get fetched once, and cover get in tests `get` runs apply over the manifest after it saves its patch. A stale record beside the fetched patch is named once (a `patch_stale` warning under `--json`). A patch fetched for a version the project moved off is stale as soon as it is saved: it is its own `skipped` event, so the warning for it is left out of the envelope, and the run exits 0. `run_nested_apply` takes the caller's facts as one `NestedApply` instead of four arguments. Also a test of a stale gem record beside a record for another project's gem: the run no longer fails. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/commands/agent_download.rs | 56 ++++--- crates/socket-patch-cli/src/commands/get.rs | 10 +- .../src/commands/stale_patch.rs | 8 +- .../apply/in_process_gem_fallback_home.rs | 61 ++++++++ .../tests/get/get_stale_patches.rs | 144 ++++++++++++++++++ crates/socket-patch-cli/tests/get/main.rs | 1 + 7 files changed, 255 insertions(+), 27 deletions(-) create mode 100644 crates/socket-patch-cli/tests/get/get_stale_patches.rs diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 9c56d06aae..d125f76dec 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -484,7 +484,7 @@ The route is taken only when **all** of these hold; otherwise the run takes the **Hosted-state visibility (`redirectState`, additive/MINOR).** Every non-hosted-mode, non-vendored-mode `scan --json` SUCCESS envelope (report-only, `--mode agent`/`--sync`, and the zero-discovery envelope) carries an additive top-level `redirectState` object whenever the project's lockfiles pin ≥ 1 hosted patch: `{ mode, records: [{purl, uuid}], wiringLive: [purl] }`. It is a descriptive STATE block, not a warning. `mode` is the constant `"hosted"`. **v5.0 (MAJOR shape change)**: hosted mode keeps no ledger, so `records` lists the hosted pins lockfile discovery finds (one per `(purl, uuid)`, the same discovery `vex` uses: a hosted URL counts only on `https://patch.socket.dev` or the `--patch-server-url` origin), and the v4 `ledger` and `records[].ledgerKey` keys are gone. Each record's `purl` is CANONICALIZED (qualifiers stripped, percent-decoded — e.g. `pkg:npm/@scope/pkg@1.0.0`, `pkg:gem/nokogiri@1.13.3`) to the same spelling `wiringLive` carries, so the join is a plain string compare. `wiringLive` is the subset of those pins among this run's *counted* purls (post-`--ecosystems`-filter) — computed once per run, the same set that feeds `hosted_wiring_retained`. A record missing from `wiringLive` is still wired; it just was not crawled/queried this run (an `--ecosystems` filter, a zero discovery). The key is omitted when no lockfile pins a hosted patch (and under `--global`), and error envelopes (the `--offline` refusal, all-batches-failed) are deliberately minimal and never carry it. A pre-v5 `.socket/vendor/redirect-state.json` is not read. Hosted-mode runs carry their own `redirect` payload and `details.mode: "hosted"` events instead, and vendored-mode runs carry the takeover warnings (their takeovers may restore pins mid-run) — neither duplicates a pre-run snapshot that could go stale. -**Agent-flow run-level warnings (additive).** An agent-mode apply (`--mode agent` / `--sync`, `--json`) may add a top-level `warnings[]` array of `{code, detail}` entries to the scan envelope (absent when none fired; each is also mirrored to stderr unless `--silent`). They surface cross-mode state the apply cannot change — never a status or exit-code change (hosted refusals set the precedent: exit 0 + warning). Codes (stable; new codes are additive/MINOR): `vendored_ownership_retained` — vendor-owned package(s) were skipped before download (each is also a `skipped` / `vendored` event); the detail names the purls and the migration path (`remove `, or `vendor --revert` which unwinds every vendored package, then re-run). `hosted_wiring_retained` — the lockfiles still pin scanned package(s) to a hosted patch (the agent run does not unwind hosted wiring — as of v5.0 that is `socket-patch rollback`'s job, which restores the upstream registry entries, or `remove ` per package); the detail names the purls and the options (stay `--mode hosted`, migrate via `scan --mode vendored`, or `socket-patch rollback`). The warning keys on the hosted pins lockfile discovery finds at scan time, so a flow that restored the upstream entries retires it. The human path prints the same `hosted_wiring_retained` text to stderr after an apply; the vendored counterpart is already covered by its per-package `[skip] … (vendored …)` lines. `ownership_not_restored` (v5.0; `apply` and `rollback` `warnings[]` alike) — a file WAS patched (or restored) but could not be given its original uid/gid (its mode is kept; the group is kept when the caller belongs to it); the detail is `: : patched, but ownership could not be restored to uid N gid M: ` and the human line `Warning: ` (stderr, muted by `--silent`); never a status or exit change. `go_installed_tool_stale` (v5.0; `apply`, dry runs included) — a `--global` Go apply patched a module cache copy that a tool installed with `go install` was built from before the patch; the detail names the binary and the `go install @` remedy (or, when they can't be inspected, what could not be checked); never a status or exit change. `stale_bytecode_not_removed` (`apply` and `rollback` `warnings[]` alike) — a `.py` file WAS patched (or restored) but CPython bytecode compiled from its previous bytes (`__pycache__/.[.opt-N].pyc`) could not be deleted, so Python may keep running the old code until it is removed; the detail is `: could not remove stale Python bytecode (: , …); …` and the human line `Warning: `; never a status or exit change. `patch_files_skipped` (`apply --force`) — a file of the patch is not on disk and was skipped; the detail is `: N patch file(s) not found on disk and skipped (--force): , …` and the human line `Warning: `. The package's event is `applied` with the files that were written, or, when the run wrote none and the files that exist are patched, `skipped` / `already_patched`; never a status or exit change. `cargo_build_cache_stale` (v5.0; `apply` and `rollback` `warnings[]` alike) — a cargo crate's bytes changed but its compiled copy in a project build directory could not be invalidated (a fingerprint directory that could not be removed, or a `build.build-dir` with a `{workspace-path-hash}` template); the detail names the crates to `cargo clean -p` before the next build, which may otherwise link the stale code; never a status or exit change. `nuget_stale_output_copies` (`apply`, `rollback` and `remove` `warnings[]` alike, and those of an agent-mode `scan` / `get`, both from the apply it runs and from the rollback of a recorded patch it replaces) — agent mode patches a NuGet package where NuGet restored it, but an application loads the copy a build put in the project's output (`bin///`, a publish directory), and a project built before the run still holds the previous file there. One warning per package and per kind of stale copy: the detail is `: N copies of under this project's bin and publish directories still hold : . …`, with at most five paths relative to `--cwd` and then `+N more`. `` and `` are `the unpatched file` and `An application run from that output loads the unpatched code.` for a copy that holds a file's original bytes after an apply; `the patched file` and `The package was restored, not what was built from it.` after `rollback` / `remove`; and `the file this run replaced in the package` and `The package's file was replaced, not what was built from it.` for a copy that holds a file the run replaced with another one: the file of a recorded patch that another patch replaces (whether `scan` / `get` rolled the recorded patch back first or the apply wrote over its file), or other content `apply` was told to overwrite. The detail names the remedy (`dotnet build` / `dotnet publish` copy the package's file into the output they write, one configuration per run; rebuild or republish each output listed, or delete it) and says that output written to another directory was not searched. The human line is `Warning: `. A copy is matched by file name (ASCII case ignored), then by content: one holding bytes the package had before the run is stale, one holding the package's current bytes is not, and one with any other bytes (another version, an earlier patch's file, a trimmed or ReadyToRun-compiled output) is counted in the package's first detail as not judged. Searched: every directory named `bin` or `publish` below `--cwd`, eight levels deep, which covers the SDK's `artifacts/bin` and `artifacts/publish` layout; never through a symbolic link, and never under `obj`, `packages`, `node_modules` (names compared without regard to ASCII case), a hidden directory or the package folder itself (however its path and `--cwd` are spelled), inside a `bin` or `publish` directory as outside one. The project tree is walked breadth-first and a directory's own `bin` / `publish` is searched before the walk goes deeper, so output near the root is found first. The search stops after listing 10,000 project directories, listing 10,000 directories inside output trees, or hashing 512 same-named files. A search that stops there with directories left says so: a stale copy's detail ends `The search stopped at its limit, so more copies may exist.`, and when it had found no stale copy the run gets one warning of the same code instead: `NuGet: the search of this project's bin and publish directories for stale copies of stopped at its limit of and found none in the part it searched. Not searched, with what is below them: . Output built before this run may still hold the unpatched file: rebuild or republish it (`dotnet build`, `dotnet publish`).` (`the patched file` after a rollback; the rollback of a replaced patch never prints that line, since the apply that normally follows it searches the same tree and does: a `--save-only` replacement, which runs no apply, prints none). An output path set in a project file (`OutputPath`, `PublishDir`) is not evaluated, and a single-file bundle holds no separate copy to find. A package an earlier run patched is checked on every run, so the warning repeats until each output is rebuilt or deleted (a copy that holds a replaced file is known only to the run that replaced it: later runs count it as not judged); a dry run reports only packages that are already patched, and a `--global` / `--global-prefix` run, which has no project, searches nothing. Nothing is written, and it is never a status or exit change: `apply --check` and `vex` do not read build output. `patch_stale` (`scan` and `get` `warnings[]`) — the manifest holds a stale patch: a record for a version of a package the project no longer uses (see the `patch_stale` skip code). The detail is `: The patch is for , but (stale patch); run `socket-patch scan --prune ` to remove it from the manifest`, one warning per record. It comes from the apply an agent-mode run ends with (which skips the record; the standalone `apply --json` reports it as a `skipped` event instead), or, when the run applied nothing (report-only, `--dry-run`, nothing found or selected), from the scan itself, which compares the manifest with what it found installed or resolved by a lockfile (`the project uses `); never both in one run. A run that prunes (`--prune` / `--sync`, hosted mode aside) removes the record in its GC and reports no warning for it. The human path prints the same `Warning: N manifest patch(es) … stale …:` block as `apply`, once, on stderr (hidden by `--silent`). Never a status or exit change. +**Agent-flow run-level warnings (additive).** An agent-mode apply (`--mode agent` / `--sync`, `--json`) may add a top-level `warnings[]` array of `{code, detail}` entries to the scan envelope (absent when none fired; each is also mirrored to stderr unless `--silent`). They surface cross-mode state the apply cannot change — never a status or exit-code change (hosted refusals set the precedent: exit 0 + warning). Codes (stable; new codes are additive/MINOR): `vendored_ownership_retained` — vendor-owned package(s) were skipped before download (each is also a `skipped` / `vendored` event); the detail names the purls and the migration path (`remove `, or `vendor --revert` which unwinds every vendored package, then re-run). `hosted_wiring_retained` — the lockfiles still pin scanned package(s) to a hosted patch (the agent run does not unwind hosted wiring — as of v5.0 that is `socket-patch rollback`'s job, which restores the upstream registry entries, or `remove ` per package); the detail names the purls and the options (stay `--mode hosted`, migrate via `scan --mode vendored`, or `socket-patch rollback`). The warning keys on the hosted pins lockfile discovery finds at scan time, so a flow that restored the upstream entries retires it. The human path prints the same `hosted_wiring_retained` text to stderr after an apply; the vendored counterpart is already covered by its per-package `[skip] … (vendored …)` lines. `ownership_not_restored` (v5.0; `apply` and `rollback` `warnings[]` alike) — a file WAS patched (or restored) but could not be given its original uid/gid (its mode is kept; the group is kept when the caller belongs to it); the detail is `: : patched, but ownership could not be restored to uid N gid M: ` and the human line `Warning: ` (stderr, muted by `--silent`); never a status or exit change. `go_installed_tool_stale` (v5.0; `apply`, dry runs included) — a `--global` Go apply patched a module cache copy that a tool installed with `go install` was built from before the patch; the detail names the binary and the `go install @` remedy (or, when they can't be inspected, what could not be checked); never a status or exit change. `stale_bytecode_not_removed` (`apply` and `rollback` `warnings[]` alike) — a `.py` file WAS patched (or restored) but CPython bytecode compiled from its previous bytes (`__pycache__/.[.opt-N].pyc`) could not be deleted, so Python may keep running the old code until it is removed; the detail is `: could not remove stale Python bytecode (: , …); …` and the human line `Warning: `; never a status or exit change. `patch_files_skipped` (`apply --force`) — a file of the patch is not on disk and was skipped; the detail is `: N patch file(s) not found on disk and skipped (--force): , …` and the human line `Warning: `. The package's event is `applied` with the files that were written, or, when the run wrote none and the files that exist are patched, `skipped` / `already_patched`; never a status or exit change. `cargo_build_cache_stale` (v5.0; `apply` and `rollback` `warnings[]` alike) — a cargo crate's bytes changed but its compiled copy in a project build directory could not be invalidated (a fingerprint directory that could not be removed, or a `build.build-dir` with a `{workspace-path-hash}` template); the detail names the crates to `cargo clean -p` before the next build, which may otherwise link the stale code; never a status or exit change. `nuget_stale_output_copies` (`apply`, `rollback` and `remove` `warnings[]` alike, and those of an agent-mode `scan` / `get`, both from the apply it runs and from the rollback of a recorded patch it replaces) — agent mode patches a NuGet package where NuGet restored it, but an application loads the copy a build put in the project's output (`bin///`, a publish directory), and a project built before the run still holds the previous file there. One warning per package and per kind of stale copy: the detail is `: N copies of under this project's bin and publish directories still hold : . …`, with at most five paths relative to `--cwd` and then `+N more`. `` and `` are `the unpatched file` and `An application run from that output loads the unpatched code.` for a copy that holds a file's original bytes after an apply; `the patched file` and `The package was restored, not what was built from it.` after `rollback` / `remove`; and `the file this run replaced in the package` and `The package's file was replaced, not what was built from it.` for a copy that holds a file the run replaced with another one: the file of a recorded patch that another patch replaces (whether `scan` / `get` rolled the recorded patch back first or the apply wrote over its file), or other content `apply` was told to overwrite. The detail names the remedy (`dotnet build` / `dotnet publish` copy the package's file into the output they write, one configuration per run; rebuild or republish each output listed, or delete it) and says that output written to another directory was not searched. The human line is `Warning: `. A copy is matched by file name (ASCII case ignored), then by content: one holding bytes the package had before the run is stale, one holding the package's current bytes is not, and one with any other bytes (another version, an earlier patch's file, a trimmed or ReadyToRun-compiled output) is counted in the package's first detail as not judged. Searched: every directory named `bin` or `publish` below `--cwd`, eight levels deep, which covers the SDK's `artifacts/bin` and `artifacts/publish` layout; never through a symbolic link, and never under `obj`, `packages`, `node_modules` (names compared without regard to ASCII case), a hidden directory or the package folder itself (however its path and `--cwd` are spelled), inside a `bin` or `publish` directory as outside one. The project tree is walked breadth-first and a directory's own `bin` / `publish` is searched before the walk goes deeper, so output near the root is found first. The search stops after listing 10,000 project directories, listing 10,000 directories inside output trees, or hashing 512 same-named files. A search that stops there with directories left says so: a stale copy's detail ends `The search stopped at its limit, so more copies may exist.`, and when it had found no stale copy the run gets one warning of the same code instead: `NuGet: the search of this project's bin and publish directories for stale copies of stopped at its limit of and found none in the part it searched. Not searched, with what is below them: . Output built before this run may still hold the unpatched file: rebuild or republish it (`dotnet build`, `dotnet publish`).` (`the patched file` after a rollback; the rollback of a replaced patch never prints that line, since the apply that normally follows it searches the same tree and does: a `--save-only` replacement, which runs no apply, prints none). An output path set in a project file (`OutputPath`, `PublishDir`) is not evaluated, and a single-file bundle holds no separate copy to find. A package an earlier run patched is checked on every run, so the warning repeats until each output is rebuilt or deleted (a copy that holds a replaced file is known only to the run that replaced it: later runs count it as not judged); a dry run reports only packages that are already patched, and a `--global` / `--global-prefix` run, which has no project, searches nothing. Nothing is written, and it is never a status or exit change: `apply --check` and `vex` do not read build output. `patch_stale` (`scan` and `get` `warnings[]`) — the manifest holds a stale patch: a record for a version of a package the project no longer uses (see the `patch_stale` skip code). The detail is `: The patch is for , but (stale patch); run `socket-patch scan --prune ` to remove it from the manifest`, one warning per record (a record `scan --prune` keeps names its `rollback` instead, as in the skip's `reason`). A patch this run selected that is itself stale (`get` of a patch for a version the project moved off) is saved and reported as its `skipped` / `patch_stale` event, not as a warning as well, and the run exits 0 where the apply it ends with used to fail as `package_not_installed`. It comes from the apply an agent-mode run ends with (which skips the record; the standalone `apply --json` reports it as a `skipped` event instead), or, when the run applied nothing (report-only, `--dry-run`, nothing found or selected), from the scan itself, which compares the manifest with what it found installed or resolved by a lockfile (`the project uses `); never both in one run. A run that prunes (`--prune` / `--sync`, hosted mode aside) removes the record in its GC and reports no warning for it. The human path prints the same `Warning: N manifest patch(es) … stale …:` block as `apply`, once, on stderr (hidden by `--silent`). Never a status or exit change. `scan --prune` opts into garbage collection. When set, `scan` removes manifest entries for packages no longer present in the crawl, then deletes orphan blob files, and every obsolete diff and package archive, from `.socket/`. A blob is an orphan when no patch left in the manifest references it: the afterHash and beforeHash blobs of every remaining patch are kept, the same retention policy `repair` uses (the beforeHash blobs are an offline rollback's only restore data, and `repair` downloads afterHash blobs only). Diff and legacy package archives are never kept, even for a remaining patch: nothing reads them any more. Off by default (v3.0) so a temporary uninstall doesn't silently destroy manifest state. Under `--global`/`--global-prefix` the crawl covers only the global installs while the manifest is still `--cwd`'s, so the prune also keeps every entry the `--cwd` project accounts for (its installed packages and its lockfile-listed ones, exactly what the project's own `--prune` keeps): a global prune removes only entries neither scope has. Only entries whose ecosystem this run actually crawled are eligible: a `pkg:/` with no crawler in this build (a newer CLI's ecosystem in the committed manifest) is exempt — the crawl never looked for them, so their absence is not evidence of removal (same fail-safe as the `--ecosystems` filter, which narrows the query but never the prune's installed set). A Cargo entry is also exempt while its agent-mode copy is still patched: the project crawl looks up only the crates `Cargo.lock` resolves, but a crate the lock bumped or dropped keeps its patched copy in the machine-wide `$CARGO_HOME/registry/src` cache (nothing deletes it), and the entry holds the only blobs that can restore that copy. The wet pass keeps it with a `cargo_cache_patch_kept` warning naming the `socket-patch rollback ` that restores the copy and drops the entry; the `--dry-run` preview reports no event (and no warning) for it. A PyPI entry is exempt the same way: a project with no environment of its own is crawled only for the packages it declares, in the one interpreter it installs into, so a package it stopped declaring, or one an earlier release patched in another interpreter or a tool's environment, drops out of the crawl with its copy still patched. The copies `rollback ` restores are looked up by PURL, and for a project that installs into a shared interpreter so are the ones `rollback --global` restores (a project with an environment of its own never patched a copy outside it). The wet pass keeps an entry with a still-patched copy with a `pypi_installed_patch_kept` warning. A prune that an empty crawl skips drops no record, and reports the same warning for each recorded PyPI patch that is still on disk. The pass also reconciles vendored state (runs FIRST, under ONE apply-lock acquisition shared with the manifest prune — lock contention skips the whole pass without failing the scan; `--lock-timeout` is honored and a lock I/O error is reported rather than swallowed; the existence gate — a manifest file OR the vendor ledger's directory `.socket/vendor/`, which holds the artifacts too (a lost ledger leaves them), both cheap stats; one that cannot be stat'd is not absent, and the pass goes on to the read that reports it — runs BEFORE the lock, so a bare project never gets a `.socket/`; in the vendored scan arms the pass runs AFTER the vendor step): (a) ledger entries still tracked by a manifest record (manifest-mode entries written by standalone `vendor`) whose patch is gone from the manifest are reverted — `detached` entries (every `scan`/`get --mode vendored` entry, v5.0) have no manifest record to lose and are exempt from this leg; (b) EVERY ledger entry whose dependency is no longer in the lockfile graph is reverted and any manifest entry it still had dropped (v5.0: the check is about the lockfile, not the manifest, so embedded-record entries are no longer exempt; a missing or undeterminable lockfile keeps the entry, fail-safe); and (c) orphan `.socket/vendor//` dirs with no ledger entry are swept, except one a project file still installs from, which is kept with a `vendor_orphan_still_wired` warning (with no ledger entry at all the pass deletes no vendor dir, and only warns). A vendor ledger that cannot be read stops the vendored half before (a): nothing is reverted or swept, the pass carries a `vendor_state_unreadable` warning, and the manifest half still runs (the scan recovers the vendored purls it exempts from the committed artifacts). The pass also takes out the entries of hosted mode's pnpm registry route that no lockfile uses any more (see "pnpm registry route", *Cleanup*): from pnpm-workspace.yaml and the pnpm locks alone, under the same lock, for a project that holds something of a route (which then passes the existence gate without a manifest or a ledger; the lock's `.socket/` is removed again when it stays empty); never under `--global`. A run whose crawl found nothing still does this half and the vendored one; where the ledger names no entry the lock no longer wires, the vendored half reverts and sweeps nothing and only reports, read-only, what it could not reconcile (`vendor_state_unreadable`, `vendor_orphan_still_wired`; human mode: `Warning:` lines on stderr). The prune never deletes a zero-patch `.socket/manifest.json` (its `{"patches": {}}` + `setup` block stay). Under `--json` (v5.0, MAJOR) the pass is recorded into the scan envelope: each pruned manifest entry is a `removed` event with `details.manifest: true`, each reverted vendored entry a `removed` event (`errorCode: "vendor_reverted"`, `details.mode: "vendored"`), each kept entry a `skipped` / `vendor_revert_kept` event whose reason says why it was kept (a drift, or a project file that still installs from the artifact) and each entry whose revert failed a `skipped` / `vendor_revert_failed` event whose reason carries the revert's own (a GC revert failure never fails the run); a `--dry-run` preview reports the removals as `verified`. The artifact sweep is the envelope's `gc` (`summary.bytesFreed` mirrors it), the orphan vendor dirs swept are the top-level `removedVendorOrphanDirs` count, and each registry entry taken out is a `registry_entry_unused` event counted in `gc.removedRegistryEntries`. The pass's warnings join the top-level `warnings[]`: `vendor_state_unreadable` (the vendor ledger could not be read, so the vendored half did nothing; `status` and the exit code are the scan's own), `vendor_orphan_still_wired` (a vendor dir no ledger entry owns was kept because a project file still installs from it; the detail names the dir and the two ways out, restoring the missing ledger entries from version control, or pointing the lockfile back at the registry release and deleting the dir), `vendor_state_write_failed` (entries were reverted but the ledger rewrite failed), `manifest_write_failed` (the pruned manifest could not be written: no entry was pruned and no blob, diff or package archive was swept, since the manifest on disk still references them), `cleanup_failed` (an orphan sweep failed mid-way, or `.socket/` or one of its `blobs/`, `diffs/`, `packages/` directories is a symlink, which is never swept), `cargo_cache_patch_kept` (see above), `registry_cleanup_skipped` / `registry_cleanup_failed` (the registry-route half could not read or write the pnpm files), the reinstall advisories of the vendored reverts (`vendor_bun_reinstall_required`, `vendor_vlt_reinstall_required`, `vendor_pypi_reinstall_required`), and `vendor_revert_residual_reference` for an entry kept because a project file still installs from its artifact: its detail starts with the entry's purl and names that file (a revert's other warnings, such as `vendor_lock_entry_removed` or a drift keep's, are not repeated). A pass skipped at the lock (`lock_held` | `lock_io`) has no `gc` and no events, only a `gc_skipped` warning whose detail ends with the code. Human mode prints `GC: skipped: .`, one `GC: .` line per warning, and `GC: failed to revert N vendored entries: …` (singular for one), each purl followed by the revert's reason in parentheses. A drift keep is an entry the revert deliberately preserved (`vendor_artifact_kept` — undo the drift and re-run `vendor --revert` to finish). A keep for a project file that still installs from the artifact is not a drift (#1184): the revert restored its recorded wiring, and the way out is to point the file named by `vendor_revert_residual_reference` back at the registry release (or re-export it from the restored lock) and prune again. The preview runs no revert, so it sees neither keep and its `verified` reverts may over-promise what a wet run will actually reclaim. diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 2e554e8cb8..5e341ebb09 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -2040,22 +2040,22 @@ pub(crate) fn telemetry_command(env: &Envelope) -> &'static str { /// apply (a same-process re-acquire would contend), released by apply once /// its last mutation is done. Returns apply's report: its exit code and /// what failed, for the caller's envelope (see [`fold_apply_failures`]). -/// Callers print their own "Applying patches..." line. `json` is the -/// caller's flag: a JSON caller gets no human error lines, from this +/// Callers print their own "Applying patches..." line. `nested` says what +/// the apply knows of its caller; its `caller_json` is the caller's +/// flag: a JSON caller gets no human error lines, from this /// function or from the nested apply (`common` itself is never JSON). The /// read-only `--check` redirect verifier stays off and embedded VEX is /// opt-in on the top-level command only, never on this internal /// invocation. pub(crate) async fn run_nested_apply( - command: &'static str, + nested: super::apply::NestedApply, common: GlobalArgs, - json: bool, - report_user_patch_skips: bool, - prune_follows: bool, recorded: &[(String, String)], client: &ApiClient, lock: LockGuard, ) -> ApplyRunReport { + let json = nested.caller_json; + let report_user_patch_skips = nested.report_user_patch_skips; let quiet = common.silent || json; let manifest_path = common.resolved_manifest_path(); let apply_args = super::apply::ApplyArgs { @@ -2063,12 +2063,7 @@ pub(crate) async fn run_nested_apply( force: false, check: false, vex: Default::default(), - nested: Some(super::apply::NestedApply { - caller_json: json, - report_user_patch_skips, - command, - prune_follows, - }), + nested: Some(nested), }; // The nested apply runs on the host's client: seeded, never rebuilt. let client = crate::args::RunApiClient::new_with(Some(client.clone())); @@ -2129,8 +2124,9 @@ pub(crate) fn apply_key_covers(key: &str, record: &str) -> bool { /// leaves a `failed` event and the envelope's `partialFailure` agrees with /// exit 1. The apply's non-fatal warnings (`content_mismatch_overwritten`, /// #1004) join `env.warnings`: a JSON caller's nested apply is silent, so -/// the envelope is their only channel. `None` (no apply ran) records -/// nothing. +/// the envelope is their only channel, except a `patch_stale` warning for +/// a patch this run selected, which its `skipped` event already says. +/// `None` (no apply ran) records nothing. pub(crate) fn record_apply_outcome( env: &mut Envelope, recorded: &[(String, String)], @@ -2143,10 +2139,26 @@ pub(crate) fn record_apply_outcome( // The caller may already carry the same run-level advisory (scan reports // the gem `.bundle/config` / stale-plugin warnings from its own crawl). let reported = env.warnings.len(); + // A stale patch this run selected is recorded below as its own + // `skipped` event, reason included: the warning would say it twice. + let said_as_event = |warning: &RunWarning| { + warning.code == super::stale_patch::PATCH_STALE + && report.skipped.iter().any(|skip| { + skip.error_code.as_deref() == Some(super::stale_patch::PATCH_STALE) + && skip.purl.as_deref().is_some_and(|key| { + recorded.iter().any(|(purl, _)| apply_key_covers(key, purl)) + && super::stale_patch::warning_detail( + key, + skip.reason.as_deref().unwrap_or_default(), + ) == warning.detail + }) + }) + }; for warning in &report.warnings { - if !env.warnings[..reported] - .iter() - .any(|w| w.code == warning.code && w.detail == warning.detail) + if !said_as_event(warning) + && !env.warnings[..reported] + .iter() + .any(|w| w.code == warning.code && w.detail == warning.detail) { env.warnings.push(warning.clone()); } @@ -2598,11 +2610,13 @@ pub async fn download_and_apply_patches_into( apply_report = Some( crate::ecosystem_dispatch::boxed(|| { run_nested_apply( - command, + super::apply::NestedApply { + caller_json: params.json, + report_user_patch_skips: !params.user_patch_skips_reported, + command, + prune_follows: params.prune_follows, + }, nested_apply_args_from_params(params, run, &manifest_path), - params.json, - !params.user_patch_skips_reported, - params.prune_follows, &recorded, run.api_client, lock, diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index 8b631f9ac7..dd1f938287 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -2487,11 +2487,13 @@ async fn save_and_apply_patch( // result in one line (`Applied 1 patch.`). apply_report = Some( run_nested_apply( - "get", + super::apply::NestedApply { + caller_json: args.common.json, + report_user_patch_skips: true, + command: "get", + prune_follows: false, + }, nested_apply_args(&args.common, &manifest_path, quiet), - args.common.json, - true, - false, &recorded, client, lock, diff --git a/crates/socket-patch-cli/src/commands/stale_patch.rs b/crates/socket-patch-cli/src/commands/stale_patch.rs index 1341af9f50..5a0e7fe852 100644 --- a/crates/socket-patch-cli/src/commands/stale_patch.rs +++ b/crates/socket-patch-cli/src/commands/stale_patch.rs @@ -126,11 +126,17 @@ impl StalePatch { pub(crate) fn warning(&self, common: &GlobalArgs) -> RunWarning { RunWarning::new( PATCH_STALE, - format!("{}: {}", normalize_purl(&self.purl), self.detail(common)), + warning_detail(&self.purl, &self.detail(common)), ) } } +/// The detail of the run warning for the stale patch `purl` whose event +/// reason is `reason`. +pub(crate) fn warning_detail(purl: &str, reason: &str) -> String { + format!("{}: {reason}", normalize_purl(purl)) +} + /// The command that removes stale records, scoped to the tree `common` /// names so it can be pasted as printed. /// diff --git a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs index bf5739974a..f2effe00ac 100644 --- a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs +++ b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs @@ -390,6 +390,67 @@ fn explicit_path_with_only_another_projects_copy_is_a_calm_skip() { assert_eq!(format!("{stdout}{stderr}"), ""); } +/// A stale patch beside a record for another project's gem: no record +/// matched a copy the project loads, one is another project's (a skip of +/// its own), and the one left over is for a version of a gem the lock +/// resolves at another version. A run in which nothing matched used to +/// fail on that record: a stale patch does not fail it. +#[test] +fn a_stale_patch_beside_another_projects_copy_does_not_fail_the_run() { + const STALE: &str = "pkg:gem/colorize@1.0.0"; + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + // The lock resolves colorize 1.1.0. + write_lock_without_the_gem(&fx); + let manifest_path = fx.project.path().join(".socket").join("manifest.json"); + let mut manifest: serde_json::Value = + serde_json::from_slice(&std::fs::read(&manifest_path).unwrap()).unwrap(); + manifest["patches"][STALE] = patch_record( + "66616c6c-6261-4b63-8368-6f6d65000001", + one_file("lib/colorize.rb", ORIGINAL, &patched_bytes()), + ); + std::fs::write( + &manifest_path, + serde_json::to_vec_pretty(&manifest).unwrap(), + ) + .unwrap(); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + assert!( + find_other_project_skip(&env).is_some(), + "the copy that was found is still its own skip.\nenvelope: {env}" + ); + let stale = find_event(&env, "skipped", "patch_stale") + .unwrap_or_else(|| panic!("the record must be a patch_stale skip.\nenvelope: {env}")); + assert_eq!(stale["purl"], STALE, "envelope: {env}"); + assert!( + stale["reason"] + .as_str() + .is_some_and(|r| r.contains("the project lockfile resolves 1.1.0")), + "envelope: {env}" + ); + assert!( + find_event(&env, "skipped", NOT_INSTALLED).is_none(), + "envelope: {env}" + ); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!(!stderr.contains("Error:"), "stderr={stderr}"); + assert!( + stderr.contains("Warning: 1 manifest patch is stale") + && stderr.contains(" - pkg:gem/colorize@1.0.0 (the project lockfile resolves 1.1.0)"), + "stderr={stderr}" + ); +} + /// A project with no `Gemfile.lock` (a gem library that commits none): /// nothing was read that could say the project does not use the gem, so /// the copy in the `gem env` home is not called another project's and no diff --git a/crates/socket-patch-cli/tests/get/get_stale_patches.rs b/crates/socket-patch-cli/tests/get/get_stale_patches.rs new file mode 100644 index 0000000000..e275f608e3 --- /dev/null +++ b/crates/socket-patch-cli/tests/get/get_stale_patches.rs @@ -0,0 +1,144 @@ +//! `get` over a project whose manifest holds a stale patch: a record for +//! a version of a package the project no longer uses. +//! +//! `get` runs `apply` over the whole manifest after it saves its patch. +//! A stale record beside the patch it fetched is named once, with the +//! command that removes it, and never fails the run. A patch fetched for +//! a version the project has moved off is stale as soon as it is saved: +//! `get` saves it, says so, and exits 0, where it used to fail the apply. + +use wiremock::MockServer; + +use crate::common::parse_json_envelope; +use crate::get_fixture::{ + install_npm_fixture, manifest_json, mount_real_view, run_get_bin, write_project, AFTER_BYTES, + NAME, PURL, UUID, +}; + +const STALE: &str = "pkg:npm/widget@1.0.0"; +const STALE_UUID: &str = "57a1e000-0000-4000-8000-000000000002"; + +/// Add a `widget@1.0.0` record to the manifest of a project that has +/// `widget@2.0.0` installed. +fn add_stale_record(root: &std::path::Path) { + install_npm_fixture(root, "widget", "2.0.0"); + crate::get_fixture::seed_manifest_with(root, STALE, STALE_UUID); +} + +fn stale_warnings(v: &serde_json::Value) -> Vec { + v["warnings"] + .as_array() + .into_iter() + .flatten() + .filter(|w| w["code"] == "patch_stale") + .filter_map(|w| w["detail"].as_str().map(str::to_string)) + .collect() +} + +const NOTICE: &str = + "Warning: 1 manifest patch is stale (the project uses another version of the package; \ + skipped):"; +const REMEDY: &str = "Run `socket-patch scan --prune` to remove it from the manifest."; + +/// A stale record beside the patch `get` fetched: the fetched patch is +/// applied, the stale one is named once with the remedy, and the run +/// succeeds. `--json` carries it as one `patch_stale` warning. +#[tokio::test] +async fn a_stale_record_beside_the_fetched_patch_is_named_once() { + let server = MockServer::start().await; + mount_real_view(&server, UUID, PURL).await; + + let tmp = tempfile::tempdir().unwrap(); + write_project(tmp.path()); + add_stale_record(tmp.path()); + let (code, stdout, stderr) = run_get_bin(tmp.path(), &server.uri(), &[UUID]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(stderr.matches(NOTICE).count(), 1, "{stderr}"); + assert!( + stderr.contains(" - pkg:npm/widget@1.0.0 (2.0.0 is installed)") && stderr.contains(REMEDY), + "{stderr}" + ); + assert!( + stdout.contains("Applied 1 of 2 patches: 1 stale."), + "{stdout}" + ); + assert_eq!( + std::fs::read(tmp.path().join("node_modules").join(NAME).join("index.js")).unwrap(), + AFTER_BYTES + ); + assert!(manifest_json(tmp.path())["patches"][STALE].is_object()); + + let tmp = tempfile::tempdir().unwrap(); + write_project(tmp.path()); + add_stale_record(tmp.path()); + let (code, stdout, stderr) = run_get_bin(tmp.path(), &server.uri(), &[UUID, "--json"]); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 0, "{v}\n{stderr}"); + assert_eq!(v["status"], "success", "{v}"); + assert_eq!(v["summary"]["applied"], 1, "{v}"); + assert_eq!( + stale_warnings(&v), + [ + "pkg:npm/widget@1.0.0: The patch is for 1.0.0, but 2.0.0 is installed (stale \ + patch); run `socket-patch scan --prune` to remove it from the manifest" + ], + "{v}" + ); + assert!(!stderr.contains("stale"), "{stderr}"); +} + +/// The patch `get` fetched is for a version the project moved off. It is +/// saved, skipped as stale and named once: one `skipped` event in +/// `--json` and no second mention as a warning. The run exits 0, as +/// `apply` does on the same manifest. +#[tokio::test] +async fn a_fetched_patch_for_a_version_the_project_moved_off_is_a_stale_skip() { + let server = MockServer::start().await; + mount_real_view(&server, UUID, PURL).await; + let moved_project = || { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write( + tmp.path().join("package.json"), + r#"{ "name": "consumer", "version": "0.0.0" }"#, + ) + .unwrap(); + install_npm_fixture(tmp.path(), NAME, "2.0.0"); + tmp + }; + + let tmp = moved_project(); + let (code, stdout, stderr) = run_get_bin(tmp.path(), &server.uri(), &[UUID]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert_eq!(stderr.matches(NOTICE).count(), 1, "{stderr}"); + assert!( + stderr.contains(" - pkg:npm/covgap-pkg@1.0.0 (2.0.0 is installed)") + && stderr.contains(REMEDY), + "{stderr}" + ); + assert!( + stdout.contains("Applied 0 of 1 patch: 1 stale."), + "{stdout}" + ); + + let tmp = moved_project(); + let (code, stdout, stderr) = run_get_bin(tmp.path(), &server.uri(), &[UUID, "--json"]); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 0, "{v}\n{stderr}"); + assert_eq!(v["status"], "success", "{v}"); + let stale: Vec<&serde_json::Value> = v["events"] + .as_array() + .into_iter() + .flatten() + .filter(|e| e["errorCode"] == "patch_stale") + .collect(); + assert_eq!(stale.len(), 1, "{v}"); + assert_eq!(stale[0]["action"], "skipped", "{v}"); + assert_eq!(stale[0]["purl"], PURL, "{v}"); + assert_eq!(stale[0]["uuid"], UUID, "{v}"); + assert_eq!(v["summary"]["applied"], 0, "{v}"); + assert_eq!(v["summary"]["failed"], 0, "{v}"); + assert!( + stale_warnings(&v).is_empty(), + "the event already says it; {v}" + ); +} diff --git a/crates/socket-patch-cli/tests/get/main.rs b/crates/socket-patch-cli/tests/get/main.rs index 10f4b923f2..c514ada208 100644 --- a/crates/socket-patch-cli/tests/get/main.rs +++ b/crates/socket-patch-cli/tests/get/main.rs @@ -32,5 +32,6 @@ mod get_modes_e2e; mod get_nested_apply_api_flags_e2e; mod get_render; mod get_single_json_document; +mod get_stale_patches; mod get_update_summary_e2e; mod global_packages_e2e; From 08297523d6077ada32388aae5f41fe5a774adab7 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 4 Dec 2026 15:42:41 -0500 Subject: [PATCH 5/6] Take stale evidence only from the project's own tree or its lockfiles Review fixes. A version found in a store every project on the machine shares (a gem home, the Cargo registry, the Go module cache, a Maven or Gradle repository, the NuGet packages folder) may be another project's, so it no longer makes a record stale: there, only a lockfile does. Installed evidence is kept for npm, PyPI and Composer, whose packages are in a tree of the project's own. A global run has no project to ask and reports no stale patch; its unmatched records stay not installed. `scan` follows the same two rules. `scan --json` adds its stale warnings per record instead of all or none, and a scan that vendors or redirects something now names the stale records too. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../socket-patch-cli/src/commands/scan/gc.rs | 24 ++- .../socket-patch-cli/src/commands/scan/mod.rs | 35 ++-- .../src/commands/stale_patch.rs | 155 +++++++++++++----- .../tests/apply/stale_patch_skip.rs | 25 +++ docs/usage.md | 4 +- 6 files changed, 187 insertions(+), 58 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index d125f76dec..3ffc7b27fa 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2790,7 +2790,7 @@ command's integration tests check its output. | `not_in_platform_build` | `skipped` | apply (gem): the installed copy is the JRuby (`java`) build of the gem and no file of the patch is part of that build (a patch to the C extension or a library it packs). Nothing was written and nothing is left to do: the code the patch changes is not in that build, `apply --check` is in sync and `vex` attests the package (`vulnerable_code_not_present`), and a nested `scan --mode agent` counts the patch among those in place, as it counts `already_patched`. `reason` says so in plain words. rollback (gem): the same copy; nothing of the patch was applied to it, so nothing was restored. See "The JRuby build of a gem". | | `gem_fallback_home_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: a best-effort copy in a `gem env` home (the system gems, `~/.gem`, an rbenv or asdf home) was left unpatched, because it matched no variant or could not be written, while a bundle-path copy of the gem applied. The patch IS in effect on the copy bundler loads. Keyed by the base purl; the detail names the copy's path and the reason. Never flips status or exit. See "Copy classes". | | `gem_other_project_copy_skipped` | `skipped` | apply (gem), and the apply that `get` / `scan --mode agent` run: the record is for another project's gem. Its every copy sits in a `gem env` home Bundler does not load the project's gems from, and the project's Bundler lock, which was read, does not list it. Nothing was applied. Keyed by the manifest key; the detail names the copy and gives `socket-patch rollback `, which drops the record and restores the copy if an earlier release patched it. Never flips status or exit; the human summary counts the patch as `not applicable`. With no lock read the gem is `package_not_installed` instead. See "Copy classes". | -| `patch_stale` | `skipped` | apply, `apply --check`, and the apply that `get` / `scan --mode agent` run: a stale patch. The manifest entry has no installed copy, no lockfile resolves its version, and the project's lockfiles or its installed tree hold the same package at another version (compared as canonical purls, so a name's spelling, a qualifier or an equal PEP 440 spelling is not another version): the project moved off the version the record patches, and nothing pruned the record. The lockfiles are asked first; the installed tree is crawled only for the entries no lockfile names (a project with no lockfile, a global run). The `reason` names the record's version, the version in use and where it was found (`the project lockfile resolves 2.0.0` / `2.0.0 is installed`), and the remedy ``socket-patch scan --prune ``, where `` repeats the run's `--cwd`, `--manifest-path`, `-g` / `--global-prefix` and `--ecosystems`. A Cargo or PyPI record whose copy of the old version is still patched on this machine (the shared registry cache, an environment that still holds the old release) is one `scan --prune` keeps, so its `reason` and its line in the warning name ``socket-patch rollback `` instead, which restores that copy and removes the record; `` gains `-g` when the copy is one only a global rollback reaches (a Python package in another interpreter or a tool's environment, a crate in the registry cache that a `cargo vendor` directory hides). In the warning those lines come first, and the `scan --prune` line then covers the rest. **Never a failure**: the status stays `success` and the exit 0, even when it is the only manifest entry or no other entry matched (such a run exited 1 as `package_not_installed` before); a `package_not_installed` entry with no such evidence beside it still fails an all-miss run. Human path: one `Warning: N manifest patch(es) … stale (the project uses another version of the package; skipped):` block on stderr that lists each purl with the version in use and ends with the remedy (hidden by `--silent`; under `--json` the events are the channel), and an `S stale` bucket in the summary line, shown only when non-zero, in place of counting the entry as `not found on disk`. `scan` names the same entries when it does not prune (see the `patch_stale` warning). Telemetry reports the patch with the outcome `stale`, not `skipped` or `failed`. | +| `patch_stale` | `skipped` | apply, `apply --check`, and the apply that `get` / `scan --mode agent` run: a stale patch. The manifest entry has no installed copy, no lockfile resolves its version, and the project's lockfiles or its installed tree hold the same package at another version (compared as canonical purls, so a name's spelling, a qualifier or an equal PEP 440 spelling is not another version): the project moved off the version the record patches, and nothing pruned the record. The lockfiles are asked first; the installed tree is crawled only for the entries no lockfile names, and only for npm, PyPI and Composer, whose packages are installed in a tree of the project's own. A gem home, the Cargo registry, the Go module cache, a Maven or Gradle repository and the NuGet packages folder are shared by every project on the machine, so another version found there is no evidence: such a record is stale only when a lockfile says so (Maven and NuGet have no lockfile view, so their records are never stale). A `-g` / `--global-prefix` run has no project to ask and reports no stale patch: its unmatched entries stay `package_not_installed`. The `reason` names the record's version, the version in use and where it was found (`the project lockfile resolves 2.0.0` / `2.0.0 is installed`), and the remedy ``socket-patch scan --prune ``, where `` repeats the run's `--cwd`, `--manifest-path`, `-g` / `--global-prefix` and `--ecosystems`. A Cargo or PyPI record whose copy of the old version is still patched on this machine (the shared registry cache, an environment that still holds the old release) is one `scan --prune` keeps, so its `reason` and its line in the warning name ``socket-patch rollback `` instead, which restores that copy and removes the record; `` gains `-g` when the copy is one only a global rollback reaches (a Python package in another interpreter or a tool's environment, a crate in the registry cache that a `cargo vendor` directory hides). In the warning those lines come first, and the `scan --prune` line then covers the rest. **Never a failure**: the status stays `success` and the exit 0 (one exception, as for any run that applied nothing: `apply --vex ` still fails as `no_applicable_patches` when no patch was applied), even when it is the only manifest entry or no other entry matched (such a run exited 1 as `package_not_installed` before); a `package_not_installed` entry with no such evidence beside it still fails an all-miss run. Human path: one `Warning: N manifest patch(es) … stale (the project uses another version of the package; skipped):` block on stderr that lists each purl with the version in use and ends with the remedy (hidden by `--silent`; under `--json` the events are the channel), and an `S stale` bucket in the summary line, shown only when non-zero, in place of counting the entry as `not found on disk`. `scan` names the same entries when it does not prune (see the `patch_stale` warning). Telemetry reports the patch with the outcome `stale`, not `skipped` or `failed`. | | `package_not_installed` | `skipped` | apply: manifest entry has no matching installed package (a record whose package the project uses at another version is `patch_stale` instead; an installed gem or PyPI copy that holds a patched file with content no record of its release was made for is `no_matching_variant` instead). When the project's lockfiles resolve the purl (a platform-gated optional dependency, a devDependency under `--omit=dev`), the detail says it is lockfile-only and the entry never fails the run, even when no other patch matched; only an all-miss run with an unmatched purl that no lock resolves exits 1 (`partialFailure`). **Cargo is never lockfile-only (v5.0, #616)**: `cargo fetch` unpacks every `Cargo.lock` entry (target-gated ones included), so a locked crate missing from `$CARGO_HOME/registry/src` was simply not fetched yet (a cold CI cache, a pruned `registry/src`) and the next `cargo build` would compile it unpatched; it counts as an unresolved purl (an all-miss run exits 1, as in 4.x) and its detail, the human error and the human warning say to run `cargo fetch` first. A crate `Cargo.lock` takes from a path, git, `[patch]` or `[replace]` source is never looked up in the registry cache (#506): cargo does not build that copy, so the same detail also names that case. | | `apply_failed` | `failed` | apply: hash mismatch, write error, archive read error. Also a manifest key that is not a purl (see `invalid_purl`). The copy is left as it was: every file is staged (its blob read and hash-checked, with the file's final mode and owner) before the first is renamed into place, and a rename that fails puts the files already replaced back. The `error` names the file (`Cannot apply patch: - `); a blob that does not hold its hash's bytes is named with the remedy (`blob is corrupt … Run \`socket-patch repair\``). Only when putting a file back fails too does the `error` end with the files left changed; the original of such a file is kept beside it as `.socket-kept--`, a name no later run removes. A run killed between two renames can still leave some files patched; the next `apply` finishes it. A killed run also leaves `.socket-stage--` / `.socket-orig--` files beside the patch's files (staged content and the second names of the files being replaced, never the package's own content); an `apply` or `rollback` of that package removes them once they are ten minutes old. For a PyPI distribution it may also leave `.socket-optional-stage-RECORD-` / `.socket-optional-orig-RECORD-` in the `.dist-info`, from the rewrite of its `RECORD` rows; the next `apply`, `rollback` or `remove` of the package removes those at once (see "PyPI `.dist-info/RECORD` in agent mode"). | | `native_extension_not_rebuilt` | `failed` | apply (gem), and the apply that `get` / `scan --mode agent` run: the patch is incomplete. Its files were written into the installed copy and are left there (unlike `apply_failed`, where the copy is as it was), and the compiled code the copy runs is not the patch's: the build compiled nothing of it, or, on the JRuby build of a gem, the patch changes sources of the gem's jars and does not bring the jars. `error` says what was written and what is not in effect; `files` lists what this run wrote. The run exits 1 (`partialFailure`), the patch stays recorded, `apply --check` is out of sync and `vex` does not attest it; `rollback` restores the files. The same code is a `warnings[]` entry of the run, and the `apply --check` / `vex` tag of such a copy. See "A build that builds nothing of the patch". | diff --git a/crates/socket-patch-cli/src/commands/scan/gc.rs b/crates/socket-patch-cli/src/commands/scan/gc.rs index 2f8d66e519..1b7a8eaedf 100644 --- a/crates/socket-patch-cli/src/commands/scan/gc.rs +++ b/crates/socket-patch-cli/src/commands/scan/gc.rs @@ -919,7 +919,10 @@ fn detect_prunable( /// ([`detect_prunable`]) whose package the scan found at another version /// (`scanned_purls`: installed, or resolved by a lockfile). Sorted. The /// ones the prune keeps for a copy that is still patched are marked, and -/// name `rollback` (see [`keep_patched_cargo_copies`]). +/// name `rollback` (see [`keep_patched_cargo_copies`]). A version the scan +/// found in a store other projects share (a gem home, a registry or +/// module cache) counts only when a lockfile of the project resolves it, +/// and a global scan, which has no project, names none. /// /// A scan that does not prune names them with the remedy, as `apply` does /// for the ones it skips (see [`crate::commands::stale_patch`]); an entry @@ -931,11 +934,26 @@ pub(super) async fn stale_records( scanned_purls: &HashSet, vendored: &HashSet, ) -> Vec { - use crate::commands::stale_patch::{classify, mark_still_patched, Evidence}; + use crate::commands::stale_patch::{ + classify, installed_tree_is_the_projects, mark_still_patched, stale_by_lock, Evidence, + }; + if common.is_global() { + return Vec::new(); + } let mut prunable = detect_prunable(manifest, scanned_purls, vendored); prunable.sort(); let scanned: Vec = scanned_purls.iter().map(|p| PurlKey::new(p)).collect(); - let mut stale = classify(&prunable, &scanned, Evidence::Project).0; + // What the scan found in a store other projects share may be another + // project's version: there, only a lockfile says what this one uses. + let (mut stale, shared): (Vec<_>, Vec<_>) = classify(&prunable, &scanned, Evidence::Project) + .0 + .into_iter() + .partition(|patch| installed_tree_is_the_projects(&patch.purl)); + if !shared.is_empty() { + let shared: Vec = shared.into_iter().map(|patch| patch.purl).collect(); + stale.extend(stale_by_lock(common, &shared).await.0); + stale.sort_by(|a, b| a.purl.cmp(&b.purl)); + } if !stale.is_empty() { mark_still_patched(common, manifest, socket_dir, &mut stale).await; } diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index db6f9365e2..222cd868cf 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -3806,6 +3806,7 @@ async fn scan_project( // Hosted mode: the redirect engine records its events into this // envelope and prints it. if hosted { + crate::commands::stale_patch::warn_once(&mut env, &stale_records, &args.common); if let Some(sweep) = withdrawn_sweep { sweep.record_into(&mut env); } @@ -3995,6 +3996,9 @@ async fn scan_project( } // --- Vendor path (if requested; --sync selects agent instead) --- } else if vendor { + // The vendor step prints the envelope: it runs no apply, so + // nothing else names the stale records. + crate::commands::stale_patch::warn_once(&mut env, &stale_records, &args.common); // Must STAY a boxed fn: this branch's temporaries would otherwise // live in the enclosing poll frame in debug builds, which has to // fit Windows' 1 MiB main-thread stack. @@ -4034,19 +4038,10 @@ async fn scan_project( .await; } - // A nested apply names the stale records it skipped; a run that - // applied nothing names them here. - if !env - .warnings - .iter() - .any(|w| w.code == crate::commands::stale_patch::PATCH_STALE) - { - env.warnings.extend( - stale_records - .iter() - .map(|patch| patch.warning(&args.common)), - ); - } + // A nested apply names the stale records it skipped; the ones it + // did not (a run that applied nothing, a record out of the + // apply's reach) are named here. + crate::commands::stale_patch::warn_once(&mut env, &stale_records, &args.common); finish_rollout_json(&stage, &mut env); let final_code = embed_vex_into_json( &args.common, @@ -4270,6 +4265,13 @@ async fn scan_project( // engine (the same entry as `get --mode hosted`) — it must NOT fall // through to the apply/vendor branches. if hosted { + // No apply runs on this path, so nothing else names the stale + // records. + if !silent { + for line in crate::commands::stale_patch::notice_lines(&stale_records, &args.common) { + eprintln!("{line}"); + } + } let pairs: Vec<(String, String)> = rows .iter() .map(|r| (r.writer.purl.clone(), r.writer.uuid.clone())) @@ -4617,6 +4619,13 @@ async fn scan_project( let mut agent_steps: Vec = Vec::new(); let code = if vendor { + // No apply runs on this path, so nothing else names the stale + // records. + if !silent { + for line in crate::commands::stale_patch::notice_lines(&stale_records, &args.common) { + eprintln!("{line}"); + } + } // Boxed for the same Windows 1 MiB frame reason as the JSON path. boxed_vendor_interactive_path( &args, diff --git a/crates/socket-patch-cli/src/commands/stale_patch.rs b/crates/socket-patch-cli/src/commands/stale_patch.rs index 5a0e7fe852..643820b862 100644 --- a/crates/socket-patch-cli/src/commands/stale_patch.rs +++ b/crates/socket-patch-cli/src/commands/stale_patch.rs @@ -18,7 +18,10 @@ //! A record is stale only on evidence: the project's lockfiles or its //! installed tree hold the same package at another version, and neither //! holds the record's own. A record for a package the project shows no -//! sign of is not stale; it stays `package_not_installed`. +//! sign of is not stale; it stays `package_not_installed`. A version found +//! in a store every project on the machine shares is no such sign +//! ([`installed_tree_is_the_projects`]), and a global run has no project +//! to ask. use std::collections::{BTreeSet, HashMap}; @@ -131,6 +134,25 @@ impl StalePatch { } } +/// Add the `patch_stale` warning of each of `stale` that `env` does not +/// name yet: a nested apply names the ones it skipped, in its own words. +pub(crate) fn warn_once( + env: &mut crate::json_envelope::Envelope, + stale: &[StalePatch], + common: &GlobalArgs, +) { + for patch in stale { + let named = warning_detail(&patch.purl, ""); + if !env + .warnings + .iter() + .any(|w| w.code == PATCH_STALE && w.detail.starts_with(&named)) + { + env.warnings.push(patch.warning(common)); + } + } +} + /// The detail of the run warning for the stale patch `purl` whose event /// reason is `reason`. pub(crate) fn warning_detail(purl: &str, reason: &str) -> String { @@ -316,13 +338,56 @@ pub(crate) fn classify( (stale, undecided) } +/// Whether an installed copy of another version of `purl`'s package says +/// the project moved to it: only where a project's packages are installed +/// in a tree of its own (`node_modules`, a Python environment or the +/// packages the project declares in a shared interpreter, Composer's +/// `vendor/`). A gem home, the Cargo registry, the Go module cache, a +/// Maven or Gradle repository and the NuGet packages folder hold what +/// every project on the machine installed, so a version found there may +/// be another project's, and only a lockfile says what this one uses. +pub(crate) fn installed_tree_is_the_projects(purl: &str) -> bool { + matches!( + Ecosystem::from_purl(purl), + Some(Ecosystem::Npm | Ecosystem::Pypi | Ecosystem::Composer) + ) +} + +/// The `candidates` the project's lockfiles resolve at another version +/// only, and the ones no lockfile names. +pub(crate) async fn stale_by_lock( + common: &GlobalArgs, + candidates: &[String], +) -> (Vec, Vec) { + let ctx = crate::commands::context::ProjectContext::new(common); + let mut locked: Vec = ctx + .locks() + .await + .entries + .iter() + .map(|entry| PurlKey::new(&entry.purl)) + .collect(); + // A gem the lock resolves only as platform builds is left out of + // the inventory, and is resolved all the same. + locked.extend( + ctx.gem_platform_only_purls() + .await + .iter() + .map(|purl| PurlKey::new(purl)), + ); + classify(candidates, &locked, Evidence::Lockfile) +} + /// The stale ones among `candidates`: manifest keys no installed copy /// matched and no lockfile resolves at their own version (sorted). /// /// The project's lockfiles are asked first. The installed tree is crawled -/// only for the candidates no lockfile names, and only in their -/// ecosystems: a project with no lockfile, a global run. `manifest` and -/// `socket_dir` tell which of them `scan --prune` keeps +/// only for the candidates no lockfile names, and only in the ecosystems +/// whose installed tree is the project's own +/// ([`installed_tree_is_the_projects`]). A global run has no project to +/// ask, and what is installed globally says nothing of the records of the +/// project in `--cwd`: nothing is stale there. `manifest` and `socket_dir` +/// tell which of the stale records `scan --prune` keeps /// ([`mark_still_patched`]). pub(crate) async fn detect( common: &GlobalArgs, @@ -330,32 +395,11 @@ pub(crate) async fn detect( socket_dir: &std::path::Path, candidates: &[String], ) -> Vec { - if candidates.is_empty() { + if candidates.is_empty() || common.is_global() { return Vec::new(); } - let mut stale = Vec::new(); - let mut undecided = candidates.to_vec(); - if !common.is_global() { - let ctx = crate::commands::context::ProjectContext::new(common); - let mut locked: Vec = ctx - .locks() - .await - .entries - .iter() - .map(|entry| PurlKey::new(&entry.purl)) - .collect(); - // A gem the lock resolves only as platform builds is left out of - // the inventory, and is resolved all the same. - locked.extend( - ctx.gem_platform_only_purls() - .await - .iter() - .map(|purl| PurlKey::new(purl)), - ); - let (found, rest) = classify(&undecided, &locked, Evidence::Lockfile); - stale.extend(found); - undecided = rest; - } + let (mut stale, mut undecided) = stale_by_lock(common, candidates).await; + undecided.retain(|purl| installed_tree_is_the_projects(purl)); if !undecided.is_empty() { let ecosystems: Vec = undecided .iter() @@ -364,18 +408,16 @@ pub(crate) async fn detect( .collect::>() .into_iter() .collect(); - if !ecosystems.is_empty() { - let (installed, _, _) = crate::ecosystem_dispatch::crawl_ecosystems_for_name( - &common.crawler_options(), - Some(&ecosystems), - ) - .await; - let installed: Vec = installed - .iter() - .map(|package| PurlKey::new(&package.purl)) - .collect(); - stale.extend(classify(&undecided, &installed, Evidence::Installed).0); - } + let (installed, _, _) = crate::ecosystem_dispatch::crawl_ecosystems_for_name( + &common.crawler_options(), + Some(&ecosystems), + ) + .await; + let installed: Vec = installed + .iter() + .map(|package| PurlKey::new(&package.purl)) + .collect(); + stale.extend(classify(&undecided, &installed, Evidence::Installed).0); } stale.sort_by(|a, b| a.purl.cmp(&b.purl)); mark_still_patched(common, manifest, socket_dir, &mut stale).await; @@ -506,6 +548,39 @@ mod tests { /// A record `scan --prune` keeps names the `rollback` that restores /// its still-patched copy, in the reason and on a line of its own. + /// Installed evidence counts only where the tree is the project's + /// own, and a global run has no project: nothing is stale there. + #[tokio::test] + async fn shared_stores_and_global_runs_give_no_installed_evidence() { + for purl in [ + "pkg:npm/a@1.0.0", + "pkg:pypi/a@1.0.0", + "pkg:composer/a/b@1.0.0", + ] { + assert!(installed_tree_is_the_projects(purl), "{purl}"); + } + for purl in [ + "pkg:gem/a@1.0.0", + "pkg:cargo/a@1.0.0", + "pkg:golang/a.example/b@v1.0.0", + "pkg:maven/a/b@1.0.0", + "pkg:nuget/a@1.0.0", + ] { + assert!(!installed_tree_is_the_projects(purl), "{purl}"); + } + let tmp = tempfile::tempdir().unwrap(); + let global = common(&["--global", "--cwd", tmp.path().to_str().unwrap()]); + let manifest = PatchManifest::default(); + let found = detect( + &global, + &manifest, + &tmp.path().join(".socket"), + &["pkg:npm/widget@1.0.0".to_string()], + ) + .await; + assert!(found.is_empty(), "{found:?}"); + } + #[test] fn a_record_whose_copy_is_still_patched_names_rollback() { let default = common(&[]); diff --git a/crates/socket-patch-cli/tests/apply/stale_patch_skip.rs b/crates/socket-patch-cli/tests/apply/stale_patch_skip.rs index 15b7850353..7a42e8b800 100644 --- a/crates/socket-patch-cli/tests/apply/stale_patch_skip.rs +++ b/crates/socket-patch-cli/tests/apply/stale_patch_skip.rs @@ -459,3 +459,28 @@ fn a_stale_cargo_patch_with_no_patched_copy_names_prune() { ); } } + +/// The Cargo registry cache is shared by every project on the machine, +/// so another version of the crate in it is not evidence that this +/// project moved: with no lockfile to say so, the record stays not +/// installed and the all-miss run still fails. +#[test] +fn another_version_in_a_shared_cache_is_not_evidence_without_a_lockfile() { + let tmp = tempfile::tempdir().unwrap(); + let cargo_home = write_moved_cargo_project(tmp.path(), None); + std::fs::remove_file(tmp.path().join("Cargo.lock")).unwrap(); + let env = [("CARGO_HOME", cargo_home.as_str())]; + + let (code, stdout, stderr) = run_apply( + tmp.path(), + &["--offline", "--ecosystems", "cargo", "--json"], + &env, + ); + let v = parse_json_envelope(&stdout); + assert_eq!(code, 1, "{v}\n{stderr}"); + assert_eq!( + event_for(&v, CRATE_STALE)["errorCode"], + "package_not_installed", + "{v}" + ); +} diff --git a/docs/usage.md b/docs/usage.md index 056e451df4..efd011dce4 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -402,7 +402,9 @@ package in another interpreter or a tool's environment. `apply --check` and `scan` name stale patches too, and `--silent` hides the warning. A record is stale only when the project's lockfiles or its installed packages hold the -same package at another version. A record for a package the project doesn't have at +same package at another version. Packages in a store that other projects share (a gem +home, the Cargo, Go, Maven, Gradle or NuGet caches) don't count, only a lockfile does +there, and a `--global` run reports no stale patches. A record for a package the project doesn't have at all still fails a run in which no patch matched, since that usually means the wrong directory. From e2a9faea57d21d498eaee93e9535f19e7cbc7bad Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 4 Dec 2026 15:56:54 -0500 Subject: [PATCH 6/6] Classify the PyPI purl through `Ecosystem::from_purl` The release comparison tested the purl type with an inline prefix check, which the guard test in the core crate rejects. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/utils/purl_key.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/socket-patch-core/src/utils/purl_key.rs b/crates/socket-patch-core/src/utils/purl_key.rs index 2a2f1a3214..60f9ae215d 100644 --- a/crates/socket-patch-core/src/utils/purl_key.rs +++ b/crates/socket-patch-core/src/utils/purl_key.rs @@ -27,6 +27,7 @@ use std::fmt; use crate::crawlers::python_crawler::canonicalize_pypi_name; +use crate::crawlers::Ecosystem; use crate::utils::composer_version::composer_version_key; use crate::utils::purl::{normalize_purl, strip_purl_qualifiers}; use crate::vendor::nuget_feed::normalize_nuget_version; @@ -181,7 +182,7 @@ impl PurlKey { if package != other_package || version == other_version { return None; } - if package.starts_with("pkg:pypi/") + if Ecosystem::from_purl(package) == Some(Ecosystem::Pypi) && crate::utils::pep440::versions_equal(version, other_version) { return None;