feat(core): removing from a system Python is refused, and a guard trip is not a typo

Three refusals a removal did not have.

**PEP 668.** DATA-FLOW §2's preamble says "all mutating flows", and `UpdateFlow`
has refused externally-managed environments since S1. `UninstallFlow` did not, so
PipDock would strip packages out of a system Python it declines to *upgrade* —
the worse of the two operations, since there is no resolver standing between the
user and the damage.

**The guard was advisory.** `start` returned a `GuardReport` and `execute` ran
the engine; between those two points nothing stopped a caller from not looking.
DATA-FLOW §5's three options are a dialog, and a dialog is not an enforcement
point. `GuardAck` is, and it is a named waiver rather than a `bool` for the
reason `SnapshotProof` is: `execute(true, …)` at a call site says nothing about
what was true.

**PD-RES-004**, because the CLI printed `PD-PKG-002` — "no matching
distribution", the opposite of the truth. Every package involved exists, and that
is exactly why the removal is refused; a user grepping their logs for a typo
would have found this instead. Adding it moves both count assertions (31 → 32),
the `internally_raised` table, both locale catalogs, and three goldens —
`Code` plus the two schemas that embed it.

The exit code goes 1 → 2. CLI-SPEC §5 defines 1 as "completed with per-package
failures (see JSON `counts.failed`)", but a guard trip executes nothing, so a
script following the table reads counts that are not there. 2 is "plan aborted",
which is what happened, and it is what `exit_for` already derives from
`Area::Res` — so the binary stops disagreeing with its own mapping. Both are
non-zero, so CLI-SPEC §7's `|| echo` example is unaffected.

Verified against a real venv: the guard now prints PD-RES-004 and exits 2. The
PEP 668 gate is not reproducible here — the marker lives in the base stdlib, so
planting one would mark the machine's real Python — and it is covered by the unit
test instead, the same reason `classifier_corpus` lists PD-ENV-002 as internally
raised.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-08-09 21:46:25 +07:00
1 parent 8a5a69f14d
commit fc0aa4ccf6
11 files changed
+172 -13

No files matched your search

+17 -6
View File
@@ -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::<Vec<_>>()
.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);
@@ -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.",
@@ -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.",
@@ -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.",
+22 -6
View File
@@ -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(),
+110 -1
View File
@@ -402,9 +402,29 @@ pub struct UninstallFlow {
names: Vec<PkgName>,
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<dyn Engine>,
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<PkgName> = 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<crate::plan::ExecutionSummary> {
pub async fn execute(
&self,
ack: GuardAck,
tx: EventSink,
) -> Result<crate::plan::ExecutionSummary> {
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<SnapshotProof<'_>> {
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<crate::model::Dist> = 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")];
@@ -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",
+1
View File
@@ -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 |
+1
View File
@@ -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'
+1
View File
@@ -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."
+1
View File
@@ -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."