diff --git a/crates/pipdock-cli/src/run.rs b/crates/pipdock-cli/src/run.rs index 5d87092..390a2db 100644 --- a/crates/pipdock-cli/src/run.rs +++ b/crates/pipdock-cli/src/run.rs @@ -11,7 +11,7 @@ use pipdock_core::engine::{self, Engine, ProgressEvent, pip::PipEngine, uv::UvEn use pipdock_core::envs::{self, Candidate}; use pipdock_core::errors::{Code, PdError, Result}; use pipdock_core::flow::{ - FlowStep, NothingReason, RollbackFlow, SnapshotPolicy, UninstallFlow, UpdateFlow, + FlowStep, GuardAck, NothingReason, RollbackFlow, SnapshotPolicy, UninstallFlow, UpdateFlow, }; use pipdock_core::model::{EngineId, EnvSource, PkgName, PyEnv, StepStatus}; @@ -1195,9 +1195,10 @@ pub async fn uninstall(opts: &GlobalOpts, pkgs: &[String], force: bool) -> Resul } if !force { eprintln!( - "error[PD-PKG-002]: refusing to remove packages other packages depend on.\n\ + "error[{}]: refusing to remove packages other packages depend on.\n\ Re-run with --force to proceed anyway, or add the dependents to the removal set:\n\ pipdock uninstall {}", + Code::ResGuardTrip, report .with_dependents .iter() @@ -1205,9 +1206,12 @@ pub async fn uninstall(opts: &GlobalOpts, pkgs: &[String], force: bool) -> Resul .collect::>() .join(" ") ); - // CLI-SPEC §7 documents this as exit 1 ("exit 1 if guard trips"), so scripts can use - // `||` without matching a specific code. - return Ok(Exit::PartialFailure); + // Exit 2, not 1. CLI-SPEC §5 defines 1 as "completed with per-package failures (see + // JSON `counts.failed`)" — but a guard trip executes nothing, so there are no counts + // to read and a script following the table finds an empty summary. 2 is "plan + // aborted", which is exactly what happened. It is also what `exit_for` derives from + // `Area::Res`, so the binary no longer disagrees with its own mapping. + return Ok(Exit::PlanAborted); } eprintln!("warning: --force given; proceeding despite the breakage above"); } @@ -1244,7 +1248,14 @@ pub async fn uninstall(opts: &GlobalOpts, pkgs: &[String], force: bool) -> Resul } }); - let summary = flow.execute(tx).await?; + // Reaching here means either the guard was clear or `--force` was given and the warning + // printed; `ack_ok` refuses anything else with PD-RES-004 rather than trusting this call site. + let ack = if force { + GuardAck::ForcedDespiteBreakage + } else { + GuardAck::Clear + }; + let summary = flow.execute(ack, tx).await?; drop(pump); print_summary(opts, &summary); diff --git a/crates/pipdock-cli/tests/snapshots/golden__schema-Code.snap b/crates/pipdock-cli/tests/snapshots/golden__schema-Code.snap index 72b4595..3f31cf3 100644 --- a/crates/pipdock-cli/tests/snapshots/golden__schema-Code.snap +++ b/crates/pipdock-cli/tests/snapshots/golden__schema-Code.snap @@ -56,6 +56,11 @@ expression: out "description": "A plan is already resolving or executing in this session.\n\nThe GUI drives one resumable flow across several IPC calls, so \"start a plan\" and \"run the\nplan\" are different messages arriving at different times — nothing structurally stops a\nsecond one arriving in between. Refusing is the only safe answer: two concurrent plans\nwould interleave engine commands against one environment, and DATA-FLOW §9.3's staleness\ncheck would be comparing against a set the other plan is busy changing.", "type": "string" }, + { + "const": "PD-RES-004", + "description": "A removal was asked for that the reverse-dependency guard refused (DATA-FLOW §5).\n\nIts own code rather than a reused one. The CLI printed `PD-PKG-002` here, which means \"no\nmatching distribution\" — the opposite of the truth: every package involved exists, and\nthat is precisely why the removal is being refused. A user grepping their logs for a typo\nwould have found this instead.\n\nNot raised when the guard merely *finds* dependents. That is a report the caller shows and\nthe user answers; the code appears only when execution is attempted anyway without the\nuser having accepted the breakage.", + "type": "string" + }, { "const": "PD-BLD-001", "description": "MSVC build tools required but absent.", diff --git a/crates/pipdock-cli/tests/snapshots/golden__schema-ExecutionSummary.snap b/crates/pipdock-cli/tests/snapshots/golden__schema-ExecutionSummary.snap index 0d173c2..af9b63a 100644 --- a/crates/pipdock-cli/tests/snapshots/golden__schema-ExecutionSummary.snap +++ b/crates/pipdock-cli/tests/snapshots/golden__schema-ExecutionSummary.snap @@ -96,6 +96,11 @@ expression: out "description": "A plan is already resolving or executing in this session.\n\nThe GUI drives one resumable flow across several IPC calls, so \"start a plan\" and \"run the\nplan\" are different messages arriving at different times — nothing structurally stops a\nsecond one arriving in between. Refusing is the only safe answer: two concurrent plans\nwould interleave engine commands against one environment, and DATA-FLOW §9.3's staleness\ncheck would be comparing against a set the other plan is busy changing.", "type": "string" }, + { + "const": "PD-RES-004", + "description": "A removal was asked for that the reverse-dependency guard refused (DATA-FLOW §5).\n\nIts own code rather than a reused one. The CLI printed `PD-PKG-002` here, which means \"no\nmatching distribution\" — the opposite of the truth: every package involved exists, and\nthat is precisely why the removal is being refused. A user grepping their logs for a typo\nwould have found this instead.\n\nNot raised when the guard merely *finds* dependents. That is a report the caller shows and\nthe user answers; the code appears only when execution is attempted anyway without the\nuser having accepted the breakage.", + "type": "string" + }, { "const": "PD-BLD-001", "description": "MSVC build tools required but absent.", diff --git a/crates/pipdock-cli/tests/snapshots/golden__schema-StepResult.snap b/crates/pipdock-cli/tests/snapshots/golden__schema-StepResult.snap index 354bb87..a10a7f1 100644 --- a/crates/pipdock-cli/tests/snapshots/golden__schema-StepResult.snap +++ b/crates/pipdock-cli/tests/snapshots/golden__schema-StepResult.snap @@ -57,6 +57,11 @@ expression: out "description": "A plan is already resolving or executing in this session.\n\nThe GUI drives one resumable flow across several IPC calls, so \"start a plan\" and \"run the\nplan\" are different messages arriving at different times — nothing structurally stops a\nsecond one arriving in between. Refusing is the only safe answer: two concurrent plans\nwould interleave engine commands against one environment, and DATA-FLOW §9.3's staleness\ncheck would be comparing against a set the other plan is busy changing.", "type": "string" }, + { + "const": "PD-RES-004", + "description": "A removal was asked for that the reverse-dependency guard refused (DATA-FLOW §5).\n\nIts own code rather than a reused one. The CLI printed `PD-PKG-002` here, which means \"no\nmatching distribution\" — the opposite of the truth: every package involved exists, and\nthat is precisely why the removal is being refused. A user grepping their logs for a typo\nwould have found this instead.\n\nNot raised when the guard merely *finds* dependents. That is a report the caller shows and\nthe user answers; the code appears only when execution is attempted anyway without the\nuser having accepted the breakage.", + "type": "string" + }, { "const": "PD-BLD-001", "description": "MSVC build tools required but absent.", diff --git a/crates/pipdock-core/src/errors/catalog.rs b/crates/pipdock-core/src/errors/catalog.rs index 66f3fa9..763f6e3 100644 --- a/crates/pipdock-core/src/errors/catalog.rs +++ b/crates/pipdock-core/src/errors/catalog.rs @@ -108,6 +108,18 @@ pub enum Code { /// check would be comparing against a set the other plan is busy changing. #[serde(rename = "PD-RES-003")] ResPlanInFlight, + /// A removal was asked for that the reverse-dependency guard refused (DATA-FLOW §5). + /// + /// Its own code rather than a reused one. The CLI printed `PD-PKG-002` here, which means "no + /// matching distribution" — the opposite of the truth: every package involved exists, and + /// that is precisely why the removal is being refused. A user grepping their logs for a typo + /// would have found this instead. + /// + /// Not raised when the guard merely *finds* dependents. That is a report the caller shows and + /// the user answers; the code appears only when execution is attempted anyway without the + /// user having accepted the breakage. + #[serde(rename = "PD-RES-004")] + ResGuardTrip, // -- PD-BLD: build ------------------------------------------------------ /// MSVC build tools required but absent. @@ -205,6 +217,7 @@ impl Code { Self::ResImpossible => "PD-RES-001", Self::ResPlanStale => "PD-RES-002", Self::ResPlanInFlight => "PD-RES-003", + Self::ResGuardTrip => "PD-RES-004", Self::BldMsvcMissing => "PD-BLD-001", Self::BldBackendFailed => "PD-BLD-002", Self::BldWheelFailed => "PD-BLD-003", @@ -240,7 +253,10 @@ impl Code { | Self::EngPipTooOld | Self::EngUvShapeUnknown | Self::EngUnclassified => Area::Eng, - Self::ResImpossible | Self::ResPlanStale | Self::ResPlanInFlight => Area::Res, + Self::ResImpossible + | Self::ResPlanStale + | Self::ResPlanInFlight + | Self::ResGuardTrip => Area::Res, Self::BldMsvcMissing | Self::BldBackendFailed | Self::BldWheelFailed => Area::Bld, Self::PkgRequiresPython | Self::PkgNotFound @@ -270,6 +286,7 @@ impl Code { Self::ResImpossible, Self::ResPlanStale, Self::ResPlanInFlight, + Self::ResGuardTrip, Self::BldMsvcMissing, Self::BldBackendFailed, Self::BldWheelFailed, @@ -546,7 +563,7 @@ mod tests { fn every_variant_is_listed_in_all() { // `ALL` drives the fixture-coverage gate, so a variant missing from it would silently // escape that gate. There is no derive for "enumerate variants", hence this count check. - assert_eq!(Code::ALL.len(), 31, "add the new variant to Code::ALL"); + assert_eq!(Code::ALL.len(), 32, "add the new variant to Code::ALL"); } #[test] @@ -693,10 +710,9 @@ mod tests { #[test] fn every_documented_code_has_exactly_one_variant() { - // Rust has 30, docs/ERROR-CATALOG.md tabulates 28 (it folds PD-HLT-001..003 into one - // row) and CLAUDE.md used to say 25. Pin the number so the next person adding a code has - // to notice the docs exist. - assert_eq!(Code::ALL.len(), 31); + // Rust has 32; docs/ERROR-CATALOG.md tabulates 30, because it folds PD-HLT-001..003 into + // one row. Pin the number so the next person adding a code has to notice the docs exist. + assert_eq!(Code::ALL.len(), 32); let wire: HashSet<&str> = Code::ALL.iter().map(|c| c.as_str()).collect(); assert_eq!( wire.len(), diff --git a/crates/pipdock-core/src/flow/mod.rs b/crates/pipdock-core/src/flow/mod.rs index 34bcc9a..e7f7b13 100644 --- a/crates/pipdock-core/src/flow/mod.rs +++ b/crates/pipdock-core/src/flow/mod.rs @@ -402,9 +402,29 @@ pub struct UninstallFlow { names: Vec, plan_id: String, snapshot: SnapshotState, + /// What the guard found, kept so [`Self::execute`] can refuse a removal the user never + /// accepted. Returned to the caller as well, because the caller is what renders it. + guard: crate::graph::GuardReport, cancel: CancellationToken, } +/// Whether the user has accepted the breakage the guard found (DATA-FLOW §5). +/// +/// A separate argument to [`UninstallFlow::execute`] rather than a `bool` on the flow, for the +/// reason [`SnapshotProof`] is a named waiver: `execute(true, …)` at a call site says nothing +/// about what was true, and the one thing this type exists to prevent is a removal proceeding +/// because somebody forgot to look at the report. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GuardAck { + /// The guard found nothing, or the caller believes it did. + /// + /// Not a claim the caller gets to make freely: if the guard *did* find dependents this is + /// refused with `PD-RES-004`, which is the whole point. + Clear, + /// The user was shown what breaks and chose to remove anyway — §5's *Force remove only X*. + ForcedDespiteBreakage, +} + impl UninstallFlow { /// Parse the names, probe, and run the reverse-dependency guard. /// @@ -415,6 +435,18 @@ impl UninstallFlow { engine: Box, pkgs: &[String], ) -> Result<(Self, crate::graph::GuardReport)> { + // DATA-FLOW §2's preamble is "all mutating flows", and a removal is one. `UpdateFlow` has + // refused these since S1 and this did not, so PipDock would happily strip packages out of + // a system Python it declines to *upgrade* — the worse of the two operations, since there + // is no resolver between the user and the damage. + if env.externally_managed { + return Err(PdError::new( + Code::EnvExternallyManaged, + "this Python is externally managed (PEP 668). Use a virtual environment; \ + the override lives in Settings and is discouraged", + )); + } + let names: Vec = pkgs .iter() .map(|p| PkgName::parse(p)) @@ -435,12 +467,19 @@ impl UninstallFlow { names, plan_id, snapshot: SnapshotState::NotTaken, + guard: report.clone(), cancel: CancellationToken::new(), }, report, )) } + /// What the guard found when this flow started. + #[must_use] + pub const fn guard(&self) -> &crate::graph::GuardReport { + &self.guard + } + /// Write the pre-removal snapshot, or record the waiver. /// /// Takes a [`SnapshotPolicy`] for the same reason [`UpdateFlow::take_snapshot`] does: without @@ -478,9 +517,15 @@ impl UninstallFlow { /// Remove the packages, sequentially, skip-and-continue. /// /// # Errors + /// `PD-RES-004` when the guard found dependents and `ack` does not accept breaking them; /// `PD-SNP-001` when [`Self::take_snapshot`] has not run. Per-package failures appear in the /// summary rather than as errors. - pub async fn execute(&self, tx: EventSink) -> Result { + pub async fn execute( + &self, + ack: GuardAck, + tx: EventSink, + ) -> Result { + ack_ok(&self.guard, ack)?; let proof = proof_from(&self.snapshot)?; let sink = ProgressSink::new(tx, self.names.len(), self.cancel.clone()); // The summary is correlated by the *snapshot* id here, not `plan_id`. That is what the @@ -654,6 +699,25 @@ impl RollbackFlow { /// execute call is what let the CLI keep printing the snapshot id before execution starts, but it /// also created a way to skip the snapshot by forgetting. `SnapshotProof` makes that impossible /// to express inside one function; across two, this is the guard. +/// The guard's half of DATA-FLOW §9.1, or the refusal. +/// +/// Beside [`proof_from`] and for the same reason. The guard report is produced by `start` and +/// rendered by the caller, and between those two points nothing stopped a caller from simply +/// running the removal — DATA-FLOW §5's three options are a *dialog*, and a dialog is not an +/// enforcement point. This is. +fn ack_ok(report: &crate::graph::GuardReport, ack: GuardAck) -> Result<()> { + if report.is_clear() || matches!(ack, GuardAck::ForcedDespiteBreakage) { + return Ok(()); + } + Err(PdError::new( + Code::ResGuardTrip, + format!( + "removing this would break {} installed package(s); nothing was removed", + report.all_broken().len() + ), + )) +} + fn proof_from(state: &SnapshotState) -> Result> { match state { SnapshotState::Taken(snap) => Ok(SnapshotProof::Taken(snap)), @@ -876,6 +940,51 @@ mod tests { )); } + /// The guard's own report, with `broken` dependents of `pkg`. + fn guard_over(pkg: &str, broken: &[&str]) -> crate::graph::GuardReport { + let name = |n: &str| PkgName::parse(n).expect("test name"); + let dists: Vec = std::iter::once(crate::model::Dist { + name: name(pkg), + version: Version("1.0".to_owned()), + requires_dist: Vec::new(), + requires_python: None, + size_bytes: None, + }) + .chain(broken.iter().map(|d| crate::model::Dist { + name: name(d), + version: Version("2.0".to_owned()), + requires_dist: vec![format!("{pkg}>=1")], + requires_python: None, + size_bytes: None, + })) + .collect(); + ReverseDeps::build(&dists).guard(&[name(pkg)]) + } + + #[test] + fn a_removal_that_breaks_something_is_refused_unless_it_was_accepted() { + // The dialog in DATA-FLOW §5 is where the user answers, but a dialog is not an + // enforcement point: between `start` returning the report and `execute` running the + // engine, nothing stopped a caller from simply not looking. This is the same guard + // `proof_from` is for the snapshot half. + let breaking = guard_over("x", &["y"]); + assert!(!breaking.is_clear()); + + let err = ack_ok(&breaking, GuardAck::Clear).expect_err("must refuse"); + assert_eq!(err.code, Code::ResGuardTrip); + assert!( + err.message.contains("nothing was removed"), + "the message must say the environment is untouched: {}", + err.message + ); + + // The user was shown what breaks and chose it anyway — §5's *Force remove only X*. + assert!(ack_ok(&breaking, GuardAck::ForcedDespiteBreakage).is_ok()); + + // A clear guard needs no acknowledgement, or every plain removal would demand a force. + assert!(ack_ok(&guard_over("x", &[]), GuardAck::Clear).is_ok()); + } + #[test] fn force_latest_reaches_the_request() { let out = [outdated("idna", "3.4", "3.10")]; diff --git a/crates/pipdock-core/tests/classifier_corpus.rs b/crates/pipdock-core/tests/classifier_corpus.rs index 3246587..ffdfeb4 100644 --- a/crates/pipdock-core/tests/classifier_corpus.rs +++ b/crates/pipdock-core/tests/classifier_corpus.rs @@ -145,6 +145,10 @@ fn no_code_without_a_fixture() { "PD-RES-003", "app::state: a second plan arrived while one was already in flight", ), + ( + "PD-RES-004", + "flow: the uninstall guard found dependents the user had not accepted breaking", + ), ( "PD-PKG-001", "compat: Requires-Python enforced by PipDock, not by the engine", diff --git a/docs/ERROR-CATALOG.md b/docs/ERROR-CATALOG.md index 621a13d..e223941 100644 --- a/docs/ERROR-CATALOG.md +++ b/docs/ERROR-CATALOG.md @@ -19,6 +19,7 @@ | PD-RES-001 | `ResolutionImpossible` / uv equivalent | constraints cannot be satisfied | Per-package Skip/Force choices in the preview | | PD-RES-002 | plan stale (>10 min) or env drift hash mismatch | env changed since preview | Re-run preview | | PD-RES-003 | a plan is already resolving or executing | another plan is in flight in this session | Wait for it, or cancel it | +| PD-RES-004 | **Raised by PipDock before the engine runs** — the reverse-dependency guard (DATA-FLOW §5) found installed dependents and execution was attempted without the user accepting the breakage | removing these packages would break others | Remove the dependents too, or force the removal knowingly | | PD-BLD-001 | `Microsoft Visual C++ 14.0 or greater is required` | missing MSVC build tools | Install VS Build Tools, or prefer a wheel-providing version | | PD-BLD-002 | `error in pyproject.toml` / `Backend … failed` / `metadata-generation-failed` | broken sdist build backend | Try previous version; report upstream (owner's example case) | | PD-BLD-003 | `error: Microsoft Visual C++`-absent + `Failed building wheel` generic | sdist-only build failed | Same as above; details in log | diff --git a/ui/src/ipc/generated.ts b/ui/src/ipc/generated.ts index 4ea08e5..68a2d39 100644 --- a/ui/src/ipc/generated.ts +++ b/ui/src/ipc/generated.ts @@ -104,6 +104,7 @@ export type Code = | 'PD-RES-001' | 'PD-RES-002' | 'PD-RES-003' + | 'PD-RES-004' | 'PD-BLD-001' | 'PD-BLD-002' | 'PD-BLD-003' diff --git a/ui/src/locales/en/common.json b/ui/src/locales/en/common.json index 0e42f3d..d0511ea 100644 --- a/ui/src/locales/en/common.json +++ b/ui/src/locales/en/common.json @@ -213,6 +213,7 @@ "PD-ENV-002": "This Python is managed by the operating system.", "PD-ENV-003": "PipDock could not read this environment.", "PD-RES-003": "A plan is already running. Wait for it to finish, or stop it first.", + "PD-RES-004": "Other installed packages depend on these, so nothing was removed.", "PD-SNP-001": "The snapshot could not be written, so nothing was changed.", "PD-INT-001": "PipDock hit an internal error.", "unknown": "An unexpected error occurred." diff --git a/ui/src/locales/vi/common.json b/ui/src/locales/vi/common.json index 8851b35..9fef446 100644 --- a/ui/src/locales/vi/common.json +++ b/ui/src/locales/vi/common.json @@ -205,6 +205,7 @@ "PD-ENV-002": "Bản Python này do hệ điều hành quản lý.", "PD-ENV-003": "PipDock không đọc được môi trường này.", "PD-RES-003": "Đang có một kế hoạch chạy dở. Hãy đợi nó xong, hoặc dừng nó trước.", + "PD-RES-004": "Có gói khác đang phụ thuộc vào những gói này, nên chưa gỡ gì cả.", "PD-SNP-001": "Không ghi được ảnh chụp, nên không có gì bị thay đổi.", "PD-INT-001": "PipDock gặp lỗi nội bộ.", "unknown": "Đã xảy ra lỗi ngoài dự kiến."