diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 76f5548b2..4d5926dcf 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -2072,11 +2072,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) @@ -2175,8 +2171,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 0904c008f..91bc47e41 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 @@ -1616,12 +1621,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 @@ -1680,8 +1699,8 @@ 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 => ( if caveats.is_no_variant(r) { NO_MATCHING_VARIANT @@ -1691,6 +1710,7 @@ fn collect_apply_failures( r.error .clone() .unwrap_or_else(|| "unknown error".to_string()), + r.failure_cause().map(ApplyFailureCause::as_str), ), None => continue, }; @@ -1701,6 +1721,7 @@ fn collect_apply_failures( purl: r.package_key.clone(), code: code.to_string(), error, + cause, }); } if !failures.is_empty() { @@ -1711,6 +1732,7 @@ fn collect_apply_failures( code: "package_not_installed".to_string(), error: not_installed_detail(&purl).to_string(), purl, + cause: None, }); } failures @@ -1961,6 +1983,7 @@ pub(crate) async fn run_locked( lockfile_only, run_warnings, fallback_skips, + unreported, caveats, targeted, show_summary, @@ -2389,7 +2412,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), @@ -2402,7 +2437,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, @@ -2439,11 +2474,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() { @@ -2493,18 +2523,51 @@ 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 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. +/// +/// `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( results: &[ApplyResult], caveats: &GemCaveats, + failures: &[ApplyFailure], + unreported: &[(String, ApplyFailureCause)], 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, 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()) + }) + .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" && !named.contains(f.purl.as_str())) + .map(|f| f.event(&f.purl)), + ) .collect(); crate::telemetry_outcomes::patch_outcomes( &events, @@ -2513,6 +2576,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 @@ -2586,6 +2660,7 @@ fn synthesize_vendor_owned_results( applied_via: HashMap::new(), error: None, sidecar: None, + cause: None, }); matched.insert(purl); } @@ -2635,6 +2710,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. @@ -3227,6 +3306,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, @@ -3269,6 +3349,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, @@ -3343,6 +3424,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(); @@ -3426,6 +3508,7 @@ async fn apply_patches_inner( lockfile_only, run_warnings, fallback_skips, + unreported, caveats: GemCaveats::default(), targeted: target_manifest_purls.len(), show_summary: true, @@ -3539,6 +3622,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 { @@ -3982,6 +4066,14 @@ async fn apply_patches_inner( for (variant_purl, _) in &records { matched_manifest_purls.insert((*variant_purl).to_string()); } + // The result below is keyed by the base purl, which + // names no one record: telemetry names each. + unreported.extend(records.iter().map(|(variant_purl, _)| { + ( + (*variant_purl).to_string(), + ApplyFailureCause::NoMatchingVariant, + ) + })); let path = pkg_path.display().to_string(); caveats.no_variant.push(NoVariantCopy { purl: base_purl.clone(), @@ -3996,6 +4088,7 @@ async fn apply_patches_inner( applied_via: HashMap::new(), error: Some(reason), sidecar: None, + cause: Some(ApplyFailureCause::NoMatchingVariant), }); } } @@ -4145,6 +4238,7 @@ async fn apply_patches_inner( lockfile_only, run_warnings, fallback_skips, + unreported, caveats, targeted: target_manifest_purls.len(), show_summary: true, @@ -4272,12 +4366,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(), @@ -4287,6 +4383,7 @@ impl MavenApplied { applied_via: HashMap::new(), error: Some(format!("{code}: {detail}")), sidecar: None, + cause: Some(ApplyFailureCause::Coded(code)), }); self.warn(code, detail); self.failed = true; @@ -4402,6 +4499,12 @@ async fn apply_maven_base(m: &MavenBase<'_>) -> MavenApplied { ), ); out.failed = true; + out.unreported.extend(variants.iter().map(|v| { + ( + (*v).clone(), + ApplyFailureCause::Coded("gradle_ro_cache_shadows"), + ) + })); } if copies.consumed.is_empty() { if copies.read_only.is_empty() { @@ -4660,6 +4763,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( + variants + .iter() + .map(|v| ((*v).clone(), ApplyFailureCause::NoMatchingVariant)), + ); if args.prints_errors() { eprintln!( "{}", @@ -4742,6 +4850,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); } @@ -5205,6 +5314,7 @@ mod tests { applied_via, error: None, sidecar: None, + cause: None, } } @@ -5257,6 +5367,132 @@ 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::Coded("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-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 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. + #[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] @@ -5321,6 +5557,7 @@ mod tests { applied_via, error: None, sidecar: None, + cause: None, }; let event = result_to_event(&result, false); @@ -5362,6 +5599,7 @@ mod tests { applied_via: HashMap::new(), error: None, sidecar: None, + cause: None, } } @@ -5506,6 +5744,7 @@ mod tests { applied_via, error: None, sidecar: None, + cause: None, }; let event = result_to_event(&result, false); let v: serde_json::Value = @@ -5749,6 +5988,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) = @@ -5976,6 +6216,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)); @@ -6347,6 +6588,7 @@ mod tests { applied_via: HashMap::new(), error: error.map(str::to_string), sidecar: None, + cause: None, } } @@ -6367,11 +6609,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"), }, ] ); @@ -6392,6 +6636,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..dbd6da521 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`, 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 /// 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/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-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..f738bb996 100644 --- a/crates/socket-patch-core/src/patch/apply.rs +++ b/crates/socket-patch-core/src/patch/apply.rs @@ -108,6 +108,70 @@ 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. 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. + 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, + /// 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, +} + +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::Coded(code) => code, + Self::Unclassified => "unclassified", + } + } +} + /// Result of applying patches to a single package. #[derive(Debug, Clone)] pub struct ApplyResult { @@ -133,6 +197,27 @@ pub struct ApplyResult { /// Surfaced in the CLI JSON envelope under /// `Envelope.sidecars[]` (top-level, not per-event). pub sidecar: Option, + /// 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 [`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 { + (!self.success).then(|| self.cause.unwrap_or(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 +1510,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 +1710,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 +1725,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 +1749,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 +1776,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 +1835,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 +1905,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 +1985,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 +2020,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 +2063,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 +2141,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 +2230,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 `unclassified`, + /// whatever its files say; a set cause wins. + #[test] + 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::Unclassified) + ); + assert_eq!( + result_with(false, &[VerifyStatus::NotFound]).failure_cause(), + Some(ApplyFailureCause::Unclassified) + ); + 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::Coded("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 +4821,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..e2cd1c8f7 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -5389,13 +5389,16 @@ fn untouched_result(package_key: &str, pkg_path: &Path, error: Option) - applied_via: HashMap::new(), error, sidecar: None, + cause: None, } } -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)), } } @@ -5520,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) } @@ -5638,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/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/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/rollback.rs b/crates/socket-patch-core/src/patch/rollback.rs index 2742e4f77..d1756e3e6 100644 --- a/crates/socket-patch-core/src/patch/rollback.rs +++ b/crates/socket-patch-core/src/patch/rollback.rs @@ -500,7 +500,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..8650a8e8c 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`. @@ -71,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() { @@ -78,7 +83,6 @@ pub(crate) fn fold(result: &mut R, copy: &Path, mut copy_result: R) _ => return, } } else { - result.mark_failed(); 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..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(), } } @@ -661,6 +667,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 +682,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 +713,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 @@ -2134,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!( [ @@ -2149,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); @@ -2957,11 +2978,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/utils/socket_cli_config.rs b/crates/socket-patch-core/src/utils/socket_cli_config.rs index 3933e8d5a..eb825d1ee 100644 --- a/crates/socket-patch-core/src/utils/socket_cli_config.rs +++ b/crates/socket-patch-core/src/utils/socket_cli_config.rs @@ -67,6 +67,21 @@ pub fn truthy(value: &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") @@ -241,6 +256,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/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, } }