From 9160defc3555226e29febb0bbd866cd0728ebdd5 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 10:22:08 -0500 Subject: [PATCH 1/4] Say why an apply failed in its telemetry and --json events A failed in-place apply reported the same `apply_failed` code for every cause, so the patch-lifecycle events could not tell a hash mismatch from a missing blob, a write error or an uninstalled package. - core: `ApplyResult.cause` (`ApplyFailureCause`), set at each failure of the in-place engine: hash_mismatch, file_not_found, unsafe_path, shared_store, conda_build, blob_missing, blob_corrupt, write_failed, sidecar_failed; Maven refusals keep their own codes. A failure that sets none falls back to the file that stopped it, else `unclassified`, so the unexplained share stays measurable. A failed store copy hands its cause to the package. - --json: a failed apply event keeps `errorCode: apply_failed` and adds `cause` (additive; nested get/scan envelopes carry it too). - telemetry: each failed patch's `code` is its cause; failures with no package result (no release variant matched, a Maven base refused as a whole, a manifest patch whose package is not installed) are named too; `failure_codes` counts failed patches per code over the whole run; a run stopped before patching reports `sources_download_failed` / `offline_missing_sources` as its `error_code`. Exit codes and what counts as a failure are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/socket-patch-cli/CLI_CONTRACT.md | 8 + .../src/commands/agent_download.rs | 9 +- crates/socket-patch-cli/src/commands/apply.rs | 200 ++++++++++-- crates/socket-patch-cli/src/commands/get.rs | 1 + crates/socket-patch-cli/src/json_envelope.rs | 13 + .../src/telemetry_outcomes.rs | 11 +- .../tests/cli/telemetry_e2e.rs | 146 +++++++++ crates/socket-patch-core/src/patch/apply.rs | 295 +++++++++++++++--- crates/socket-patch-core/src/patch/gem_ext.rs | 1 + crates/socket-patch-core/src/patch/jvm_jar.rs | 1 + .../socket-patch-core/src/patch/rollback.rs | 2 +- .../src/patch/store_copies.rs | 5 +- crates/socket-patch-core/src/telemetry.rs | 30 ++ crates/socket-patch-core/src/vendor/common.rs | 1 + docs/configuration.md | 7 +- 15 files changed, 652 insertions(+), 78 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index bc390b2e6..3f5959494 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -170,6 +170,14 @@ A missing referenced diff does not remove that protection. so a `postinstall` apply never fails an install over them. The manifest is not changed, and a skipped entry is not reconciled away as dropped. - Skipped events carry a stable `errorCode` and a human-readable `reason`. +- A failed `apply` event (standalone, or the nested apply of agent-mode `get` / + `scan`) keeps `errorCode: apply_failed` and adds `cause`, a stable code for why + the package's patch did not apply: `hash_mismatch` (a file matches neither the + original nor the patched bytes), `file_not_found`, `blob_missing`, + `blob_corrupt`, `write_failed`, `sidecar_failed`, `shared_store`, + `conda_build`, `unsafe_path`, `no_matching_variant`, a Maven refusal's own + code (for example `gradle_copy_unexpected_bytes` or `jvm_agent_service_required`), + or `unclassified` for a failure whose path names none. Route on `errorCode`; `cause` refines it and new values may be added. `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` diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 9a9a0e0b1..16322dd1d 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -2085,11 +2085,7 @@ pub(crate) fn record_apply_outcome( .iter() .find(|f| apply_key_covers(&f.purl, purl)) { - env.record( - PatchEvent::new(EventAction::Failed, purl.as_str()) - .with_uuid(uuid.as_str()) - .with_error(failure.code.as_str(), failure.error.as_str()), - ); + env.record(failure.event(purl.as_str()).with_uuid(uuid.as_str())); failed_any = true; } else if let Some(skip) = report.skipped.iter().find(|skip| { !unsupported_copy(skip) @@ -2188,8 +2184,7 @@ pub(crate) fn record_apply_outcome( continue; } appended.push(&failure.purl); - let mut event = PatchEvent::new(EventAction::Failed, failure.purl.as_str()) - .with_error(failure.code.as_str(), failure.error.as_str()); + let mut event = failure.event(failure.purl.as_str()); if let Some(uuid) = uuid_of(&failure.purl) { event = event.with_uuid(uuid); } diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 7bfeaba0a..f79bf014c 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -8,7 +8,8 @@ use socket_patch_core::crawlers::{ use socket_patch_core::manifest::operations::{manifest_exists, read_manifest}; use socket_patch_core::manifest::schema::{PatchFileInfo, PatchManifest, PatchRecord}; use socket_patch_core::patch::apply::{ - apply_package_patch, verify_file_patch, ApplyResult, MismatchPolicy, PatchSources, VerifyStatus, + apply_package_patch, verify_file_patch, ApplyFailureCause, ApplyResult, MismatchPolicy, + PatchSources, VerifyStatus, }; use socket_patch_core::patch::apply_lock::LockGuard; use socket_patch_core::patch::gem_ext; @@ -322,6 +323,7 @@ async fn reconcile_local_go( applied_via: HashMap::new(), error: Some(error), sidecar: None, + cause: None, } }) .collect() @@ -382,6 +384,7 @@ fn invalid_key_failures(args: &ApplyArgs, manifest_purls: &[String]) -> Vec PatchEvent { let purl = result.package_key.clone(); - if !result.success { - return PatchEvent::new(PatchAction::Failed, purl).with_error( - "apply_failed", - result - .error - .clone() - .unwrap_or_else(|| "unknown error".to_string()), - ); + if let Some(cause) = result.failure_cause() { + return PatchEvent::new(PatchAction::Failed, purl) + .with_error( + "apply_failed", + result + .error + .clone() + .unwrap_or_else(|| "unknown error".to_string()), + ) + .with_cause(cause.as_str()); } // A package managed by `socket-patch vendor` is skipped with its own @@ -1598,12 +1603,26 @@ pub async fn run(args: ApplyArgs) -> i32 { /// One patch the nested apply failed: the manifest purl, a stable code /// (`apply_failed`, `package_not_installed`) and the error text — the same -/// `errorCode` / `error` pair the standalone `apply --json` reports. +/// `errorCode` / `error` pair the standalone `apply --json` reports, and +/// the `cause` of an `apply_failed` one. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct ApplyFailure { pub purl: String, pub code: String, pub error: String, + pub cause: Option<&'static str>, +} + +impl ApplyFailure { + /// The `failed` event the standalone `apply --json` would print. + pub(crate) fn event(&self, purl: &str) -> PatchEvent { + let event = PatchEvent::new(PatchAction::Failed, purl) + .with_error(self.code.as_str(), self.error.as_str()); + match self.cause { + Some(cause) => event.with_cause(cause), + None => event, + } + } } /// What a run of [`run_locked`] reports back. `apply` itself only needs @@ -1662,13 +1681,14 @@ fn collect_apply_failures( ) -> Vec { let mut failures: Vec = Vec::new(); for r in results { - let (code, error) = match caveats.incomplete_of(r) { - Some(copy) => (gem_ext::NOT_REBUILT_REASON, copy.detail.clone()), + let (code, error, cause) = match caveats.incomplete_of(r) { + Some(copy) => (gem_ext::NOT_REBUILT_REASON, copy.detail.clone(), None), None if !r.success => ( "apply_failed", r.error .clone() .unwrap_or_else(|| "unknown error".to_string()), + r.failure_cause().map(ApplyFailureCause::as_str), ), None => continue, }; @@ -1679,6 +1699,7 @@ fn collect_apply_failures( purl: r.package_key.clone(), code: code.to_string(), error, + cause, }); } if !failures.is_empty() { @@ -1689,6 +1710,7 @@ fn collect_apply_failures( code: "package_not_installed".to_string(), error: not_installed_detail(&purl).to_string(), purl, + cause: None, }); } failures @@ -1939,6 +1961,7 @@ pub(crate) async fn run_locked( lockfile_only, run_warnings, fallback_skips, + unreported, caveats, targeted, show_summary, @@ -2367,7 +2390,19 @@ pub(crate) async fn run_locked( } // Track telemetry - let reported = reported_patches(&results, &caveats, args.common.dry_run, &patch_uuids); + let failures = if success { + Vec::new() + } else { + collect_apply_failures(&results, &caveats, &unmatched, &lockfile_only) + }; + let reported = reported_patches( + &results, + &caveats, + &failures, + &unreported, + args.common.dry_run, + &patch_uuids, + ); if success { track_patch_applied( telemetry_command(&args), @@ -2380,7 +2415,7 @@ pub(crate) async fn run_locked( } else { track_patch_apply_failed( telemetry_command(&args), - "apply_failed", + run_failure_code(&run_warnings), "One or more patches failed to apply", args.common.dry_run, &reported, @@ -2417,11 +2452,6 @@ pub(crate) async fn run_locked( ..ApplyRunReport::default() }; } - let failures = if success { - Vec::new() - } else { - collect_apply_failures(&results, &caveats, &unmatched, &lockfile_only) - }; let run_error = if let Some(Err(e)) = &vex_result { Some((e.code.to_string(), e.message.clone())) } else if failures.is_empty() { @@ -2471,18 +2501,31 @@ fn telemetry_command(args: &ApplyArgs) -> &'static str { /// The patches an apply run acted on, as its telemetry names them: the /// run's per-package events ([`GemCaveats::event_of`], what `--json` -/// prints), each under the patch its manifest record names. +/// prints), the patches that failed the run by not being installed +/// (`failures`), and the failures no result describes (`unreported`), +/// each under the patch its manifest record names. /// /// A plain fn, so the events it builds stay off the async frame of `run`. fn reported_patches( results: &[ApplyResult], caveats: &GemCaveats, + failures: &[ApplyFailure], + unreported: &[(String, ApplyFailureCause)], dry_run: bool, patch_uuids: &HashMap, ) -> Vec { let events: Vec = results .iter() .map(|result| caveats.event_of(result, dry_run)) + .chain( + failures + .iter() + .filter(|f| f.code == "package_not_installed") + .map(|f| f.event(&f.purl)), + ) + .chain(unreported.iter().map(|(purl, cause)| { + PatchEvent::new(PatchAction::Failed, purl.as_str()).with_cause(cause.as_str()) + })) .collect(); crate::telemetry_outcomes::patch_outcomes( &events, @@ -2491,6 +2534,17 @@ fn reported_patches( ) } +/// The `error_code` of a failed apply run's telemetry: the stage that +/// kept it from patching anything (`sources_download_failed`, +/// `offline_missing_sources`), else `apply_failed`, with each failed +/// patch's own cause beside it. +fn run_failure_code(run_warnings: &[RunWarning]) -> &str { + run_warnings + .iter() + .find(|w| is_stage_failure_code(&w.code)) + .map_or("apply_failed", |w| w.code.as_str()) +} + /// The one apply-failure exit: `apply_failed` telemetry, then the error /// envelope (`--json`) or an `Error:` line that prints even under /// `--silent` ("errors only", never "nothing" — exit 1 with no message @@ -2564,6 +2618,7 @@ fn synthesize_vendor_owned_results( applied_via: HashMap::new(), error: None, sidecar: None, + cause: None, }); matched.insert(purl); } @@ -2613,6 +2668,10 @@ struct ApplyOutcome { /// (best-effort class): one non-fatal `Skipped` event each in the /// envelope, one gated stderr line each on the human path. fallback_skips: Vec, + /// Failures no result describes (no release variant matched the + /// installed copy, a Maven base refused as a whole), per manifest + /// purl: telemetry names them, as `results` name the rest. + unreported: Vec<(String, ApplyFailureCause)>, /// The gem copies whose apply succeeded with a caveat /// ([`gem_ext::GemCaveat`]): the ones with nothing of the patch in /// their build, and the ones whose patch is incomplete. @@ -3165,6 +3224,7 @@ async fn apply_patches_inner( lockfile_only: HashSet::new(), run_warnings: vec![stage_failure_warning(args.common.offline)], fallback_skips: Vec::new(), + unreported: Vec::new(), caveats: GemCaveats::default(), targeted: target_manifest_purls.len(), show_summary: false, @@ -3207,6 +3267,7 @@ async fn apply_patches_inner( lockfile_only: HashSet::new(), run_warnings: Vec::new(), fallback_skips: Vec::new(), + unreported: Vec::new(), caveats: GemCaveats::default(), targeted: 0, show_summary: false, @@ -3281,6 +3342,7 @@ async fn apply_patches_inner( } } let mut fallback_skips: Vec = Vec::new(); + let mut unreported: Vec<(String, ApplyFailureCause)> = Vec::new(); let mut caveats = GemCaveats::default(); let mut go_pristine_mods: HashMap = HashMap::new(); @@ -3364,6 +3426,7 @@ async fn apply_patches_inner( lockfile_only, run_warnings, fallback_skips, + unreported, caveats: GemCaveats::default(), targeted: target_manifest_purls.len(), show_summary: true, @@ -3477,6 +3540,7 @@ async fn apply_patches_inner( }; let out = Box::pin(apply_maven_base(&maven)).await; has_errors |= out.failed; + unreported.extend(out.unreported); matched_manifest_purls.extend(out.matched); run_warnings.extend(out.warnings); if out.applied { @@ -3895,6 +3959,13 @@ async fn apply_patches_inner( // variant fails loudly instead of silently staying // vulnerable behind a sibling copy's success. has_errors = true; + if !attempted { + unreported.extend( + variants + .iter() + .map(|v| (v.clone(), ApplyFailureCause::NoMatchingVariant)), + ); + } if !attempted && args.prints_errors() { // No variant matched the installed distribution at all — // the package on disk isn't any known release variant. @@ -4055,6 +4126,7 @@ async fn apply_patches_inner( lockfile_only, run_warnings, fallback_skips, + unreported, caveats, targeted: target_manifest_purls.len(), show_summary: true, @@ -4182,12 +4254,14 @@ struct MavenApplied { failed: bool, /// Some copy ended patched. applied: bool, + /// See [`ApplyOutcome::unreported`]. + unreported: Vec<(String, ApplyFailureCause)>, } impl MavenApplied { /// A refusal of `purl` with nothing written: a Failed event carrying /// `code` and a run warning with the same code. - fn refuse(&mut self, purl: &str, path: &Path, code: &str, detail: String) { + fn refuse(&mut self, purl: &str, path: &Path, code: &'static str, detail: String) { self.results.push(ApplyResult { package_key: purl.to_string(), package_path: path.display().to_string(), @@ -4197,6 +4271,7 @@ impl MavenApplied { applied_via: HashMap::new(), error: Some(format!("{code}: {detail}")), sidecar: None, + cause: Some(ApplyFailureCause::Refused(code)), }); self.warn(code, detail); self.failed = true; @@ -4312,6 +4387,12 @@ async fn apply_maven_base(m: &MavenBase<'_>) -> MavenApplied { ), ); out.failed = true; + out.unreported.extend(m.variants.iter().map(|v| { + ( + v.clone(), + ApplyFailureCause::Refused("gradle_ro_cache_shadows"), + ) + })); } if copies.consumed.is_empty() { if copies.read_only.is_empty() { @@ -4570,6 +4651,11 @@ async fn apply_maven_base(m: &MavenBase<'_>) -> MavenApplied { let gradle_only = copies.consumed.iter().all(|c| gradle_cache::expands(c)); if !attempted && !out.failed && !gradle_only { out.failed = true; + out.unreported.extend( + m.variants + .iter() + .map(|v| (v.clone(), ApplyFailureCause::NoMatchingVariant)), + ); if args.prints_errors() { eprintln!( "{}", @@ -5034,6 +5120,7 @@ mod tests { applied_via, error: None, sidecar: None, + cause: None, } } @@ -5086,6 +5173,68 @@ mod tests { assert_eq!(v["action"], "failed"); assert_eq!(v["errorCode"], "apply_failed"); assert_eq!(v["error"], "hash mismatch"); + // No cause was set and the verified file was ready. + assert_eq!(v["cause"], "unclassified"); + } + + /// Telemetry names the failures no package result describes (no + /// release variant matched, a Maven base refused as a whole) and the + /// patches that failed the run by not being installed, each under its + /// record's UUID and code. + #[test] + fn reported_patches_name_the_failures_with_no_result() { + let uuids = HashMap::from([ + ( + "pkg:pypi/w@1.0?artifact_id=a".to_string(), + "u-wheel".to_string(), + ), + ("pkg:maven/g/a@1.0".to_string(), "u-maven".to_string()), + ("pkg:npm/gone@1.0.0".to_string(), "u-gone".to_string()), + ]); + let failures = [ApplyFailure { + purl: "pkg:npm/gone@1.0.0".to_string(), + code: "package_not_installed".to_string(), + error: "No installed package matches this PURL".to_string(), + cause: None, + }]; + let unreported = [ + ( + "pkg:pypi/w@1.0?artifact_id=a".to_string(), + ApplyFailureCause::NoMatchingVariant, + ), + ( + "pkg:maven/g/a@1.0".to_string(), + ApplyFailureCause::Refused("gradle_ro_cache_shadows"), + ), + ]; + let reported = reported_patches( + &[], + &GemCaveats::default(), + &failures, + &unreported, + 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-wheel", "failed", Some("no_matching_variant")), + ("u-maven", "failed", Some("gradle_ro_cache_shadows")), + ] + ); + } + + /// A run stopped before patching anything reports that stage. + #[test] + fn run_failure_code_is_the_stage_that_stopped_the_run() { + assert_eq!(run_failure_code(&[]), "apply_failed"); + let stage = RunWarning::new(SOURCES_DOWNLOAD_FAILED, "x"); + assert_eq!(run_failure_code(&[stage]), SOURCES_DOWNLOAD_FAILED); } #[test] @@ -5150,6 +5299,7 @@ mod tests { applied_via, error: None, sidecar: None, + cause: None, }; let event = result_to_event(&result, false); @@ -5191,6 +5341,7 @@ mod tests { applied_via: HashMap::new(), error: None, sidecar: None, + cause: None, } } @@ -5335,6 +5486,7 @@ mod tests { applied_via, error: None, sidecar: None, + cause: None, }; let event = result_to_event(&result, false); let v: serde_json::Value = @@ -5578,6 +5730,7 @@ mod tests { purl: GEM_PURL.to_string(), code: "native_extension_not_rebuilt".to_string(), error: "the patch's files were written, but not built".to_string(), + cause: None, }] ); let (applied, skipped) = @@ -5805,6 +5958,7 @@ mod tests { applied_via: HashMap::new(), error: None, sidecar: None, + cause: None, }; let t = tally_results(std::slice::from_ref(&applied), &caveats); assert_eq!((t.applied, t.unsupported), (1, 1)); @@ -6176,6 +6330,7 @@ mod tests { applied_via: HashMap::new(), error: error.map(str::to_string), sidecar: None, + cause: None, } } @@ -6196,11 +6351,13 @@ mod tests { purl: "pkg:npm/a@1.0.0".to_string(), code: "apply_failed".to_string(), error: "Permission denied (os error 13)".to_string(), + cause: Some("unclassified"), }, ApplyFailure { purl: "pkg:npm/b@1.0.0".to_string(), code: "apply_failed".to_string(), error: "unknown error".to_string(), + cause: Some("unclassified"), }, ] ); @@ -6221,6 +6378,7 @@ mod tests { purl: "pkg:npm/gone@1.0.0".to_string(), code: "package_not_installed".to_string(), error: "No installed package matches this PURL".to_string(), + cause: None, }], "a lockfile-resolved purl never fails the run (#403)" ); diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index f55def800..c418c32af 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -3502,6 +3502,7 @@ mod tests { purl: purl.to_string(), code: code.to_string(), error: error.to_string(), + cause: None, } } diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index 3ad54dd72..45771c3dd 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -380,6 +380,12 @@ pub struct PatchEvent { /// Underlying error message for `Failed` events. #[serde(skip_serializing_if = "Option::is_none")] pub error: Option, + /// Why a `Failed` apply event's patch did not apply, finer than its + /// `error_code` (which stays `apply_failed`): `hash_mismatch`, + /// `file_not_found`, `blob_missing`, `write_failed`, + /// `no_matching_variant`, … or `unclassified`. Omitted elsewhere. + #[serde(skip_serializing_if = "Option::is_none")] + pub cause: Option, /// Command-specific additional fields. Consumers MUST NOT depend on /// the shape of this object — different subcommands attach different /// keys here, e.g. `list` (vulnerabilities, license, tier, @@ -411,6 +417,7 @@ impl PatchEvent { reason: None, error_code: None, error: None, + cause: None, details: None, } } @@ -450,6 +457,12 @@ impl PatchEvent { self } + /// Attach the cause of a failed apply (see [`PatchEvent::cause`]). + pub fn with_cause(mut self, cause: impl Into) -> Self { + self.cause = Some(cause.into()); + self + } + /// Attach command-specific extra fields. See [`PatchEvent::details`] /// for the contract — consumers should not depend on the shape. pub fn with_details(mut self, details: serde_json::Value) -> Self { diff --git a/crates/socket-patch-cli/src/telemetry_outcomes.rs b/crates/socket-patch-cli/src/telemetry_outcomes.rs index a892e7555..23330627f 100644 --- a/crates/socket-patch-cli/src/telemetry_outcomes.rs +++ b/crates/socket-patch-cli/src/telemetry_outcomes.rs @@ -90,7 +90,8 @@ fn mode_of(event: &PatchEvent, default: &'static str) -> &'static str { /// * Several events for one patch (one per installed copy, or a download /// and then an apply) fold into the one that says most: see /// [`outcome_of`]. The `code` is that event's `errorCode`, and only a -/// failure or a skip has one. +/// failure or a skip has one; a failure with a `cause` (an apply's, +/// under the generic `apply_failed`) reports the cause instead. pub(crate) fn patch_outcomes<'a>( events: impl IntoIterator, default_mode: &'static str, @@ -107,9 +108,11 @@ pub(crate) fn patch_outcomes<'a>( continue; }; let mode = mode_of(event, default_mode); - let code = matches!(event.action, PatchAction::Failed | PatchAction::Skipped) - .then(|| event.error_code.clone()) - .flatten(); + let code = match event.action { + PatchAction::Failed => event.cause.clone().or_else(|| event.error_code.clone()), + PatchAction::Skipped => event.error_code.clone(), + _ => None, + }; let entry = PatchOutcome { uuid: uuid.clone(), ecosystem: purl.map(ecosystem_of).unwrap_or_default(), diff --git a/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs b/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs index c29f60ca9..b490be8d2 100644 --- a/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs +++ b/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs @@ -1610,6 +1610,152 @@ async fn apply_reports_the_patches_it_applied() { assert_eq!(only_patch(again)["code"], "already_patched"); } +/// Run `apply` on a project `prepare` broke, expect it to fail, and return +/// the one `patch_apply_failed` event and the `--json` envelope. +async fn failed_apply( + prepare: impl FnOnce(&Path), + mock: &MockServer, +) -> (serde_json::Value, serde_json::Value) { + let tmp = tempfile::tempdir().expect("tempdir"); + write_agent_project(tmp.path(), ORIGINAL); + prepare(tmp.path()); + + let (code, stdout, stderr) = run_cmd(tmp.path(), &mock.uri(), "apply", &[], &[]); + assert_eq!(code, 1, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let envelope: serde_json::Value = + serde_json::from_str(&stdout).unwrap_or_else(|e| panic!("--json output ({e}):\n{stdout}")); + + let bodies = telemetry_bodies(mock).await; + let failed: Vec<&serde_json::Value> = bodies + .iter() + .filter(|b| b["event_type"] == "patch_apply_failed") + .collect(); + assert_eq!(failed.len(), 1, "{bodies:#?}"); + (failed[0].clone(), envelope) +} + +/// The failed event of a run whose one patch failed with `cause`: the +/// patch is named under that code, the run counts it, and the envelope's +/// failed event carries the same cause beside the generic `apply_failed`. +fn assert_failed_with(event: &serde_json::Value, envelope: &serde_json::Value, cause: &str) { + assert_eq!(event["metadata"]["error_code"], "apply_failed", "{event:#}"); + assert_eq!( + only_patch(event), + &serde_json::json!({ + "uuid": PATCHED_UUID, + "ecosystem": "npm", + "mode": "agent", + "outcome": "failed", + "code": cause, + }) + ); + assert_eq!( + event["metadata"]["failure_codes"], + serde_json::json!({ cause: 1 }), + "{event:#}" + ); + assert!(!event.to_string().contains("tpkg"), "{event:#}"); + + let failed: Vec<&serde_json::Value> = envelope["events"] + .as_array() + .expect("events[]") + .iter() + .filter(|e| e["action"] == "failed") + .collect(); + assert_eq!(failed.len(), 1, "{envelope:#}"); + assert_eq!(failed[0]["errorCode"], "apply_failed", "{envelope:#}"); + assert_eq!(failed[0]["cause"], cause, "{envelope:#}"); +} + +/// A file that matches neither side of the patch fails it as +/// `hash_mismatch`, not the bare `apply_failed`. +#[tokio::test] +async fn a_hash_mismatch_is_reported_as_such() { + let mock = telemetry_only_mock().await; + let (event, envelope) = failed_apply( + |root| std::fs::write(root.join("node_modules/tpkg/index.js"), b"edited\n").unwrap(), + &mock, + ) + .await; + assert_failed_with(&event, &envelope, "hash_mismatch"); +} + +/// A patched file missing from the installed copy: `file_not_found`. +#[tokio::test] +async fn a_missing_file_is_reported_as_such() { + let mock = telemetry_only_mock().await; + let (event, envelope) = failed_apply( + |root| std::fs::remove_file(root.join("node_modules/tpkg/index.js")).unwrap(), + &mock, + ) + .await; + assert_failed_with(&event, &envelope, "file_not_found"); +} + +/// A blob whose bytes do not hash to its name: `blob_corrupt`. +#[tokio::test] +async fn a_corrupt_blob_is_reported_as_such() { + let mock = telemetry_only_mock().await; + let (event, envelope) = failed_apply( + |root| { + let blob = root + .join(".socket/blobs") + .join(crate::common::git_sha256(PATCHED)); + std::fs::write(blob, b"not the patched bytes\n").unwrap(); + }, + &mock, + ) + .await; + assert_failed_with(&event, &envelope, "blob_corrupt"); +} + +/// A manifest patch whose package is not installed (and that no lockfile +/// names) fails the run as `package_not_installed`, though no package +/// result exists for it. +#[tokio::test] +async fn a_patch_whose_package_is_not_installed_is_named() { + let mock = telemetry_only_mock().await; + let (event, _envelope) = failed_apply( + |root| std::fs::remove_dir_all(root.join("node_modules/tpkg")).unwrap(), + &mock, + ) + .await; + assert_eq!(event["metadata"]["error_code"], "apply_failed", "{event:#}"); + assert_eq!(only_patch(&event)["outcome"], "failed", "{event:#}"); + assert_eq!( + only_patch(&event)["code"], + "package_not_installed", + "{event:#}" + ); + assert_eq!( + event["metadata"]["failure_codes"], + serde_json::json!({ "package_not_installed": 1 }), + "{event:#}" + ); +} + +/// 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] +async fn a_failed_download_is_the_runs_error_code() { + let mock = telemetry_only_mock().await; + let (event, _envelope) = failed_apply( + |root| { + std::fs::remove_file( + root.join(".socket/blobs") + .join(crate::common::git_sha256(PATCHED)), + ) + .unwrap() + }, + &mock, + ) + .await; + assert_eq!( + event["metadata"]["error_code"], "sources_download_failed", + "{event:#}" + ); +} + /// A rollback names the patch it rolled back, and says whether the user /// asked for that patch or rolled the whole project back. #[tokio::test] diff --git a/crates/socket-patch-core/src/patch/apply.rs b/crates/socket-patch-core/src/patch/apply.rs index 6a0a66836..421355cef 100644 --- a/crates/socket-patch-core/src/patch/apply.rs +++ b/crates/socket-patch-core/src/patch/apply.rs @@ -108,6 +108,69 @@ impl<'a> PatchSources<'a> { } } +/// Why a package's patch did not apply: a stable code for the `cause` of +/// a failed `--json` event and the `code` its telemetry reports. Never +/// carries a name, path or version. +/// +/// [`Unclassified`](Self::Unclassified) is a failure whose path sets no +/// cause, kept as its own value so that share can be measured and the +/// path named. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ApplyFailureCause { + /// A file matches neither the patch's original nor its patched hash: + /// a different build of the version, or a local edit. + HashMismatch, + /// A file the patch changes is not in the installed copy. + FileNotFound, + /// The patch names a path outside the package directory. + UnsafePath, + /// The copy is in a store other projects share (pnpm's global virtual + /// store, PDM's cache): patching it would patch them too. + SharedStore, + /// A conda build of the package the patch cannot be applied to. + CondaBuild, + /// The patched content is not in the blob store and could not be read. + BlobMissing, + /// A blob's content does not hash to its name. + BlobCorrupt, + /// Staging or committing a file failed (permissions, disk, a lock). + WriteFailed, + /// An ecosystem's checksum or metadata files could not be brought in + /// line with the patched files. + SidecarFailed, + /// No release variant in the manifest matches the installed one (a + /// wheel, platform gem or Maven classifier). + NoMatchingVariant, + /// Refused before writing, under the refusal's own stable code (a + /// Gradle build that verifies dependencies, a cache copy with bytes + /// no variant was made for, …). + Refused(&'static str), + /// A failure on a path that sets no cause. + Unclassified, +} + +impl ApplyFailureCause { + /// The code: snake_case, the names `apply --check` uses for the same + /// states where it has one (`hash_mismatch`, `file_not_found`, + /// `no_matching_variant`). + pub fn as_str(self) -> &'static str { + match self { + Self::HashMismatch => "hash_mismatch", + Self::FileNotFound => "file_not_found", + Self::UnsafePath => "unsafe_path", + Self::SharedStore => "shared_store", + Self::CondaBuild => "conda_build", + Self::BlobMissing => "blob_missing", + Self::BlobCorrupt => "blob_corrupt", + Self::WriteFailed => "write_failed", + Self::SidecarFailed => "sidecar_failed", + Self::NoMatchingVariant => "no_matching_variant", + Self::Refused(code) => code, + Self::Unclassified => "unclassified", + } + } +} + /// Result of applying patches to a single package. #[derive(Debug, Clone)] pub struct ApplyResult { @@ -133,6 +196,37 @@ pub struct ApplyResult { /// Surfaced in the CLI JSON envelope under /// `Envelope.sidecars[]` (top-level, not per-event). pub sidecar: Option, + /// Why the package failed, where the failing path knows. Read it + /// through [`ApplyResult::failure_cause`], which also covers a failure + /// that set none. + pub cause: Option, +} + +impl ApplyResult { + /// Why this package failed; `None` when it did not. A failure that set + /// no cause is named by the file that stopped it (the verify loop stops + /// at the first file it cannot patch), else + /// [`ApplyFailureCause::Unclassified`]. + pub fn failure_cause(&self) -> Option { + if self.success { + return None; + } + Some( + self.cause + .unwrap_or_else(|| match self.files_verified.last().map(|v| v.status) { + Some(VerifyStatus::HashMismatch) => ApplyFailureCause::HashMismatch, + Some(VerifyStatus::NotFound) => ApplyFailureCause::FileNotFound, + _ => ApplyFailureCause::Unclassified, + }), + ) + } + + /// Fail the result with `cause` and `error`. + fn fail(&mut self, cause: ApplyFailureCause, error: String) { + self.success = false; + self.cause = Some(cause); + self.error = Some(error); + } } /// A patch's files in file-name order: the verify and write loops walk @@ -1425,7 +1519,11 @@ impl crate::patch::store_copies::CopyFold for ApplyResult { self.success } - fn mark_failed(&mut self) { + fn mark_failed(&mut self, copy: &Self) { + // The first failure names the package's cause. + if self.success { + self.cause = copy.failure_cause(); + } self.success = false; } @@ -1621,6 +1719,7 @@ async fn apply_package_patch_at( applied_via: HashMap::new(), error: None, sidecar: None, + cause: None, }; // A package dir that resolves into a store other projects link to @@ -1635,7 +1734,7 @@ async fn apply_package_patch_at( ) .await { - result.error = Some(store.refusal("patch")); + result.fail(ApplyFailureCause::SharedStore, store.refusal("patch")); return result; } @@ -1659,6 +1758,7 @@ async fn apply_package_patch_at( // A compiled build is one a command skips, with this // text as its warning. Any other refusal fails the // copy on every run, so it says how to drop the record. + result.cause = Some(ApplyFailureCause::CondaBuild); result.error = Some(if build.unsupported(pkg_path).is_some() { refused } else { @@ -1685,9 +1785,12 @@ async fn apply_package_patch_at( // disk write — NOT skippable by `--force`, since a path escape is never // a legitimate patch target. if !is_safe_relative_subpath(normalize_file_path(file_name)) { - result.error = Some(format!( - "Refusing patch with unsafe file path (escapes package directory): {file_name}" - )); + result.fail( + ApplyFailureCause::UnsafePath, + format!( + "Refusing patch with unsafe file path (escapes package directory): {file_name}" + ), + ); return result; } @@ -1741,10 +1844,14 @@ async fn apply_package_patch_at( .message .clone() .unwrap_or_else(|| format!("{:?}", verify_result.status)); - result.error = Some(format!( - "Cannot apply patch: {} - {}", - verify_result.file, msg - )); + result.fail( + if verify_result.status == VerifyStatus::NotFound { + ApplyFailureCause::FileNotFound + } else { + ApplyFailureCause::HashMismatch + }, + format!("Cannot apply patch: {} - {}", verify_result.file, msg), + ); result.files_verified.push(verify_result); return result; } @@ -1807,7 +1914,8 @@ async fn apply_package_patch_at( ) .await; if let Some(why) = result.sidecar.as_ref().and_then(|s| s.fixup_failure()) { - result.error = Some(why.to_string()); + let why = why.to_string(); + result.fail(ApplyFailureCause::SidecarFailed, why); return result; } } @@ -1886,12 +1994,15 @@ async fn apply_package_patch_at( }); } } - result.error = Some(format!( - "Cannot apply patch: {}{}{}", - e.file.map(|file| format!("{file} - ")).unwrap_or_default(), - e.source, - not_restored_note(&e.not_restored) - )); + result.fail( + ApplyFailureCause::WriteFailed, + format!( + "Cannot apply patch: {}{}{}", + e.file.map(|file| format!("{file} - ")).unwrap_or_default(), + e.source, + not_restored_note(&e.not_restored) + ), + ); }; // Stage every file that needs writing before the first is renamed into @@ -1918,31 +2029,33 @@ async fn apply_package_patch_at( // vendor flows stage there, so vendoring writes no `.socket/blobs` // entries), then the on-disk blob, which must hold the bytes its // name promises. - let patched_content: Cow<'_, [u8]> = - if let Some(bytes) = sources.mem_blobs.and_then(|m| m.get(&file_info.after_hash)) { - Cow::Borrowed(bytes.as_slice()) - } else { - let blob = read_blob(sources.blobs_path, &file_info.after_hash) - .await - .and_then(|bytes| { - let hash = compute_git_sha256_from_bytes(&bytes); - if hash == file_info.after_hash { - return Ok(bytes); - } - Err(corrupt_blob_error( - &sources.blobs_path.join(&file_info.after_hash), - &hash, - )) - }); - match blob { - Ok(bytes) => Cow::Owned(bytes), - Err(msg) => { - abort_package(write).await; - result.error = Some(format!("Cannot apply patch: {file_name} - {msg}")); - return result; + let patched_content: Cow<'_, [u8]> = if let Some(bytes) = + sources.mem_blobs.and_then(|m| m.get(&file_info.after_hash)) + { + Cow::Borrowed(bytes.as_slice()) + } else { + let blob = read_blob(sources.blobs_path, &file_info.after_hash) + .await + .map_err(|msg| (ApplyFailureCause::BlobMissing, msg)) + .and_then(|bytes| { + let hash = compute_git_sha256_from_bytes(&bytes); + if hash == file_info.after_hash { + return Ok(bytes); } + Err(( + ApplyFailureCause::BlobCorrupt, + corrupt_blob_error(&sources.blobs_path.join(&file_info.after_hash), &hash), + )) + }); + match blob { + Ok(bytes) => Cow::Owned(bytes), + Err((cause, msg)) => { + abort_package(write).await; + result.fail(cause, format!("Cannot apply patch: {file_name} - {msg}")); + return result; } - }; + } + }; // A bin npm installed with an LF shebang gets the patched bytes in // that form too (see `npm_bin`). @@ -1959,7 +2072,10 @@ async fn apply_package_patch_at( Ok(write) => write, Err(e) => { abort_package(write).await; - result.error = Some(format!("Cannot apply patch: {file_name} - {e}")); + result.fail( + ApplyFailureCause::WriteFailed, + format!("Cannot apply patch: {file_name} - {e}"), + ); return result; } }; @@ -2034,7 +2150,10 @@ async fn apply_package_patch_at( not_restored_note(¬_restored) ) }; - result.error = Some(format!("Cannot apply patch: {message}")); + result.fail( + ApplyFailureCause::SidecarFailed, + format!("Cannot apply patch: {message}"), + ); result.sidecar = Some(fixup_failed_record(package_key, message)); return result; } @@ -2120,6 +2239,99 @@ mod tests { use super::*; use crate::hash::git_sha256::compute_git_sha256_from_bytes; + fn result_with(success: bool, statuses: &[VerifyStatus]) -> ApplyResult { + ApplyResult { + package_key: "pkg:npm/a@1.0.0".to_string(), + package_path: "/tmp/a".to_string(), + success, + files_verified: statuses + .iter() + .map(|&status| VerifyResult { + file: "package/index.js".to_string(), + status, + message: None, + current_hash: None, + expected_hash: None, + target_hash: None, + }) + .collect(), + files_patched: Vec::new(), + applied_via: HashMap::new(), + error: None, + sidecar: None, + cause: None, + } + } + + /// A success has no cause; a failure that set none is named by the + /// file that stopped it, else `unclassified`; a set cause wins. + #[test] + fn failure_cause_falls_back_to_the_file_that_stopped_the_apply() { + assert_eq!( + result_with(true, &[VerifyStatus::HashMismatch]).failure_cause(), + None + ); + assert_eq!( + result_with(false, &[VerifyStatus::Ready, VerifyStatus::HashMismatch]).failure_cause(), + Some(ApplyFailureCause::HashMismatch) + ); + assert_eq!( + result_with(false, &[VerifyStatus::NotFound]).failure_cause(), + Some(ApplyFailureCause::FileNotFound) + ); + assert_eq!( + result_with(false, &[VerifyStatus::Ready]).failure_cause(), + Some(ApplyFailureCause::Unclassified) + ); + let mut set = result_with(false, &[VerifyStatus::HashMismatch]); + set.cause = Some(ApplyFailureCause::WriteFailed); + assert_eq!(set.failure_cause(), Some(ApplyFailureCause::WriteFailed)); + } + + /// A store copy that fails fails its package under the copy's cause. + #[test] + fn a_failed_store_copy_gives_its_package_its_cause() { + use crate::patch::store_copies::CopyFold; + let mut primary = result_with(true, &[VerifyStatus::Ready]); + let mut copy = result_with(false, &[VerifyStatus::Ready]); + copy.cause = Some(ApplyFailureCause::BlobCorrupt); + primary.mark_failed(©); + assert!(!primary.success); + assert_eq!( + primary.failure_cause(), + Some(ApplyFailureCause::BlobCorrupt) + ); + // A second failed copy does not replace the first one's cause. + let mut other = result_with(false, &[VerifyStatus::HashMismatch]); + other.cause = None; + primary.mark_failed(&other); + assert_eq!( + primary.failure_cause(), + Some(ApplyFailureCause::BlobCorrupt) + ); + } + + /// Every cause has its own code. + #[test] + fn failure_cause_codes_are_distinct() { + let all = [ + ApplyFailureCause::HashMismatch, + ApplyFailureCause::FileNotFound, + ApplyFailureCause::UnsafePath, + ApplyFailureCause::SharedStore, + ApplyFailureCause::CondaBuild, + ApplyFailureCause::BlobMissing, + ApplyFailureCause::BlobCorrupt, + ApplyFailureCause::WriteFailed, + ApplyFailureCause::SidecarFailed, + ApplyFailureCause::NoMatchingVariant, + ApplyFailureCause::Refused("gradle_copy_unexpected_bytes"), + ApplyFailureCause::Unclassified, + ]; + let codes: std::collections::HashSet<&str> = all.iter().map(|c| c.as_str()).collect(); + assert_eq!(codes.len(), all.len()); + } + #[test] fn test_normalize_file_path_with_prefix() { assert_eq!( @@ -4618,6 +4830,7 @@ mod tests { applied_via: HashMap::new(), error: None, sidecar: None, + cause: None, }; let mut primary = clean(); diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 1feac92b5..84cb777e0 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -5389,6 +5389,7 @@ fn untouched_result(package_key: &str, pkg_path: &Path, error: Option) - applied_via: HashMap::new(), error, sidecar: None, + cause: None, } } diff --git a/crates/socket-patch-core/src/patch/jvm_jar.rs b/crates/socket-patch-core/src/patch/jvm_jar.rs index 94db45cab..60838e10e 100644 --- a/crates/socket-patch-core/src/patch/jvm_jar.rs +++ b/crates/socket-patch-core/src/patch/jvm_jar.rs @@ -409,6 +409,7 @@ fn result_for(swap: &JarSwap<'_>, dir: &Path) -> ApplyResult { applied_via: HashMap::new(), error: None, sidecar: None, + cause: None, } } diff --git a/crates/socket-patch-core/src/patch/rollback.rs b/crates/socket-patch-core/src/patch/rollback.rs index 5209cfdf0..0ae68be26 100644 --- a/crates/socket-patch-core/src/patch/rollback.rs +++ b/crates/socket-patch-core/src/patch/rollback.rs @@ -496,7 +496,7 @@ impl crate::patch::store_copies::CopyFold for RollbackResult { self.success } - fn mark_failed(&mut self) { + fn mark_failed(&mut self, _copy: &Self) { self.success = false; } diff --git a/crates/socket-patch-core/src/patch/store_copies.rs b/crates/socket-patch-core/src/patch/store_copies.rs index 4d1d7fa5a..a9c6c010a 100644 --- a/crates/socket-patch-core/src/patch/store_copies.rs +++ b/crates/socket-patch-core/src/patch/store_copies.rs @@ -32,7 +32,8 @@ pub(crate) trait CopyFold: Sized { /// The verb in a failed copy's note ("patch", "roll back"). const VERB: &'static str; fn success(&self) -> bool; - fn mark_failed(&mut self); + /// Fail `self` because `copy` (one of its other copies) failed. + fn mark_failed(&mut self, copy: &Self); fn error_mut(&mut self) -> &mut Option; /// Move `copy_result`'s per-file records into `self`, renaming each /// file with `qualify`. @@ -78,7 +79,7 @@ pub(crate) fn fold(result: &mut R, copy: &Path, mut copy_result: R) _ => return, } } else { - result.mark_failed(); + result.mark_failed(©_result); format!( "store copy {} failed to {}: {}", copy.display(), diff --git a/crates/socket-patch-core/src/telemetry.rs b/crates/socket-patch-core/src/telemetry.rs index 0b075d85e..6b9a0ca40 100644 --- a/crates/socket-patch-core/src/telemetry.rs +++ b/crates/socket-patch-core/src/telemetry.rs @@ -661,6 +661,8 @@ impl PatchOutcome { /// * `patches`: at most [`MAX_REPORTED_PATCHES`] outcomes, and /// `patches_truncated: true` when that cap dropped some; /// * `outcomes`: how many patches ended each way, over the whole run; +/// * `failure_codes`: how many failed patches had each `code` (`none` for +/// one without), over the whole run; absent when none failed; /// * `ecosystems`, `modes`: the distinct values, sorted, over the whole run. /// /// A run that named no patch adds nothing. @@ -674,10 +676,16 @@ fn with_patches(mut metadata: serde_json::Value, patches: &[PatchOutcome]) -> se return metadata; } let mut outcomes: BTreeMap<&str, usize> = BTreeMap::new(); + let mut failure_codes: BTreeMap<&str, usize> = BTreeMap::new(); let mut ecosystems: BTreeSet<&str> = BTreeSet::new(); let mut modes: BTreeSet<&str> = BTreeSet::new(); for patch in patches { *outcomes.entry(patch.outcome).or_default() += 1; + if patch.outcome == OUTCOME_FAILED { + *failure_codes + .entry(patch.code.as_deref().unwrap_or("none")) + .or_default() += 1; + } if !patch.ecosystem.is_empty() { ecosystems.insert(&patch.ecosystem); } @@ -699,6 +707,9 @@ fn with_patches(mut metadata: serde_json::Value, patches: &[PatchOutcome]) -> se } add("patches", serde_json::json!(reported)); add("outcomes", serde_json::json!(outcomes)); + if !failure_codes.is_empty() { + add("failure_codes", serde_json::json!(failure_codes)); + } add("ecosystems", serde_json::json!(ecosystems)); add("modes", serde_json::json!(modes)); metadata @@ -2957,11 +2968,30 @@ mod tests { ); assert_eq!(metadata["ecosystems"], serde_json::json!(["npm", "pypi"])); assert_eq!(metadata["modes"], serde_json::json!(["agent"])); + // Every failure is counted by code, the capped-off ones included. + assert_eq!( + metadata["failure_codes"], + serde_json::json!({ "hash_mismatch": failed }) + ); // Under the cap nothing is flagged. let short = with_patches(serde_json::json!({}), &patches[..3]); assert_eq!(short["patches"].as_array().unwrap().len(), 3); assert!(short.get("patches_truncated").is_none()); + // No failure, no `failure_codes`. + assert!(short.get("failure_codes").is_none()); + // A failure without a code is counted as `none`. + let uncoded = with_patches( + serde_json::json!({}), + &[outcome( + "00000000-0000-4000-8000-000000000000", + "npm", + MODE_AGENT, + OUTCOME_FAILED, + None, + )], + ); + assert_eq!(uncoded["failure_codes"], serde_json::json!({ "none": 1 })); // No patch, no fields; and the event's own keys are never replaced. assert_eq!( with_patches(serde_json::json!({ "dry_run": true }), &[]), diff --git a/crates/socket-patch-core/src/vendor/common.rs b/crates/socket-patch-core/src/vendor/common.rs index 2c9f37e2c..8f1cce227 100644 --- a/crates/socket-patch-core/src/vendor/common.rs +++ b/crates/socket-patch-core/src/vendor/common.rs @@ -82,6 +82,7 @@ pub(crate) fn synthesized_result( applied_via: HashMap::new(), error, sidecar: None, + cause: None, } } diff --git a/docs/configuration.md b/docs/configuration.md index bdd138dd4..aac500bee 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -137,7 +137,9 @@ Every event has these fields: A `scan` reports once for each project directory it scans. A failure event carries the subset of its row's fields known when it failed, plus `error_code`: the code the command's `--json` output reports (for example `patch_not_found` -or `rollback_failed`). `patch_fetch_failed` reports `uuid` only when you asked +or `rollback_failed`). A failed `apply` whose patch content could not be +obtained reports that stage instead of `apply_failed`: `sources_download_failed` +or `offline_missing_sources`. `patch_fetch_failed` reports `uuid` only when you asked for a patch by UUID. A command that stops on a usage error, or because another run holds the lock, reports nothing. @@ -148,9 +150,10 @@ 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`, `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`, `verified` on a dry run, `skipped`, `failed`). A `skipped` or `failed` entry adds `code`, the reason code `--json` reports (for example `already_patched`); a failed apply's entry uses the event's `cause` (for example `hash_mismatch`, `file_not_found`, `blob_missing`, `no_matching_variant`, `package_not_installed`) | | `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` (`none` for one without), over the whole run. Only when a patch failed | | `ecosystems`, `modes` | The distinct ecosystems and modes of those patches | A patch UUID is Socket's identifier for one patch, and each patch is for one From 2dcd6dfda2604688e09fe8d47f0c08430a01a633 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 11:32:25 -0500 Subject: [PATCH 2/4] Say in telemetry whether a run is in CI `context.ci` is `true` when `CI` is set to anything but empty, `0` or `false`, or `GITHUB_ACTIONS` is set: the same rule the update notifier already used, now shared from core. It tells CI runs from a developer's machine without naming the provider, repository or job. Co-Authored-By: Claude Opus 5.5 --- .../socket-patch-cli/src/update_notifier.rs | 14 +++------- crates/socket-patch-core/src/telemetry.rs | 14 ++++++++-- .../src/utils/socket_cli_config.rs | 28 +++++++++++++++++++ docs/configuration.md | 1 + 4 files changed, 45 insertions(+), 12 deletions(-) diff --git a/crates/socket-patch-cli/src/update_notifier.rs b/crates/socket-patch-cli/src/update_notifier.rs index 200bcdaef..faf9f21bb 100644 --- a/crates/socket-patch-cli/src/update_notifier.rs +++ b/crates/socket-patch-cli/src/update_notifier.rs @@ -23,7 +23,7 @@ use socket_patch_core::update::{ self as core_update, detect_channel, is_newer, upgrade_hint, upgrade_hint_for, ChannelEnv, InstallChannel, UpdateEndpoints, UpdateTimeouts, }; -use socket_patch_core::utils::socket_cli_config::env_truthy; +use socket_patch_core::utils::socket_cli_config::{env_truthy, running_in_ci}; use crate::args::GlobalArgs; @@ -104,20 +104,14 @@ fn should_check(ctx: &GuardCtx) -> Result<(), SkipReason> { impl GuardCtx { /// Capture the real environment + the parsed global flags. fn capture(common: &GlobalArgs) -> Self { - let ci = std::env::var("CI").unwrap_or_default(); GuardCtx { opted_out: env_truthy("SOCKET_NO_UPDATE_CHECK"), offline: common.offline, silent: common.silent, json: common.json, - // `CI` set to anything non-empty except an explicit falsy counts; - // `GITHUB_ACTIONS` counts whenever non-empty. Deliberately short - // list — the TTY guard covers other vendors' runners anyway. - ci: (!ci.is_empty() - && !matches!(ci.trim().to_ascii_lowercase().as_str(), "0" | "false")) - || !std::env::var("GITHUB_ACTIONS") - .unwrap_or_default() - .is_empty(), + // Deliberately short list — the TTY guard covers other + // vendors' runners anyway. + ci: running_in_ci(), // The notice prints on stderr; stdout may be legitimately piped // (`list | jq`) in a perfectly interactive session. stderr_tty: crate::ui::attended(crate::ui::Stream::Stderr), diff --git a/crates/socket-patch-core/src/telemetry.rs b/crates/socket-patch-core/src/telemetry.rs index 6b9a0ca40..107f21ac7 100644 --- a/crates/socket-patch-core/src/telemetry.rs +++ b/crates/socket-patch-core/src/telemetry.rs @@ -130,6 +130,11 @@ struct PatchTelemetryContext { /// [`InstallChannel::id`]: crate::update::channel::InstallChannel::id #[serde(skip_serializing_if = "Option::is_none")] channel: Option<&'static str>, + /// Whether the run is in CI ([`running_in_ci`]): `CI` or + /// `GITHUB_ACTIONS` set. A flag, never which provider or which job. + /// + /// [`running_in_ci`]: crate::utils::socket_cli_config::running_in_ci + ci: bool, } /// Error details for telemetry events. @@ -241,6 +246,7 @@ fn build_telemetry_context(command: &str) -> PatchTelemetryContext { arch: std::env::consts::ARCH.to_string(), command: command.to_string(), channel: install_channel(), + ci: crate::utils::socket_cli_config::running_in_ci(), } } @@ -2145,7 +2151,10 @@ mod tests { // where the binary cannot read its own path. match install_channel() { Some(channel) => { - assert_eq!(ctx, ["arch", "channel", "command", "platform", "version"]); + assert_eq!( + ctx, + ["arch", "channel", "ci", "command", "platform", "version"] + ); assert_eq!(v["context"]["channel"], channel); assert!( [ @@ -2160,8 +2169,9 @@ mod tests { "unexpected channel id {channel}" ); } - None => assert_eq!(ctx, ["arch", "command", "platform", "version"]), + None => assert_eq!(ctx, ["arch", "ci", "command", "platform", "version"]), } + assert!(v["context"]["ci"].is_boolean(), "{v:#}"); assert_eq!(v["error"]["type"], "Error"); assert_eq!(v["error"]["message"], "boom"); assert_eq!(v["metadata"]["patches_count"], 2); diff --git a/crates/socket-patch-core/src/utils/socket_cli_config.rs b/crates/socket-patch-core/src/utils/socket_cli_config.rs index 7175eb86c..b30ebf6dd 100644 --- a/crates/socket-patch-core/src/utils/socket_cli_config.rs +++ b/crates/socket-patch-core/src/utils/socket_cli_config.rs @@ -66,6 +66,21 @@ pub fn env_truthy(name: &str) -> bool { ) } +/// Whether this process runs in CI: `CI` set to anything but empty, `0` or +/// `false` (the convention CI providers follow), or `GITHUB_ACTIONS` set. +pub fn running_in_ci() -> bool { + ci_from( + std::env::var("CI").ok().as_deref(), + std::env::var("GITHUB_ACTIONS").ok().as_deref(), + ) +} + +/// [`running_in_ci`] over the two variables' values. +pub fn ci_from(ci: Option<&str>, github_actions: Option<&str>) -> bool { + let ci = ci.unwrap_or_default().trim().to_ascii_lowercase(); + (!ci.is_empty() && ci != "0" && ci != "false") || !github_actions.unwrap_or_default().is_empty() +} + /// `SOCKET_NO_CONFIG` — disable the socket-cli config fallback layer. pub fn is_config_disabled() -> bool { env_truthy("SOCKET_NO_CONFIG") @@ -240,6 +255,19 @@ mod tests { .into_bytes() } + #[test] + fn ci_is_a_set_ci_or_github_actions() { + assert!(!ci_from(None, None)); + for off in ["", " ", "0", "false", "FALSE"] { + assert!(!ci_from(Some(off), None), "CI={off:?}"); + } + for on in ["1", "true", "woodpecker"] { + assert!(ci_from(Some(on), None), "CI={on:?}"); + } + assert!(ci_from(None, Some("true"))); + assert!(!ci_from(None, Some(""))); + } + #[test] fn parses_base64_encoded_json() { let cfg = parse_config_bytes(&b64( diff --git a/docs/configuration.md b/docs/configuration.md index aac500bee..80b6ac1ed 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -116,6 +116,7 @@ Every event has these fields: | `context.platform`, `context.arch` | Operating system and CPU architecture (for example `linux`, `x86_64`) | | `context.command` | The subcommand (`scan`, `apply`, …) | | `context.channel` | How this copy of Socket Patch was installed: `npm`, `cargo`, `homebrew`, `pypi` or `launcher_cache` when the binary sits where that tool puts it, and `standalone` for anywhere else (the install script, a downloaded binary, a container image). It names the channel only, never the path, and is left out when the binary cannot read its own location | +| `context.ci` | `true` when the run is in CI (the `CI` variable is set to anything but empty, `0` or `false`, or `GITHUB_ACTIONS` is set), else `false`. It never names the provider, the repository or the job | | `metadata` | The per-event fields in the table below, and nothing else | | `error.type`, `error.message` | Failure events only. URLs in the message are redacted (credentials, grant tokens, signed query values), your home directory is replaced by `~`, and a message longer than 1,000 characters is cut. The message can still quote a package name or a path in the project | From b7a89655ba18bb9d1fe0c2e142c241769d21bbb1 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 12:06:58 -0500 Subject: [PATCH 3/4] Name an apply failure's cause only where the path that failed it knows Review fixes: - Drop the fallback that guessed a cause from the verified files: a step after a successful engine run (a failed native rebuild, a `--force` skip) could leave the last file describing something else. A failure with no cause set is `unclassified`. - Set the cause where results are failed outside the engine: gem refusals and `native_extension_build_failed`, Gradle's stale transform copies, a failed `go.mod` edit (`write_failed`). `Refused` becomes `Coded` and the enum is `#[non_exhaustive]`. - A copy no release variant matches is reported as `no_matching_variant`, not `package_not_installed`; once per record, never a record another copy applied; Maven entries come from the manifest-filtered variants. - A failed store copy's cause is read before its files move. - The contract says which causes reach `--json` and which only telemetry. Co-Authored-By: Claude Opus 5.5 --- crates/socket-patch-cli/CLI_CONTRACT.md | 10 ++- crates/socket-patch-cli/src/commands/apply.rs | 87 +++++++++++++++---- crates/socket-patch-cli/src/json_envelope.rs | 4 +- crates/socket-patch-core/src/patch/apply.rs | 49 +++++------ crates/socket-patch-core/src/patch/gem_ext.rs | 11 ++- .../src/patch/redirect/golang_local.rs | 2 + .../src/patch/store_copies.rs | 5 +- 7 files changed, 115 insertions(+), 53 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 3f5959494..6f46aa010 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -175,9 +175,13 @@ A missing referenced diff does not remove that protection. the package's patch did not apply: `hash_mismatch` (a file matches neither the original nor the patched bytes), `file_not_found`, `blob_missing`, `blob_corrupt`, `write_failed`, `sidecar_failed`, `shared_store`, - `conda_build`, `unsafe_path`, `no_matching_variant`, a Maven refusal's own - code (for example `gradle_copy_unexpected_bytes` or `jvm_agent_service_required`), - or `unclassified` for a failure whose path names none. Route on `errorCode`; `cause` refines it and new values may be added. + `conda_build`, `unsafe_path`, a refusal's or a native rebuild's own code + (for example `gradle_copy_unexpected_bytes`, `jvm_agent_service_required` + or `native_extension_build_failed`), or `unclassified` for a failure whose + path names none. Route on `errorCode`; `cause` refines it and new values may + be added. A failure with no package event (a copy no release variant + matches, a Maven base refused as a whole) has no `cause` here; telemetry + reports it as `no_matching_variant` or the refusal's code. `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` diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index f79bf014c..1dfb2d535 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -2501,9 +2501,13 @@ fn telemetry_command(args: &ApplyArgs) -> &'static str { /// The patches an apply run acted on, as its telemetry names them: the /// run's per-package events ([`GemCaveats::event_of`], what `--json` -/// prints), the patches that failed the run by not being installed -/// (`failures`), and the failures no result describes (`unreported`), -/// each under the patch its manifest record names. +/// prints), the failures no result describes (`unreported`, once each, +/// leaving out a record another copy applied), and the patches that failed +/// the run by not being installed (`failures`), each under the patch its +/// manifest record names. +/// +/// `unreported` comes before `failures`: 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( @@ -2514,18 +2518,29 @@ fn reported_patches( dry_run: bool, patch_uuids: &HashMap, ) -> Vec { + let applied: HashSet<&str> = results + .iter() + .filter(|r| r.success) + .map(|r| r.package_key.as_str()) + .collect(); + let mut named: HashSet<&str> = HashSet::new(); + let unreported: Vec = unreported + .iter() + .filter(|(purl, _)| !applied.contains(purl.as_str()) && named.insert(purl.as_str())) + .map(|(purl, cause)| { + PatchEvent::new(PatchAction::Failed, purl.as_str()).with_cause(cause.as_str()) + }) + .collect(); let events: Vec = results .iter() .map(|result| caveats.event_of(result, dry_run)) + .chain(unreported) .chain( failures .iter() - .filter(|f| f.code == "package_not_installed") + .filter(|f| f.code == "package_not_installed" && !named.contains(f.purl.as_str())) .map(|f| f.event(&f.purl)), ) - .chain(unreported.iter().map(|(purl, cause)| { - PatchEvent::new(PatchAction::Failed, purl.as_str()).with_cause(cause.as_str()) - })) .collect(); crate::telemetry_outcomes::patch_outcomes( &events, @@ -4271,7 +4286,7 @@ impl MavenApplied { applied_via: HashMap::new(), error: Some(format!("{code}: {detail}")), sidecar: None, - cause: Some(ApplyFailureCause::Refused(code)), + cause: Some(ApplyFailureCause::Coded(code)), }); self.warn(code, detail); self.failed = true; @@ -4387,10 +4402,10 @@ async fn apply_maven_base(m: &MavenBase<'_>) -> MavenApplied { ), ); out.failed = true; - out.unreported.extend(m.variants.iter().map(|v| { + out.unreported.extend(variants.iter().map(|v| { ( - v.clone(), - ApplyFailureCause::Refused("gradle_ro_cache_shadows"), + (*v).clone(), + ApplyFailureCause::Coded("gradle_ro_cache_shadows"), ) })); } @@ -4652,9 +4667,9 @@ async fn apply_maven_base(m: &MavenBase<'_>) -> MavenApplied { if !attempted && !out.failed && !gradle_only { out.failed = true; out.unreported.extend( - m.variants + variants .iter() - .map(|v| (v.clone(), ApplyFailureCause::NoMatchingVariant)), + .map(|v| ((*v).clone(), ApplyFailureCause::NoMatchingVariant)), ); if args.prints_errors() { eprintln!( @@ -4738,6 +4753,7 @@ async fn check_derived_copies( list(&stale) ); result.success = false; + result.cause = Some(ApplyFailureCause::Coded("gradle_transform_copy_stale")); result.error = Some(format!("gradle_transform_copy_stale: {detail}")); out.warn("gradle_transform_copy_stale", detail); } @@ -5204,7 +5220,7 @@ mod tests { ), ( "pkg:maven/g/a@1.0".to_string(), - ApplyFailureCause::Refused("gradle_ro_cache_shadows"), + ApplyFailureCause::Coded("gradle_ro_cache_shadows"), ), ]; let reported = reported_patches( @@ -5222,13 +5238,54 @@ mod tests { assert_eq!( named, [ - ("u-gone", "failed", Some("package_not_installed")), ("u-wheel", "failed", Some("no_matching_variant")), ("u-maven", "failed", Some("gradle_ro_cache_shadows")), + ("u-gone", "failed", Some("package_not_installed")), ] ); } + /// 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 + /// variant another copy applied. + #[test] + fn an_unmatched_variant_is_not_reported_as_not_installed() { + let wheel = "pkg:pypi/w@1.0?artifact_id=a".to_string(); + let other = "pkg:pypi/w@1.0?artifact_id=b".to_string(); + let uuids = HashMap::from([ + (wheel.clone(), "u-a".to_string()), + (other.clone(), "u-b".to_string()), + ]); + let failures = [ApplyFailure { + purl: wheel.clone(), + code: "package_not_installed".to_string(), + error: "No installed package matches this PURL".to_string(), + cause: None, + }]; + let unreported = [ + (wheel.clone(), ApplyFailureCause::NoMatchingVariant), + (other.clone(), ApplyFailureCause::NoMatchingVariant), + (wheel.clone(), ApplyFailureCause::NoMatchingVariant), + ]; + let mut applied_b = failed_result(&other, None); + applied_b.success = true; + let reported = reported_patches( + &[applied_b], + &GemCaveats::default(), + &failures, + &unreported, + false, + &uuids, + ); + let failed: Vec<(&str, Option<&str>)> = reported + .iter() + .filter(|p| p.outcome == "failed") + .map(|p| (p.uuid.as_str(), p.code.as_deref())) + .collect(); + assert_eq!(failed, [("u-a", Some("no_matching_variant"))]); + } + /// A run stopped before patching anything reports that stage. #[test] fn run_failure_code_is_the_stage_that_stopped_the_run() { diff --git a/crates/socket-patch-cli/src/json_envelope.rs b/crates/socket-patch-cli/src/json_envelope.rs index 45771c3dd..dbd6da521 100644 --- a/crates/socket-patch-cli/src/json_envelope.rs +++ b/crates/socket-patch-cli/src/json_envelope.rs @@ -382,8 +382,8 @@ pub struct PatchEvent { pub error: Option, /// Why a `Failed` apply event's patch did not apply, finer than its /// `error_code` (which stays `apply_failed`): `hash_mismatch`, - /// `file_not_found`, `blob_missing`, `write_failed`, - /// `no_matching_variant`, … or `unclassified`. Omitted elsewhere. + /// `file_not_found`, `blob_missing`, `write_failed`, a refusal's own + /// code, … or `unclassified`. Omitted elsewhere. #[serde(skip_serializing_if = "Option::is_none")] pub cause: Option, /// Command-specific additional fields. Consumers MUST NOT depend on diff --git a/crates/socket-patch-core/src/patch/apply.rs b/crates/socket-patch-core/src/patch/apply.rs index 421355cef..f738bb996 100644 --- a/crates/socket-patch-core/src/patch/apply.rs +++ b/crates/socket-patch-core/src/patch/apply.rs @@ -114,8 +114,9 @@ impl<'a> PatchSources<'a> { /// /// [`Unclassified`](Self::Unclassified) is a failure whose path sets no /// cause, kept as its own value so that share can be measured and the -/// path named. +/// path named. New causes may be added. #[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] pub enum ApplyFailureCause { /// A file matches neither the patch's original nor its patched hash: /// a different build of the version, or a local edit. @@ -141,10 +142,10 @@ pub enum ApplyFailureCause { /// No release variant in the manifest matches the installed one (a /// wheel, platform gem or Maven classifier). NoMatchingVariant, - /// Refused before writing, under the refusal's own stable code (a - /// Gradle build that verifies dependencies, a cache copy with bytes - /// no variant was made for, …). - Refused(&'static str), + /// A failure under a stable code of its own: a refusal before writing + /// (a Gradle build that verifies dependencies, a native gem that cannot + /// be rebuilt here, …) or a native rebuild that failed. + Coded(&'static str), /// A failure on a path that sets no cause. Unclassified, } @@ -165,7 +166,7 @@ impl ApplyFailureCause { Self::WriteFailed => "write_failed", Self::SidecarFailed => "sidecar_failed", Self::NoMatchingVariant => "no_matching_variant", - Self::Refused(code) => code, + Self::Coded(code) => code, Self::Unclassified => "unclassified", } } @@ -196,29 +197,19 @@ pub struct ApplyResult { /// Surfaced in the CLI JSON envelope under /// `Envelope.sidecars[]` (top-level, not per-event). pub sidecar: Option, - /// Why the package failed, where the failing path knows. Read it - /// through [`ApplyResult::failure_cause`], which also covers a failure - /// that set none. + /// Why the package failed, set by the path that failed it. Read it + /// through [`ApplyResult::failure_cause`], which names a failure that + /// set none. pub cause: Option, } impl ApplyResult { /// Why this package failed; `None` when it did not. A failure that set - /// no cause is named by the file that stopped it (the verify loop stops - /// at the first file it cannot patch), else - /// [`ApplyFailureCause::Unclassified`]. + /// no cause is [`ApplyFailureCause::Unclassified`]: it is never guessed + /// from `files_verified`, which a later step (a rebuild, a `--force` + /// skip) can leave describing something other than what failed. pub fn failure_cause(&self) -> Option { - if self.success { - return None; - } - Some( - self.cause - .unwrap_or_else(|| match self.files_verified.last().map(|v| v.status) { - Some(VerifyStatus::HashMismatch) => ApplyFailureCause::HashMismatch, - Some(VerifyStatus::NotFound) => ApplyFailureCause::FileNotFound, - _ => ApplyFailureCause::Unclassified, - }), - ) + (!self.success).then(|| self.cause.unwrap_or(ApplyFailureCause::Unclassified)) } /// Fail the result with `cause` and `error`. @@ -2263,21 +2254,21 @@ mod tests { } } - /// A success has no cause; a failure that set none is named by the - /// file that stopped it, else `unclassified`; a set cause wins. + /// A success has no cause; a failure that set none is `unclassified`, + /// whatever its files say; a set cause wins. #[test] - fn failure_cause_falls_back_to_the_file_that_stopped_the_apply() { + fn failure_cause_is_the_one_set_never_a_guess() { assert_eq!( result_with(true, &[VerifyStatus::HashMismatch]).failure_cause(), None ); assert_eq!( result_with(false, &[VerifyStatus::Ready, VerifyStatus::HashMismatch]).failure_cause(), - Some(ApplyFailureCause::HashMismatch) + Some(ApplyFailureCause::Unclassified) ); assert_eq!( result_with(false, &[VerifyStatus::NotFound]).failure_cause(), - Some(ApplyFailureCause::FileNotFound) + Some(ApplyFailureCause::Unclassified) ); assert_eq!( result_with(false, &[VerifyStatus::Ready]).failure_cause(), @@ -2325,7 +2316,7 @@ mod tests { ApplyFailureCause::WriteFailed, ApplyFailureCause::SidecarFailed, ApplyFailureCause::NoMatchingVariant, - ApplyFailureCause::Refused("gradle_copy_unexpected_bytes"), + ApplyFailureCause::Coded("gradle_copy_unexpected_bytes"), ApplyFailureCause::Unclassified, ]; let codes: std::collections::HashSet<&str> = all.iter().map(|c| c.as_str()).collect(); diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 84cb777e0..e2cd1c8f7 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -5393,10 +5393,12 @@ fn untouched_result(package_key: &str, pkg_path: &Path, error: Option) - } } -fn refusal(package_key: &str, pkg_path: &Path, code: &str, detail: String) -> GemApplied { +fn refusal(package_key: &str, pkg_path: &Path, code: &'static str, detail: String) -> GemApplied { + let mut result = untouched_result(package_key, pkg_path, Some(format!("{code}: {detail}"))); + result.cause = Some(crate::patch::apply::ApplyFailureCause::Coded(code)); GemApplied { caveat: None, - result: untouched_result(package_key, pkg_path, Some(format!("{code}: {detail}"))), + result, warning: Some((code.to_string(), detail)), } } @@ -5521,7 +5523,7 @@ struct Job<'a> { } impl Job<'_> { - fn refuse(&self, code: &str, detail: String) -> GemApplied { + fn refuse(&self, code: &'static str, detail: String) -> GemApplied { refusal(self.package_key, self.pkg_path, code, detail) } @@ -5639,6 +5641,9 @@ impl Job<'_> { ) -> GemApplied { revert_sources(self.pkg_path, originals, &result.files_patched).await; result.success = false; + result.cause = Some(crate::patch::apply::ApplyFailureCause::Coded( + BUILD_FAILED_CODE, + )); result.files_patched.clear(); result.applied_via.clear(); // What the written sources were advised about (`bundle install diff --git a/crates/socket-patch-core/src/patch/redirect/golang_local.rs b/crates/socket-patch-core/src/patch/redirect/golang_local.rs index e22a5b117..cc6e86512 100644 --- a/crates/socket-patch-core/src/patch/redirect/golang_local.rs +++ b/crates/socket-patch-core/src/patch/redirect/golang_local.rs @@ -480,6 +480,7 @@ pub async fn apply_go_redirect<'a>( go_mod_edit::ensure_replace_entry(project_root, module, version, base_rel, false).await { result.success = false; + result.cause = Some(crate::patch::apply::ApplyFailureCause::WriteFailed); result.error = Some(format!("failed to update go.mod: {e}")); return result; } @@ -957,6 +958,7 @@ async fn repair_root_go_mod_mirror( go_mod_edit::ensure_replace_entry(project_root, module, version, base_rel, false).await { result.success = false; + result.cause = Some(crate::patch::apply::ApplyFailureCause::WriteFailed); result.error = Some(format!("failed to update go.mod: {e}")); } } diff --git a/crates/socket-patch-core/src/patch/store_copies.rs b/crates/socket-patch-core/src/patch/store_copies.rs index a9c6c010a..8650a8e8c 100644 --- a/crates/socket-patch-core/src/patch/store_copies.rs +++ b/crates/socket-patch-core/src/patch/store_copies.rs @@ -72,6 +72,10 @@ where /// Merge one store copy's result into the primary's (see the module docs). pub(crate) fn fold(result: &mut R, copy: &Path, mut copy_result: R) { let qualify = |file: &str| copy.join(normalize_file_path(file)).display().to_string(); + // Before its files move: what failed the copy is read from it whole. + if !copy_result.success() { + result.mark_failed(©_result); + } result.extend_files(&mut copy_result, &qualify); let note = if copy_result.success() { match copy_result.error_mut().take() { @@ -79,7 +83,6 @@ pub(crate) fn fold(result: &mut R, copy: &Path, mut copy_result: R) _ => return, } } else { - result.mark_failed(©_result); format!( "store copy {} failed to {}: {}", copy.display(), From 165c83aebd0ce3687384320137a27b6f9112b035 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 25 Nov 2026 12:54:58 -0500 Subject: [PATCH 4/4] Keep a whole-base refusal in telemetry beside its applied copies `gradle_ro_cache_shadows` fails the run while the writable copies are patched; only a record no copy matched is left out when another copy applied it. Drop the configuration and contract doc edits. Co-Authored-By: Claude Opus 5.5 --- crates/socket-patch-cli/CLI_CONTRACT.md | 14 ++------ crates/socket-patch-cli/src/commands/apply.rs | 34 +++++++++++++++++-- docs/configuration.md | 8 ++--- 3 files changed, 35 insertions(+), 21 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 52e3ec707..81188b146 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -170,18 +170,6 @@ A missing referenced diff does not remove that protection. so a `postinstall` apply never fails an install over them. The manifest is not changed, and a skipped entry is not reconciled away as dropped. - Skipped events carry a stable `errorCode` and a human-readable `reason`. -- A failed `apply` event (standalone, or the nested apply of agent-mode `get` / - `scan`) keeps `errorCode: apply_failed` and adds `cause`, a stable code for why - the package's patch did not apply: `hash_mismatch` (a file matches neither the - original nor the patched bytes), `file_not_found`, `blob_missing`, - `blob_corrupt`, `write_failed`, `sidecar_failed`, `shared_store`, - `conda_build`, `unsafe_path`, a refusal's or a native rebuild's own code - (for example `gradle_copy_unexpected_bytes`, `jvm_agent_service_required` - or `native_extension_build_failed`), or `unclassified` for a failure whose - path names none. Route on `errorCode`; `cause` refines it and new values may - be added. A failure with no package event (a copy no release variant - matches, a Maven base refused as a whole) has no `cause` here; telemetry - reports it as `no_matching_variant` or the refusal's code. `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` @@ -770,6 +758,8 @@ Every VEX statement's impact string records which patch-application mode persist **Identifier overrides.** `--product` / `--vex-product` and `--doc-id` / `--vex-doc-id` are emitted with surrounding whitespace trimmed (a blank value means unset). +**Statement products.** The first product of every statement is the project (`--product` or the detected one), with the statement's packages as its subcomponents; readers that walk `products[0].subcomponents` see every package. Each package then follows as a product of its own with no subcomponents, which is how Trivy and Grype look a finding up, under its PURL and, for a gem with a `platform` qualifier, under the forms those scanners report it by: `pkg:gem/@` (Trivy) and, unless the platform is `ruby`, `pkg:gem/@-` (Grype, Syft), with the platform percent-decoded. Other qualifiers name a different artifact (a Maven classifier, a PyPI file), so they get no extra form. A form, the package's own PURL included, is left out of every statement of a vulnerability when it would stand for packages of that vulnerability, under its ID or any alias, with different statuses: an `affected` package, or one whose patch record the document leaves out, against a `not_affected` one. It is also left out when it equals the project's identifier. A scanner matches a package product wherever it finds that package, so the document is only for the project it was made for. + **No product to detect.** The product is read from the git `origin` remote, then from the name and version in `package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`, `composer.json`, `pom.xml`, the root's single `.csproj` or its single `.gemspec`. An application with none of these (a Bundler or pip project in a directory that has no git remote) has no product, and the run stops with `product_undetected` (`vex`: exit 2; embedded `--vex`: the host command's exit 1). No product is assumed: a directory name is not an identity (one checkout is `app` in a container and `workspace` in CI, and unrelated projects share those names), so a document issued under it could be read as a statement about another project. The message says what detection read, names any of those files that exists without a usable name and version, and ends with the run's own flag and a value built from the directory name, ready to paste: `… Pass a name that identifies this project, for example: --product pkg:generic/my-app` (`--vex-product …` on an embedded run). A run started in the project directory says `the current directory` instead of `.`. **Patch hosts (manifest-less VEX).** A hosted lockfile reference counts only when it points at Socket's patch server or the operator's `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin or under the `--patch-mirror-url` / `SOCKET_PATCH_MIRROR_URL` base. A hosted URL on any OTHER host — a staging patch server used without `--patch-server-url`, or a look-alike host — is not a hosted pin at all (v5.0: there is no redirect ledger to vouch for it), so `vex` does not attest it, and `list`, `rollback`, `remove`, `vendor` and `repair` do not see it either. Pass `--patch-server-url` for a non-production patch server. A pre-v5 redirect ledger still on disk does not change this: a record whose lockfile or recorded wiring resolves the package from a hosted-shaped URL on an origin this run was not given (or one carrying userinfo) is never attested from the ledger, whatever is installed and even under `--no-verify` / `--vex-no-verify`: `vex` reports it as `redirect_unwired`, with a `vex_claim_unwired` note naming the cause. (A patch that `apply`'s manifest also records is still verified as an agent-mode patch, on that record.) `scan` does not treat such wiring as gone: its takeover and hosted-wiring advisories still see it. diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 67a32edc1..91bc47e41 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -2523,8 +2523,10 @@ fn telemetry_command(args: &ApplyArgs) -> &'static str { /// The patches an apply run acted on, as its telemetry names them: the /// run's per-package events ([`GemCaveats::event_of`], what `--json` -/// prints), the failures no result describes (`unreported`, once each, -/// leaving out a record another copy applied), and the patches that failed +/// prints), the failures no result describes (`unreported`, once each; a +/// record no copy matched is left out when another copy applied it, while +/// 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. /// @@ -2548,7 +2550,10 @@ fn reported_patches( let mut named: HashSet<&str> = HashSet::new(); let unreported: Vec = unreported .iter() - .filter(|(purl, _)| !applied.contains(purl.as_str()) && named.insert(purl.as_str())) + .filter(|(purl, cause)| { + !(*cause == ApplyFailureCause::NoMatchingVariant && applied.contains(purl.as_str())) + && named.insert(purl.as_str()) + }) .map(|(purl, cause)| { PatchEvent::new(PatchAction::Failed, purl.as_str()).with_cause(cause.as_str()) }) @@ -5457,6 +5462,29 @@ mod tests { .map(|p| (p.uuid.as_str(), p.code.as_deref())) .collect(); assert_eq!(failed, [("u-a", Some("no_matching_variant"))]); + + // A refusal of the whole base fails the run though its writable + // copies were patched: it is reported beside them. + let refused = [( + other.clone(), + ApplyFailureCause::Coded("gradle_ro_cache_shadows"), + )]; + let mut applied_b = failed_result(&other, None); + applied_b.success = true; + let reported = reported_patches( + &[applied_b], + &GemCaveats::default(), + &[], + &refused, + false, + &uuids, + ); + let failed: Vec<(&str, Option<&str>)> = reported + .iter() + .filter(|p| p.outcome == "failed") + .map(|p| (p.uuid.as_str(), p.code.as_deref())) + .collect(); + assert_eq!(failed, [("u-b", Some("gradle_ro_cache_shadows"))]); } /// A run stopped before patching anything reports that stage. diff --git a/docs/configuration.md b/docs/configuration.md index fb1a551f1..4cca0f4c5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -124,7 +124,6 @@ Every event has these fields: | `context.platform`, `context.arch` | Operating system and CPU architecture (for example `linux`, `x86_64`) | | `context.command` | The subcommand (`scan`, `apply`, …) | | `context.channel` | How this copy of Socket Patch was installed: `npm`, `cargo`, `homebrew`, `pypi` or `launcher_cache` when the binary sits where that tool puts it, and `standalone` for anywhere else (the install script, a downloaded binary, a container image). It names the channel only, never the path, and is left out when the binary cannot read its own location | -| `context.ci` | `true` when the run is in CI (the `CI` variable is set to anything but empty, `0` or `false`, or `GITHUB_ACTIONS` is set), else `false`. It never names the provider, the repository or the job | | `metadata` | The per-event fields in the table below, and nothing else | | `error.type`, `error.message` | Failure events only. URLs in the message are redacted (credentials, grant tokens, signed query values), your home directory is replaced by `~`, and a message longer than 1,000 characters is cut. The message can still quote a package name or a path in the project | @@ -146,9 +145,7 @@ Every event has these fields: A `scan` reports once for each project directory it scans. A failure event carries the subset of its row's fields known when it failed, plus `error_code`: the code the command's `--json` output reports (for example `patch_not_found` -or `rollback_failed`). A failed `apply` whose patch content could not be -obtained reports that stage instead of `apply_failed`: `sources_download_failed` -or `offline_missing_sources`. `patch_fetch_failed` reports `uuid` only when you asked +or `rollback_failed`). `patch_fetch_failed` reports `uuid` only when you asked for a patch by UUID. A command that stops on a usage error, or because another run holds the lock, reports nothing. @@ -159,10 +156,9 @@ 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`, `verified` on a dry run, `skipped`, `failed`). A `skipped` or `failed` entry adds `code`, the reason code `--json` reports (for example `already_patched`); a failed apply's entry uses the event's `cause` (for example `hash_mismatch`, `file_not_found`, `blob_missing`, `no_matching_variant`, `package_not_installed`) | +| `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`, `verified` on a dry run, `skipped`, `failed`). A `skipped` or `failed` entry adds `code`, the reason code `--json` reports (for example `already_patched`) | | `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` (`none` for one without), over the whole run. Only when a patch failed | | `ecosystems`, `modes` | The distinct ecosystems and modes of those patches | A patch UUID is Socket's identifier for one patch, and each patch is for one