fix(core): a removal is a plan too — lifecycle, cancellation, and the waiver
Three things `execute_uninstall` never did, none of which the CLI could notice. **It emitted no lifecycle markers.** Every line it produced carried `step: 0` and there was no `StepStarted` or `StepFinished` at all. The CLI prints `event.line()` and nothing else, so it looked fine there — but the console drawer groups sections on `StepStarted` and the live region counts `StepFinished`, which is the whole reason the payload became a lifecycle in S3. The GUI would have shown an empty drawer and a counter stuck at zero, against a green suite. **It ignored cancellation.** There was no token check in the loop, so a cancelled removal removed every package and *then* reported `cancelled: true` — a summary that reads correctly over an environment that is gone. Removals are fast, which is exactly why the window matters. Now the remaining names are `Skipped` without the engine being invoked, and one killed mid-flight is `Skipped` rather than `Failed`, matching what the install path already does. **It ignored `--no-snapshot`.** `UninstallFlow::take_snapshot` took no `SnapshotPolicy`, so the flag was parsed and dropped: the same waiver meant "waive" for an update and nothing at all for a removal, the one operation with no way back. `execute_uninstall` now takes a `base` step index, because `execute_rollback` calls it and then installs on top under one sink whose `total` counts both. The restore loop had the same missing markers and started its own indices at zero; both halves now share the space. Its doc comment is restored too — the block was attached to `execute_rollback`, leaving the function with none. `FakeEngine` records `uninstall` calls the way it records installs. Without that, "the engine was not invoked for the packages after the cancel" is a claim no test can make, which is how a loop that ignores the token passes a cancellation test. Verified against a real venv, not only the fakes: a leaf removal writes its snapshot first and reports "1 successful", and `--no-snapshot` now prints the warning and skips it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1c17f6483d
commit
8a5a69f14d
4 files changed
+205
-20
No files matched your search
@@ -1213,8 +1213,21 @@ pub async fn uninstall(opts: &GlobalOpts, pkgs: &[String], force: bool) -> Resul
|
||||
}
|
||||
|
||||
// DATA-FLOW §9.2 applies to removals too: nothing is touched before a snapshot exists.
|
||||
let meta = flow.take_snapshot(&app_data_dir()).await?;
|
||||
if !opts.json {
|
||||
// `--no-snapshot` was parsed and then ignored on this path, so the same flag meant "waive" for
|
||||
// an update and nothing at all for a removal — the one operation with no way back.
|
||||
let policy = if opts.no_snapshot {
|
||||
// CLI-SPEC §2 documents this for CI images only, and requires the warning.
|
||||
eprintln!(
|
||||
"warning: --no-snapshot given. If this goes wrong there is no way back — \
|
||||
only use it on a disposable environment."
|
||||
);
|
||||
SnapshotPolicy::Waive
|
||||
} else {
|
||||
SnapshotPolicy::Take
|
||||
};
|
||||
if let Some(meta) = flow.take_snapshot(policy, &app_data_dir()).await?
|
||||
&& !opts.json
|
||||
{
|
||||
println!("snapshot {} written before removing", meta.id);
|
||||
}
|
||||
|
||||
|
||||
@@ -441,11 +441,25 @@ impl UninstallFlow {
|
||||
))
|
||||
}
|
||||
|
||||
/// Write the pre-removal snapshot.
|
||||
/// Write the pre-removal snapshot, or record the waiver.
|
||||
///
|
||||
/// Takes a [`SnapshotPolicy`] for the same reason [`UpdateFlow::take_snapshot`] does: without
|
||||
/// it the CLI's `--no-snapshot` was accepted, parsed and then silently ignored on this path,
|
||||
/// so a disposable-environment waiver behaved differently depending on which command it was
|
||||
/// given to. `Waive` returns `None` — there is no meta to print, and no id for the summary to
|
||||
/// correlate against.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-SNP-001` when it cannot be written, in which case nothing is removed.
|
||||
pub async fn take_snapshot(&mut self, app_data: &Path) -> Result<snapshot::Meta> {
|
||||
pub async fn take_snapshot(
|
||||
&mut self,
|
||||
policy: SnapshotPolicy,
|
||||
app_data: &Path,
|
||||
) -> Result<Option<snapshot::Meta>> {
|
||||
if matches!(policy, SnapshotPolicy::Waive) {
|
||||
self.snapshot = SnapshotState::Waived;
|
||||
return Ok(None);
|
||||
}
|
||||
let snap = snapshot::create(
|
||||
app_data,
|
||||
&self.env_hash,
|
||||
@@ -458,7 +472,7 @@ impl UninstallFlow {
|
||||
)?;
|
||||
let meta = snap.meta.clone();
|
||||
self.snapshot = SnapshotState::Taken(Box::new(snap));
|
||||
Ok(meta)
|
||||
Ok(Some(meta))
|
||||
}
|
||||
|
||||
/// Remove the packages, sequentially, skip-and-continue.
|
||||
@@ -483,6 +497,9 @@ impl UninstallFlow {
|
||||
&self.names,
|
||||
proof,
|
||||
sink,
|
||||
// The removals are the whole plan here, so they start at step zero. Only a rollback
|
||||
// has anything in front of them.
|
||||
0,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -627,13 +627,6 @@ async fn post_check(engine: &dyn Engine, env: &PyEnv) -> CheckReport {
|
||||
})
|
||||
}
|
||||
|
||||
/// Remove packages, sequentially, skipping past failures (DATA-FLOW §5).
|
||||
///
|
||||
/// The reverse-dependency guard is the caller's job and runs **once against the full set** before
|
||||
/// this is called; by the time execution starts the user has already decided.
|
||||
///
|
||||
/// # Errors
|
||||
/// Never for a package failure — those land in the summary. Only a stale plan aborts.
|
||||
/// Apply a rollback plan: remove what the snapshot does not have, restore what it does.
|
||||
///
|
||||
/// Lives here rather than in a head because it is the mutating half of DATA-FLOW §8, and a
|
||||
@@ -657,6 +650,9 @@ pub async fn execute_rollback(
|
||||
) -> Result<ExecutionSummary> {
|
||||
let mut results = Vec::new();
|
||||
|
||||
// One index space across both halves: the sink's `total` counts the removals and the restores
|
||||
// together, so the restores continue where the removals stopped rather than both starting at
|
||||
// zero and the live region counting to half.
|
||||
if !restore.uninstall.is_empty() {
|
||||
let removed = execute_uninstall(
|
||||
engine,
|
||||
@@ -665,28 +661,34 @@ pub async fn execute_rollback(
|
||||
&restore.uninstall,
|
||||
snapshot,
|
||||
sink.clone(),
|
||||
0,
|
||||
)
|
||||
.await?;
|
||||
results.extend(removed.results);
|
||||
}
|
||||
|
||||
for spec in &restore.install {
|
||||
for (index, spec) in restore.install.iter().enumerate() {
|
||||
let step_sink = sink.at(restore.uninstall.len() + index);
|
||||
step_sink.started(Some(spec.name.clone()), ExecMode::Isolated);
|
||||
|
||||
let step = engine
|
||||
.install(
|
||||
env,
|
||||
std::slice::from_ref(spec),
|
||||
ExecMode::Isolated,
|
||||
sink.clone(),
|
||||
step_sink.clone(),
|
||||
)
|
||||
.await;
|
||||
results.push(step.unwrap_or_else(|e| StepResult {
|
||||
let result = step.unwrap_or_else(|e| StepResult {
|
||||
pkg: spec.name.clone(),
|
||||
from: None,
|
||||
to: Some(spec.version.clone()),
|
||||
status: StepStatus::Failed,
|
||||
code: Some(e.code),
|
||||
stderr_tail: e.stderr_tail,
|
||||
}));
|
||||
});
|
||||
step_sink.finished(Some(spec.name.clone()), ExecMode::Isolated, result.status);
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
let counts = ExecutionSummary::tally(&results);
|
||||
@@ -700,6 +702,19 @@ pub async fn execute_rollback(
|
||||
})
|
||||
}
|
||||
|
||||
/// Remove packages, sequentially, skipping past failures (DATA-FLOW §5).
|
||||
///
|
||||
/// The reverse-dependency guard is the caller's job and runs **once against the full set** before
|
||||
/// this is called; by the time execution starts the user has already decided.
|
||||
///
|
||||
/// `base` is where this run's steps begin in the sink's index space. It exists because
|
||||
/// [`execute_rollback`] calls this for the removal half of a restore and then installs on top,
|
||||
/// under **one** `ProgressSink` whose `total` counts both — so the removals are steps
|
||||
/// `base..base+names.len()` and the restores continue from there. Passing `0` is right for a plain
|
||||
/// uninstall, where the removals are the whole plan.
|
||||
///
|
||||
/// # Errors
|
||||
/// Never for a package failure — those land in the summary. Only a stale plan aborts.
|
||||
pub async fn execute_uninstall(
|
||||
engine: &dyn Engine,
|
||||
env: &PyEnv,
|
||||
@@ -707,13 +722,53 @@ pub async fn execute_uninstall(
|
||||
names: &[PkgName],
|
||||
_snapshot: SnapshotProof<'_>,
|
||||
sink: ProgressSink,
|
||||
base: usize,
|
||||
) -> Result<ExecutionSummary> {
|
||||
let mut results = Vec::with_capacity(names.len());
|
||||
for name in names {
|
||||
for (index, name) in names.iter().enumerate() {
|
||||
// Checked before each removal, so a cancelled run reports the rest as never attempted
|
||||
// instead of removing them and then admitting it was cancelled. Removals are fast, which
|
||||
// is exactly why the window matters: without this the whole set goes.
|
||||
if sink.is_cancelled() {
|
||||
results.extend(names[index..].iter().map(|remaining| StepResult {
|
||||
pkg: remaining.clone(),
|
||||
from: None,
|
||||
to: None,
|
||||
status: StepStatus::Skipped,
|
||||
code: None,
|
||||
stderr_tail: None,
|
||||
}));
|
||||
break;
|
||||
}
|
||||
|
||||
// A removal used to emit neither marker, and every line it produced carried `step: 0`.
|
||||
// The CLI never noticed because it prints `event.line()` and nothing else, but the console
|
||||
// drawer groups on `StepStarted` and the live region counts `StepFinished` — both were
|
||||
// unimplementable for uninstall, and would have rendered an empty drawer against a green
|
||||
// suite.
|
||||
let step_sink = sink.at(base + index);
|
||||
step_sink.started(Some(name.clone()), ExecMode::Isolated);
|
||||
|
||||
let step = engine
|
||||
.uninstall(env, std::slice::from_ref(name), sink.clone())
|
||||
.uninstall(env, std::slice::from_ref(name), step_sink.clone())
|
||||
.await;
|
||||
results.push(match step {
|
||||
|
||||
// Killed by us is not the package's failure — the same reclassification the install path
|
||||
// makes, and for the same reason: it was not attempted to completion.
|
||||
if sink.is_cancelled() && step.is_err() {
|
||||
step_sink.finished(Some(name.clone()), ExecMode::Isolated, StepStatus::Skipped);
|
||||
results.push(StepResult {
|
||||
pkg: name.clone(),
|
||||
from: None,
|
||||
to: None,
|
||||
status: StepStatus::Skipped,
|
||||
code: None,
|
||||
stderr_tail: None,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
let result = match step {
|
||||
Ok(r) => r,
|
||||
Err(e) => StepResult {
|
||||
pkg: name.clone(),
|
||||
@@ -723,7 +778,9 @@ pub async fn execute_uninstall(
|
||||
code: Some(e.code),
|
||||
stderr_tail: e.stderr_tail,
|
||||
},
|
||||
});
|
||||
};
|
||||
step_sink.finished(Some(name.clone()), ExecMode::Isolated, result.status);
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
let counts = ExecutionSummary::tally(&results);
|
||||
|
||||
@@ -126,6 +126,14 @@ impl Engine for FakeEngine {
|
||||
names: &[PkgName],
|
||||
_sink: ProgressSink,
|
||||
) -> Result<StepResult> {
|
||||
// Recorded like installs are. Without this, "the engine was not invoked for the packages
|
||||
// after the cancel" is a claim no test can make — and a removal loop that ignores the
|
||||
// token still produces a summary that says `cancelled`.
|
||||
self.calls.lock().unwrap_or_else(|e| e.into_inner()).push((
|
||||
names.iter().map(ToString::to_string).collect(),
|
||||
ExecMode::Isolated,
|
||||
));
|
||||
|
||||
let pkg = names
|
||||
.first()
|
||||
.cloned()
|
||||
@@ -552,3 +560,93 @@ async fn an_uncancelled_run_does_not_claim_it_was_cancelled() {
|
||||
let summary = run(&FakeEngine::new(&[]), &[("alpha", "1.0")]).await;
|
||||
assert!(!summary.cancelled);
|
||||
}
|
||||
|
||||
/// Remove `names`, collecting every event, with `token` deciding whether it is cancelled.
|
||||
async fn remove_collecting(
|
||||
engine: &FakeEngine,
|
||||
names: &[&str],
|
||||
token: tokio_util::sync::CancellationToken,
|
||||
) -> (ExecutionSummary, Vec<ProgressEvent>) {
|
||||
let dir = scratch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let snap = snapshot_for(&dir);
|
||||
let parsed: Vec<PkgName> = names.iter().map(|n| PkgName::parse(n).unwrap()).collect();
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let summary = pipdock_core::plan::execute_uninstall(
|
||||
engine,
|
||||
&env(),
|
||||
"uninstall-envhash".to_owned(),
|
||||
&parsed,
|
||||
SnapshotProof::Taken(&snap),
|
||||
ProgressSink::new(tx, parsed.len(), token),
|
||||
0,
|
||||
)
|
||||
.await
|
||||
.expect("execute_uninstall");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
let mut events = Vec::new();
|
||||
while let Some(e) = rx.recv().await {
|
||||
events.push(e);
|
||||
}
|
||||
(summary, events)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_removal_opens_and_closes_a_step_per_package() {
|
||||
// Removals emitted neither marker and every line they produced carried `step: 0`. The CLI
|
||||
// never noticed, because it prints `event.line()` and nothing else — but the console drawer
|
||||
// groups on StepStarted and the live region counts StepFinished, so the GUI would have shown
|
||||
// an empty drawer and a counter stuck at zero, against a fully green suite.
|
||||
let engine = FakeEngine::new(&["locked"]);
|
||||
let (summary, events) = remove_collecting(
|
||||
&engine,
|
||||
&["alpha", "locked", "gamma"],
|
||||
tokio_util::sync::CancellationToken::new(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let started: Vec<usize> = events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
ProgressEvent::StepStarted { step, .. } => Some(*step),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let finished: Vec<usize> = events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
ProgressEvent::StepFinished { step, .. } => Some(*step),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert_eq!(started, [0, 1, 2], "one open per package, in order");
|
||||
assert_eq!(finished, [0, 1, 2], "and one close each, however it ended");
|
||||
assert_eq!(summary.counts.ok, 2);
|
||||
assert_eq!(
|
||||
summary.counts.failed, 1,
|
||||
"a locked file is still that package's failure"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_cancelled_removal_leaves_the_rest_installed() {
|
||||
// The dangerous shape: the loop had no token check at all, so a cancel removed every package
|
||||
// and *then* reported `cancelled: true`. The summary looked right and the environment was
|
||||
// gone. Removals are fast, which is exactly why the window matters.
|
||||
let engine = FakeEngine::new(&[]);
|
||||
let token = tokio_util::sync::CancellationToken::new();
|
||||
token.cancel();
|
||||
let (summary, _) = remove_collecting(&engine, &["alpha", "beta", "gamma"], token).await;
|
||||
|
||||
assert!(summary.cancelled);
|
||||
assert_eq!(summary.counts.skipped, 3, "{:?}", summary.results);
|
||||
assert_eq!(summary.counts.ok, 0);
|
||||
assert!(
|
||||
engine.calls().is_empty(),
|
||||
"the engine must not have been invoked at all: {:?}",
|
||||
engine.calls()
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user