Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(install): neue venv direkt unter dem Zielnamen bauen statt hineinzubenennen (B9)

purplee4ca07b4049e
diff --git a/src-tauri/src/commands/install/comfy_repair.rs b/src-tauri/src/commands/install/comfy_repair.rs
index 50995570..ca3f47f3 100644
--- a/src-tauri/src/commands/install/comfy_repair.rs
+++ b/src-tauri/src/commands/install/comfy_repair.rs
@@ -27,7 +27,7 @@ use std::sync::atomic::Ordering;
use std::os::windows::process::CommandExt;
use tauri::State;
-use tracing::{error, info, warn};
+use tracing::{error, info};
use crate::state::AppState;
use crate::os_error;
@@ -40,7 +40,10 @@ use super::comfy_job::{ComfyJob, COMFY_JOB};
use super::comfy_job::comfy_job_busy_message;
use super::pip::pip_install_streaming_with_retry_cancellable;
use super::torch::plan_pytorch_install;
-use super::venv::{create_comfyui_venv_named, detect_venv_passengers, staging_venv_name, sweep_retired_venvs, swap_in_new_venv};
+use super::venv::{
+ create_comfyui_venv, detect_venv_passengers, finish_rebuild, restore_after_failed_rebuild,
+ restore_orphaned_venv_if_needed, retire_for_rebuild,
+};
#[cfg(target_os = "windows")]
use super::git::{windows_git_install_hint, windows_git_probe, WindowsGitState};
#[cfg(target_os = "windows")]
@@ -148,6 +151,13 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
// log line and the line the finished run leaves behind agree (A15).
let mut requirements_fallback: Option<(String, &'static str)> = None;
+ // Runde 6, B9 "Wiederanlauf": before ANYTHING else touches this
+ // folder, recover from a rebuild that died between retiring the old
+ // venv and the new one passing verification (crash, power loss, the
+ // app being killed). A healthy environment sees no difference at
+ // all: this is a no-op the moment a usable `venv` already exists.
+ restore_orphaned_venv_if_needed(&comfy_dir);
+
// A16 (A15-2): before anything is deleted and before anything is
// downloaded. A folder with no requirements.txt is not a ComfyUI
// checkout, and nothing later in this run can change that, so there is
@@ -169,10 +179,23 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
return;
}
- // The rebuild puts about two gigabytes back, and the old venv is now
- // deleted alongside that instead of before it, so the drive gets less
- // slack than it used to. Say so before the work starts, exactly as the
- // installer does; a warning is not a refusal.
+ let venv_dir = comfy_dir.join("venv");
+
+ // Runde 6, B9: the old venv and the new one now BOTH sit on disk at
+ // the same time, from the moment the old one is retired until it is
+ // swept away in the background after the new one passes
+ // verification. The flat 5 GB estimate below never accounted for
+ // that second copy; this one does, and it REFUSES rather than warns,
+ // before anything is touched, so a drive that genuinely cannot hold
+ // both says so up front instead of failing minutes into the PyTorch
+ // download with the old venv already gone.
+ if let Some(msg) = check_repair_disk_pressure(&comfy_dir, &venv_dir) {
+ update("error", &msg);
+ return;
+ }
+ // The generic warning (soft, not a refusal) the installer also
+ // shows, kept for the same reason it always was: room for
+ // everything ELSE a repair downloads besides the venv itself.
if let Some(warning) = super::comfy_install::check_install_disk_pressure(&comfy_dir) {
update("installing", &warning);
}
@@ -209,27 +232,22 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
}
};
- // Runde 5, B7(c) (review Runde 4, Abschnitt 2, Nachbesserung 3 aus
- // Runde 3, still open): the old venv used to be retired BEFORE the
- // new one was built, so a failure anywhere in the build (torch
- // install, or `python -m venv` itself against an interpreter that
- // LOOKED right but could not actually build one) left the customer
- // with neither a working old venv nor a working new one. The new
- // venv is now built under a STAGING name, a sibling of `venv` that
- // nothing else (the launcher, autostart, `comfy_venv_state`,
- // `detect_venv_passengers`) ever looks at, so the OLD `venv` is not
- // touched at all until the new one is fully built, has its
- // dependencies, and has PASSED `verify_and_heal_environment`. Only
- // then are the two swapped. Any failure before that point cleans up
- // the half-built staging folder and returns with the old venv
- // completely untouched, and says so.
- let venv_dir = comfy_dir.join("venv");
- let staging_name = staging_venv_name();
- let staging_dir = comfy_dir.join(&staging_name);
+ // Runde 6, BLOCKER B9 (review Runde 5): Runde 5's build-then-swap
+ // built the new venv under a staging name and renamed the folder
+ // into place afterwards. A venv is not relocatable: every console
+ // script's shebang, `pip`'s own launcher, and every activate script
+ // bake in the ABSOLUTE path it was BUILT at, so that rename left
+ // `venv/bin/pip` and every other script pointing at a staging folder
+ // that no longer existed. See `venv::retire_for_rebuild`'s doc for
+ // the measured proof. The fix: the OLD venv is retired (renamed
+ // aside, reversibly (reversible because restoring it uses the EXACT
+ // same name it already had) FIRST, and the NEW venv is then built
+ // DIRECTLY under the final `venv` name via `create_comfyui_venv`, so
+ // its build path and its resting path are the same string from the
+ // very first `python -m venv` call. Never renamed again afterwards.
+ //
// OI-3: faster-whisper and Piper live in the OLD venv too. Read
- // BEFORE it is touched (it still is not, at this point), since the
- // whole point of the staging approach is that it stays readable
- // until the swap.
+ // BEFORE it is touched (it still is not, at this point).
let passengers = detect_venv_passengers(&venv_dir);
if !passengers.is_empty() {
let names: Vec<&str> = passengers.iter().map(|p| p.label).collect();
@@ -249,45 +267,70 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
);
}
- // Cleans up a half-built staging venv (best-effort, in the
- // background: it may hold a partial torch download, tens of
- // thousands of files, and nobody is waiting on this) and reports the
- // given message. Every early return below the venv build goes
- // through this, so the "old venv untouched" claim is enforced in
- // exactly one place rather than repeated at each call site.
- let abandon_staging = |status: &str, msg: &str, install_status: &std::sync::Arc<std::sync::Mutex<crate::state::InstallState>>| {
- let doomed = staging_dir.clone();
- std::thread::spawn(move || {
- if let Err(e) = std::fs::remove_dir_all(&doomed) {
- warn!(error = %e, folder = %doomed.display(), "an abandoned staging venv could not be removed");
+ // Nothing of ours may still be running out of the OLD venv before it
+ // is even RETIRED, or its files stay open on Windows and the rename
+ // fails (see `venv::windows_lock_aware_retire_error`'s doc: this is
+ // the same OI-3 reasoning Runde 5 applied right before its swap; it
+ // has to run before the retire now, since the retire is the first
+ // destructive step).
+ if venv_dir.exists() {
+ if let Ok(mut w) = whisper.lock() {
+ if w.is_running() {
+ update(
+ "installing",
+ "Stopping the voice-input server, which runs from the existing \
+ environment. It restarts by itself the next time you use voice input.",
+ );
+ w.stop();
}
- });
+ }
+ }
+
+ update("installing", "Step 1/4: Setting the existing environment aside...");
+ let retired = match retire_for_rebuild(&venv_dir) {
+ Ok(r) => r,
+ Err(msg) => {
+ update("error", &msg);
+ return;
+ }
+ };
+
+ // Every early return from here on has to leave the customer with a
+ // WORKING venv again: either the freshly verified new one, or, on
+ // ANY failure (a failed build, a failed download, a failed
+ // requirements install, a failed verification, or the user
+ // cancelling at any of those points), the retired old one restored.
+ // One place, so that guarantee is enforced once instead of repeated
+ // at each call site, the same reasoning Runde 5's `abandon_staging`
+ // documented for the staging approach.
+ let abort_and_restore = |status: &str, msg: &str, install_status: &std::sync::Arc<std::sync::Mutex<crate::state::InstallState>>| {
+ let restore_note = match restore_after_failed_rebuild(&comfy_dir, &venv_dir, retired.clone()) {
+ Ok(()) => String::new(),
+ Err(e) => format!("\n\n{}", e),
+ };
if let Ok(mut s) = install_status.lock() {
s.status = status.to_string();
- s.logs.push(msg.to_string());
+ s.logs.push(format!("{msg}{restore_note}"));
}
};
- update(
- "installing",
- "Step 1/4: Building the new environment alongside the existing one...",
- );
- let staging_py = match create_comfyui_venv_named(&comfy_dir, &staging_name, &chosen_python, Some(&cancel_flag)) {
+ let venv_py = match create_comfyui_venv(&comfy_dir, &chosen_python, Some(&cancel_flag)) {
Ok(p) => p.to_string_lossy().to_string(),
Err(e) if e == "cancelled" => {
- update(
+ abort_and_restore(
"cancelled",
- "Repair cancelled while the new environment was being built. Your existing \
- environment was not touched.",
+ "Repair cancelled while the new environment was being built. Your previous \
+ environment was restored.",
+ &install_status,
);
return;
}
Err(e) => {
- abandon_staging(
+ abort_and_restore(
"error",
&format!(
- "Building the new environment failed. Your existing environment was not \
- touched.\n\n{}",
+ "Building the new environment failed. Your previous environment was \
+ restored.\n\n{}",
e
),
&install_status,
@@ -303,23 +346,23 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
"Downloading PyTorch into the new environment (~2 GB). Live pip output below.",
);
let refs: Vec<&str> = torch_args.iter().map(|s| s.as_str()).collect();
- match pip_install_streaming_with_retry_cancellable(&refs, &staging_py, 3, &install_status, Some(&cancel_flag)) {
+ match pip_install_streaming_with_retry_cancellable(&refs, &venv_py, 3, &install_status, Some(&cancel_flag)) {
Ok(()) => update("installing", "PyTorch installed."),
Err(d) if d == "cancelled" => {
- abandon_staging(
+ abort_and_restore(
"cancelled",
- "Repair cancelled during the PyTorch download. Your existing environment was \
- not touched.",
+ "Repair cancelled during the PyTorch download. Your previous environment was \
+ restored.",
&install_status,
);
return;
}
Err(d) => {
- abandon_staging(
+ abort_and_restore(
"error",
&format!(
- "PyTorch installation failed. Your existing environment was not \
- touched.\n\n{}",
+ "PyTorch installation failed. Your previous environment was \
+ restored.\n\n{}",
d
),
&install_status,
@@ -333,7 +376,7 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
// renamed or deleted while the rebuild was running, which is a real
// few minutes on a slow line.
if !reqs.exists() {
- abandon_staging("error", &missing_requirements_for_repair(&comfy_dir), &install_status);
+ abort_and_restore("error", &missing_requirements_for_repair(&comfy_dir), &install_status);
return;
}
{
@@ -348,13 +391,13 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
"--no-input",
"-r", reqs_str.as_str(),
];
- match pip_install_streaming_with_retry_raw(&req_args, &staging_py, 3, &install_status, Some(&cancel_flag)) {
+ match pip_install_streaming_with_retry_raw(&req_args, &venv_py, 3, &install_status, Some(&cancel_flag)) {
Ok(()) => update("installing", "Dependencies installed."),
Err(f) if f.diagnosis == "cancelled" => {
- abandon_staging(
+ abort_and_restore(
"cancelled",
- "Repair cancelled during the requirements install. Your existing \
- environment was not touched.",
+ "Repair cancelled during the requirements install. Your previous \
+ environment was restored.",
&install_status,
);
return;
@@ -375,12 +418,12 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
}
}
- // OI-3: put the passengers back, into the NEW (still staging)
- // environment. Failures here are reported but do not fail the
- // repair, since a working ComfyUI is nearly ready at this point, and
- // burying it under a Piper wheel error would trade one silent loss
- // for another. What must never happen again is the repair finishing
- // without saying what happened to Voice.
+ // OI-3: put the passengers back, into the new environment. Failures
+ // here are reported but do not fail the repair, since a working
+ // ComfyUI is nearly ready at this point, and burying it under a
+ // Piper wheel error would trade one silent loss for another. What
+ // must never happen again is the repair finishing without saying
+ // what happened to Voice.
let mut lost: Vec<&str> = Vec::new();
for p in &passengers {
update(
@@ -393,14 +436,14 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
"--no-input",
p.pip_name,
];
- match pip_install_streaming_with_retry_cancellable(&args, &staging_py, 3, &install_status, Some(&cancel_flag)) {
+ match pip_install_streaming_with_retry_cancellable(&args, &venv_py, 3, &install_status, Some(&cancel_flag)) {
Ok(()) => update("installing", &format!("{} is back.", p.label)),
Err(d) if d == "cancelled" => {
- abandon_staging(
+ abort_and_restore(
"cancelled",
&format!(
- "Repair cancelled while reinstalling {}. Your existing environment \
- was not touched.",
+ "Repair cancelled while reinstalling {}. Your previous environment \
+ was restored.",
p.label
),
&install_status,
@@ -421,29 +464,29 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
// A3: this is the step the button was missing. Two of the five
// reporters pressed Repair environment and nothing changed, because a
// rebuild that trusts pip's exit code rebuilds the same hole. Now
- // also the B7(c) gate: this is the LAST check before the old venv is
- // touched at all, so a new environment that does not import never
- // gets swapped in over a working old one.
+ // also the B9 gate: this is the LAST check before the retired old
+ // venv is discarded for good, so a new environment that does not
+ // import never leaves the customer with neither one.
update("installing", "Step 4/4: Checking that the new environment really starts...");
- match verify_and_heal_environment(&staging_py, &comfy_dir, &reqs, &install_status, Some(&cancel_flag)) {
+ match verify_and_heal_environment(&venv_py, &comfy_dir, &reqs, &install_status, Some(&cancel_flag)) {
Ok(()) => {}
Err(e) if e == "cancelled" => {
- abandon_staging(
+ abort_and_restore(
"cancelled",
- "Repair cancelled during the environment check. Your existing environment \
- was not touched.",
+ "Repair cancelled during the environment check. Your previous environment \
+ was restored.",
&install_status,
);
return;
}
Err(e) => {
error!("comfyui env repair built an environment that does not import");
- abandon_staging(
+ abort_and_restore(
"error",
&format!(
"The new environment was built, but it still does not start, so your \
- existing environment was left in place instead of being replaced with \
- one that does not work either.\n\n{}",
+ previous environment was restored instead of being replaced with one \
+ that does not work either.\n\n{}",
e
),
&install_status,
@@ -452,53 +495,105 @@ pub fn repair_comfyui_env(state: State<'_, AppState>) -> Result<serde_json::Valu
}
}
- // The new environment is built, populated and VERIFIED. Only now is
- // the old one touched: nothing above this line can destroy it.
- update("installing", "Swapping in the new, verified environment...");
- if venv_dir.exists() {
- // Before the swap: nothing of ours may still be running out of
- // the OLD venv (see the `whisper` clone above), or its files
- // stay open on Windows and the rename below fails.
- if let Ok(mut w) = whisper.lock() {
- if w.is_running() {
- update(
- "installing",
- "Stopping the voice-input server, which runs from the old environment. \
- It restarts by itself the next time you use voice input.",
- );
- w.stop();
- }
- }
- }
- if let Err(e) = swap_in_new_venv(&comfy_dir, &venv_dir, &staging_dir) {
- update("error", &e);
- return;
- }
- // Opportunistic: any staging or retired folder an earlier, interrupted
- // repair left behind. Never blocks this run.
- sweep_retired_venvs(&comfy_dir);
- let venv_py = staging_py;
+ // The new environment is built, populated and VERIFIED, and it is
+ // already at its final path: nothing above this line ever renamed
+ // it, so there is no swap left to do. Only now is the retired old
+ // one discarded for good.
+ update("installing", "Removing the previous, now-replaced environment...");
+ finish_rebuild(&comfy_dir, retired);
// Runde 5 Folgeposten (review Runde 4, Abschnitt 2): the repair's own
// log line promises "custom nodes stay untouched", true for the
// FOLDERS but not for what they import: their own requirements.txt
// never followed the venv into the rebuild. Reusing
// `install_node_requirements` (the same function `install_custom_node`
- // itself calls, #72's rule) against the now-swapped-in venv, one
- // folder's failure never stopping the rest.
- let broken_nodes: Vec<(String, String)> = if comfy_dir.join("custom_nodes").is_dir() {
- update(
- "installing",
- "Restoring dependencies for your existing custom nodes...",
+ // itself calls, #72's rule) against the now-final venv, one folder's
+ // failure never stopping the rest.
+ //
+ // Runde 6, Folgeposten (a) (review Runde 5, F2): a node's own
+ // requirements.txt (an unpinned old torch, a `numpy<2`, ...) must not
+ // be allowed to quietly downgrade the core packages this repair just
+ // spent four steps verifying. A constraints file built from THIS
+ // venv's own `pip freeze` of torch/torchvision/torchaudio/numpy makes
+ // pip refuse such a change outright: the node's own install fails
+ // loudly and by name, through the existing per-node failure list,
+ // instead of the environment silently regressing. `verify_and_heal_
+ // environment` then runs a SECOND time after the whole node loop: a
+ // node with an `install.py` or another way around the constraint
+ // (F10, still open) could still break something the constraints file
+ // does not cover, and this is the backstop for that.
+ //
+ // Runde 6, Folgeposten (b): a name and a log line per node while this
+ // runs (there was one blanket sentence before), and the cancel flag
+ // is now read between nodes, so twenty custom nodes no longer look
+ // like a hang with a Cancel button that does nothing.
+ let mut broken_nodes: Vec<(String, String)> = Vec::new();
+ if comfy_dir.join("custom_nodes").is_dir() {
+ let constraints = super::custom_nodes::write_core_package_constraints(&venv_py);
+ let outcome = super::custom_nodes::reinstall_all_node_requirements(
+ &comfy_dir,
+ &venv_py,
+ constraints.as_deref(),
+ Some(&cancel_flag),
+ |name| update("installing", &format!("Restoring dependencies for {}...", name)),
);
- let broken = super::custom_nodes::reinstall_all_node_requirements(&comfy_dir, &venv_py);
- for (name, _) in &broken {
+ if let Some(c) = &constraints {
+ let _ = std::fs::remove_file(c);
+ }
+ for (name, _) in &outcome.failures {
update("installing", &format!("Could not restore requirements for {}.", name));
}
- broken
- } else {
- Vec::new()
- };
+ if outcome.cancelled {
+ update(
+ "cancelled",
+ "Repair cancelled while restoring custom node dependencies. ComfyUI's \
+ environment itself was already rebuilt and verified; some custom nodes may \
+ still be missing their own dependencies.",
+ );
+ return;
+ }
+ if outcome.failures.is_empty() && !outcome.reinstalled.is_empty() {
+ update(
+ "installing",
+ "Re-checking the environment after restoring custom node dependencies...",
+ );
+ if let Err(e) = verify_and_heal_environment(&venv_py, &comfy_dir, &reqs, &install_status, Some(&cancel_flag)) {
+ if e == "cancelled" {
+ update(
+ "cancelled",
+ "Repair cancelled during the post-restore environment check. ComfyUI's \
+ environment itself was already rebuilt and verified.",
+ );
+ return;
+ }
+ // A3: the same rule that governs the FIRST verification
+ // governs this one too. The constraints file above is
+ // the primary defense, but it cannot cover every way a
+ // node's own install could break something (an
+ // `install.py`, F10, still open); this is the backstop,
+ // and it must stop the run rather than report "complete"
+ // over an environment that no longer starts. The venv
+ // itself is left exactly as it is (its own build already
+ // passed verification once): only the node loop's
+ // outcome is undone, by naming it, not by rolling back
+ // the whole rebuild.
+ error!(nodes = ?outcome.reinstalled, "comfyui repair: custom node dependencies left the environment unable to start");
+ let suspects = outcome.reinstalled.join(", ");
+ update("error",
+ &format!(
+ "The environment was rebuilt and verified, but restoring custom node \
+ dependencies left it unable to start again. One of these likely \
+ caused it: {}. Disabling that node (move its folder out of \
+ custom_nodes and add .disabled to the name) and repairing again \
+ usually clears it.\n\n{}",
+ suspects, e
+ ),
+ );
+ return;
+ }
+ }
+ broken_nodes = outcome.failures;
+ }
// What used to say "custom nodes stay untouched" unconditionally. That
// was only ever true of the folders, not of what they import, and the
@@ -822,6 +917,73 @@ fn repair_precheck(comfy_dir: &Path) -> Result<(), String> {
Ok(())
}
+/// The total size on disk of everything under `dir`, in bytes. Best-effort:
+/// a file that vanishes mid-walk (a background delete, a concurrent process)
+/// is simply skipped rather than failing the whole measurement, since this
+/// feeds a space ESTIMATE, not an exact accounting.
+fn dir_size(dir: &Path) -> u64 {
+ walkdir::WalkDir::new(dir)
+ .into_iter()
+ .filter_map(|e| e.ok())
+ .filter(|e| e.file_type().is_file())
+ .filter_map(|e| e.metadata().ok())
+ .map(|m| m.len())
+ .sum()
+}
+
+/// Runde 6, B9: the old venv and the new one sit on the same drive at the
+/// same time now, from the moment the old one is retired until the new one
+/// passes verification. `check_install_disk_pressure`'s flat 5 GB estimate
+/// (still shown as a soft warning right after this) never accounted for
+/// that second copy, and it never refused outright either. This does both:
+/// it adds the existing venv's real, measured size to the ~5 GB a fresh
+/// build needs, and it is a REFUSAL, run before `retire_for_rebuild` touches
+/// anything, so a drive that genuinely cannot hold both says so honestly
+/// up front instead of failing part-way through with the old venv already
+/// gone.
+///
+/// `None` both when the drive cannot be identified (same fallback
+/// `check_install_disk_pressure` uses) and when there is no existing venv at
+/// all yet: a first build's own soft warning already covers that case.
+fn check_repair_disk_pressure(comfy_dir: &Path, venv_dir: &Path) -> Option<String> {
+ if !venv_dir.exists() {
+ return None;
+ }
+ use sysinfo::Disks;
+ let disks = Disks::new_with_refreshed_list();
+ let normalized = comfy_dir.to_path_buf();
+ let mut best: Option<&sysinfo::Disk> = None;
+ let mut best_len: usize = 0;
+ for d in &disks {
+ let mp = d.mount_point();
+ if normalized.starts_with(mp) {
+ let len = mp.as_os_str().len();
+ if len > best_len {
+ best_len = len;
+ best = Some(d);
+ }
+ }
+ }
+ let disk = best?;
+ let free_bytes = disk.available_space();
+ let existing_bytes = dir_size(venv_dir);
+ let needed_for_new_build: u64 = 5 * 1024 * 1024 * 1024;
+ let required = needed_for_new_build.saturating_add(existing_bytes);
+ if free_bytes < required {
+ return Some(format!(
+ "Not enough free space to rebuild this environment. The existing environment is \
+ about {:.1} GB, and building a new one alongside it before the old one is removed \
+ needs about 5 GB more ({:.1} GB total); only {:.1} GB is free on {}. Free up space \
+ and try again; nothing was changed.",
+ existing_bytes as f64 / 1_073_741_824.0,
+ required as f64 / 1_073_741_824.0,
+ free_bytes as f64 / 1_073_741_824.0,
+ disk.mount_point().to_string_lossy(),
+ ));
+ }
+ None
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -875,11 +1037,11 @@ mod tests {
let needle = |head: &str, tail: &str| format!("{head}{tail}");
let call = src.find(&needle("if let Err(msg) = repair_prech", "eck(&comfy_dir) {"))
.expect("Repair no longer prechecks at all");
- let build = src.find(&needle("\"Step 1/4: Building the new environ", "ment alongside the existing one...\","))
- .expect("the staging venv build step is gone");
+ let build = src.find(&needle("\"Step 1/4: Setting the existing environ", "ment aside...\");"))
+ .expect("the retire-the-old-venv step is gone");
let torch = src.find(&needle("\"Downloading PyTorch into the new env", "ironment (~2 GB). Live pip output below.\","))
.expect("the PyTorch step is gone");
- assert!(call < build, "the precheck runs after the new venv is built");
+ assert!(call < build, "the precheck runs after the old venv is retired");
assert!(call < torch, "the precheck runs after the PyTorch download");
// And the guard on the guard: each needle occurs EXACTLY once in the
@@ -888,7 +1050,7 @@ mod tests {
// became unreachable in the first place.
for (what, n) in [
("the precheck call", needle("if let Err(msg) = repair_prech", "eck(&comfy_dir) {")),
- ("the staging venv build step", needle("\"Step 1/4: Building the new environ", "ment alongside the existing one...\",")),
+ ("the retire-the-old-venv step", needle("\"Step 1/4: Setting the existing environ", "ment aside...\");")),
("the PyTorch step", needle("\"Downloading PyTorch into the new env", "ironment (~2 GB). Live pip output below.\",")),
] {
assert_eq!(
@@ -900,50 +1062,65 @@ mod tests {
}
#[test]
- fn the_repair_never_touches_the_old_venv_before_the_new_one_is_verified() {
- // B7(c) (review Runde 4): the old venv used to be retired BEFORE the
- // new one was even built, which is what left P3 and the Runde-4
- // reporter with neither a working old venv nor a working new one when
- // the build failed partway. Now the ONLY call that touches the old
- // venv is `swap_in_new_venv`, and it must sit strictly after
- // `verify_and_heal_environment` has already returned `Ok`.
+ fn the_repair_never_discards_the_old_venv_before_the_new_one_is_verified() {
+ // Runde 6, B9: the old venv used to be RENAMED INTO the new venv's
+ // build folder (Runde 5's staging approach), which left every
+ // console script's shebang pointing at a name that no longer
+ // existed. Now the old venv is only ever RETIRED (a reversible
+ // rename, back to the exact name it already had if anything fails)
+ // and the new one is built DIRECTLY at the final `venv` name, never
+ // renamed at all. What still has to hold: the retired old venv is
+ // discarded for good (`finish_rebuild`) only strictly after the new
+ // one, built at the final name, has passed verification.
//
// Same shape as the precheck order test above, and for the same
// reason: the body is a thread inside a Tauri command, so the order
- // is read out of this file. Needles split in half so they never match
- // themselves here, and each one checked to occur exactly once.
+ // is read out of this file. Needles split in half so they never
+ // match themselves here.
let src = include_str!("comfy_repair.rs");
let needle = |head: &str, tail: &str| format!("{head}{tail}");
- let verify = needle("verify_and_heal_environment(&stag", "ing_py, &comfy_dir, &reqs, &install_status, Some(&cancel_flag))");
- let swap = needle("swap_in_new_venv(&comfy_dir, &venv", "_dir, &staging_dir)");
+ let retire = needle("let retired = match retire_for_reb", "uild(&venv_dir) {");
+ let build = needle("let venv_py = match create_comfyui_v", "env(&comfy_dir, &chosen_python, Some(&cancel_flag)) {");
+ let verify = needle("verify_and_heal_environment(&venv_p", "y, &comfy_dir, &reqs, &install_status, Some(&cancel_flag))");
+ let finish = needle("finish_rebuild(&comfy_d", "ir, retired);");
- let at_verify = src.find(&verify).expect("the verify-and-heal call on the staging venv is gone");
- let at_swap = src.find(&swap).expect("the swap into the old venv's place is gone");
+ let at_retire = src.find(&retire).expect("the retire-for-rebuild call is gone");
+ let at_build = src.find(&build).expect("the new venv is no longer built directly at the final name");
+ let at_verify = src.find(&verify).expect("the verify-and-heal call on the new venv is gone");
+ let at_finish = src.find(&finish).expect("the old venv is no longer discarded via finish_rebuild");
- assert!(at_verify < at_swap, "the old venv is swapped in for before the new one is verified");
+ assert!(at_retire < at_build, "the old venv is retired after the new one is already being built");
+ assert!(at_build < at_verify, "the new venv is verified before it is even built");
+ assert!(at_verify < at_finish, "the old venv is discarded before the new one is verified");
// The old way out has to be gone, not merely bypassed. Any direct
- // `retire_venv`/`remove_dir_all` on the old venv outside of
- // `swap_in_new_venv` would bring back exactly the failure mode this
+ // `retire_venv`/`remove_dir_all` on the OLD venv outside of
+ // `retire_for_rebuild`, `restore_after_failed_rebuild` and
+ // `finish_rebuild` would bring back exactly the failure mode this
// guards against.
assert!(
!src.contains(&needle("retire_venv(&venv", "_dir)")),
- "something in this file still retires the old venv directly, outside swap_in_new_venv"
+ "something in this file still retires the old venv directly, outside retire_for_rebuild"
);
assert!(
!src.contains(&needle("std::fs::remove_dir_all(&venv", "_dir)")),
- "something in this file still deletes the old venv directly, outside swap_in_new_venv"
+ "something in this file still deletes the old venv directly, outside the venv module's own helpers"
);
- for (what, n) in [
- ("the verify-and-heal call", verify),
- ("the swap call", swap),
+ // verify_and_heal_environment runs a SECOND time after the custom
+ // node dependency restore (Runde 6, Folgeposten a); every other
+ // needle is expected exactly once.
+ for (what, n, expected) in [
+ ("the retire call", retire, 1),
+ ("the venv build call", build, 1),
+ ("the verify call", verify, 2),
+ ("the finish_rebuild call", finish, 1),
] {
assert_eq!(
src.matches(&n).count(),
- 1,
- "{what}: the search string finds itself in this test, so its .expect can never fire",
+ expected,
+ "{what}: expected {expected} occurrence(s) in this file",
);
}
}
diff --git a/src-tauri/src/commands/install/custom_nodes.rs b/src-tauri/src/commands/install/custom_nodes.rs
index 3b808da9..6224c80a 100644
--- a/src-tauri/src/commands/install/custom_nodes.rs
+++ b/src-tauri/src/commands/install/custom_nodes.rs
@@ -208,7 +208,11 @@ fn install_custom_node_blocking(
}
}
- install_node_requirements(&comfy_dir, &target_dir, &node_name, fallback_python)?;
+ // No constraints file here: this is a fresh clone (or update) of ONE
+ // node against whatever the venv already has, not the post-repair
+ // restore path where a downgrade of a just-verified core package is the
+ // specific risk (Runde 6, Folgeposten a).
+ install_node_requirements(&comfy_dir, &target_dir, &node_name, fallback_python, None)?;
Ok(serde_json::json!({
"status": if fresh_clone { "installed" } else { "updated" },
@@ -256,6 +260,7 @@ pub(crate) fn install_node_requirements(
target_dir: &std::path::Path,
node_name: &str,
fallback_python: &str,
+ constraints: Option<&std::path::Path>,
) -> Result<(), String> {
let reqs = target_dir.join("requirements.txt");
if !reqs.exists() {
@@ -284,6 +289,16 @@ pub(crate) fn install_node_requirements(
let run_pip = |extra: &[&str]| -> Result<std::process::Output, String> {
let mut pip = python_command(&python_bin);
pip.args(["-m", "pip", "install", "--no-input"]);
+ // Runde 6, Folgeposten (a) (review Runde 5, F2): a node's own
+ // requirements.txt must not be allowed to quietly downgrade the
+ // core packages a repair just verified (`numpy<2`, an unpinned old
+ // torch, ...). With `-c`, pip refuses to install anything that
+ // conflicts with a constraint instead of silently changing it, so
+ // THIS install fails, loudly, by name, through the ordinary
+ // per-node failure path below.
+ if let Some(c) = constraints {
+ pip.arg("-c").arg(c);
+ }
pip.args(extra);
pip.arg("-r").arg(&reqs);
pip.stdout(Stdio::piped()).stderr(Stdio::piped());
@@ -328,6 +343,78 @@ pub(crate) fn install_node_requirements(
}
+/// Runde 6, Folgeposten (a) (review Runde 5, F2): the core packages a
+/// repair just spent four steps building and verifying, as a `pip freeze`
+/// snapshot a caller can hand to [`install_node_requirements`] as a
+/// constraints file so pip REFUSES to let a node's own requirements.txt
+/// quietly change any of them.
+const CORE_PACKAGES: [&str; 4] = ["torch", "torchvision", "torchaudio", "numpy"];
+
+/// Write [`CORE_PACKAGES`]'s current, exact versions (from `pip freeze`
+/// against `python_bin`) to a fresh temp file in pip's constraints format
+/// (one `name==version` per line) and return its path. `None` when `pip
+/// freeze` itself fails to run, or when none of the core packages turn out
+/// to be installed. A ComfyUI venv should always have torch, but this must
+/// never invent a pin rather than silently skip constraining.
+///
+/// The caller owns the returned file and is responsible for deleting it once
+/// the node loop that uses it is done; this function only ever creates one.
+pub(crate) fn write_core_package_constraints(python_bin: &str) -> Option<PathBuf> {
+ let mut cmd = python_command(python_bin);
+ cmd.args(["-m", "pip", "freeze"]).stdout(Stdio::piped()).stderr(Stdio::piped());
+ let out = cmd.output().ok()?;
+ if !out.status.success() {
+ return None;
+ }
+ let freeze = String::from_utf8_lossy(&out.stdout);
+ let core_lines = core_constraint_lines(&freeze);
+ if core_lines.is_empty() {
+ return None;
+ }
+ let path = std::env::temp_dir().join(format!(
+ "lu-node-constraints-{}-{}.txt",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0),
+ ));
+ fs::write(&path, core_lines.join("\n")).ok()?;
+ Some(path)
+}
+
+/// Pure: the subset of a `pip freeze` listing that names one of
+/// [`CORE_PACKAGES`], for exactly the reason every other network- or
+/// process-touching function in this codebase splits its parsing out:
+/// testable against a canned string, no pip and no venv required.
+fn core_constraint_lines(freeze: &str) -> Vec<&str> {
+ freeze
+ .lines()
+ .filter(|line| {
+ let name = line
+ .split(['=', '@', ' ', '<', '>', '~', '!'])
+ .next()
+ .unwrap_or("")
+ .to_lowercase();
+ CORE_PACKAGES.contains(&name.as_str())
+ })
+ .collect()
+}
+
+/// What a custom-node dependency restore actually did, so the caller can
+/// tell a customer which nodes came back, which did not, and whether the
+/// user cancelled partway rather than every node simply having run.
+pub(crate) struct NodeReinstallOutcome {
+ /// Node folder names whose requirements installed cleanly.
+ pub(crate) reinstalled: Vec<String>,
+ /// Node folder name plus the reason, for every one that failed.
+ pub(crate) failures: Vec<(String, String)>,
+ /// True when the cancel flag was seen between nodes and the loop
+ /// stopped early; `reinstalled`/`failures` only cover what ran before
+ /// that point.
+ pub(crate) cancelled: bool,
+}
+
/// Runde 5 (review-engine.md Runde 4, Folgeposten): after the repair
/// rebuilds `ComfyUI/venv` from nothing, every EXISTING `custom_nodes/*`
/// folder's own `requirements.txt` (RMBG, VHS, controlnet_aux, whatever the
@@ -346,12 +433,28 @@ pub(crate) fn install_node_requirements(
/// one broken one should get four working nodes back, not zero, and the
/// caller is told which one(s) failed so it can say so instead of silently
/// claiming success.
-pub(crate) fn reinstall_all_node_requirements(comfy_dir: &std::path::Path, fallback_python: &str) -> Vec<(String, String)> {
+///
+/// Runde 6, Folgeposten (a) and (b) (review Runde 5, F2/F3): `constraints`
+/// (from [`write_core_package_constraints`]) is passed straight through to
+/// every node's own install so none of them can quietly downgrade torch or
+/// numpy; `cancel` is read BETWEEN nodes so a customer with twenty of them
+/// can actually stop the run instead of the Cancel button doing nothing
+/// (F3); and `on_progress` is called with each node's name before it starts,
+/// so the log carries one line per node instead of a single blanket
+/// sentence for the whole batch.
+pub(crate) fn reinstall_all_node_requirements(
+ comfy_dir: &std::path::Path,
+ fallback_python: &str,
+ constraints: Option<&std::path::Path>,
+ cancel: Option<&std::sync::Arc<std::sync::atomic::AtomicBool>>,
+ mut on_progress: impl FnMut(&str),
+) -> NodeReinstallOutcome {
let nodes_dir = comfy_dir.join("custom_nodes");
let Ok(entries) = fs::read_dir(&nodes_dir) else {
- return Vec::new();
+ return NodeReinstallOutcome { reinstalled: Vec::new(), failures: Vec::new(), cancelled: false };
};
let mut failures = Vec::new();
+ let mut reinstalled = Vec::new();
let mut names: Vec<(String, PathBuf)> = entries
.flatten()
.filter(|e| e.path().is_dir())
@@ -373,12 +476,18 @@ pub(crate) fn reinstall_all_node_requirements(comfy_dir: &std::path::Path, fallb
// stable.
names.sort();
for (name, target_dir) in names {
- if let Err(e) = install_node_requirements(comfy_dir, &target_dir, &name, fallback_python) {
+ if cancel.is_some_and(|c| c.load(std::sync::atomic::Ordering::SeqCst)) {
+ return NodeReinstallOutcome { reinstalled, failures, cancelled: true };
+ }
+ on_progress(&name);
+ if let Err(e) = install_node_requirements(comfy_dir, &target_dir, &name, fallback_python, constraints) {
error!(node = %name, error = %e, "custom node requirements could not be restored after a repair");
failures.push((name, e));
+ } else {
+ reinstalled.push(name);
}
}
- failures
+ NodeReinstallOutcome { reinstalled, failures, cancelled: false }
}
#[cfg(test)]
@@ -430,7 +539,7 @@ mod tests {
// No requirements.txt → must succeed without ever spawning pip
// (an empty fallback python would otherwise be an instant Err).
- assert!(install_node_requirements(&comfy, &node, "NoReqs", "").is_ok());
+ assert!(install_node_requirements(&comfy, &node, "NoReqs", "", None).is_ok());
}
#[test]
@@ -441,12 +550,90 @@ mod tests {
std::fs::create_dir_all(&node).unwrap();
std::fs::write(node.join("requirements.txt"), "imageio-ffmpeg").unwrap();
- let err = install_node_requirements(&comfy, &node, "WithReqs", "").unwrap_err();
+ let err = install_node_requirements(&comfy, &node, "WithReqs", "", None).unwrap_err();
assert!(err.contains("no Python available"), "got: {err}");
}
+ // ── Runde 6, Folgeposten (a): core-package constraints (review Runde 5,
+ // F2) ─────────────────────────────────────────────────────────────────
+
+ #[test]
+ fn core_constraint_lines_keeps_only_the_core_packages() {
+ let freeze = "torch==2.7.0\n\
+ torchvision==0.22.0\n\
+ numpy==1.26.4\n\
+ Pillow==11.0.0\n\
+ comfyui-frontend-package==1.2.3\n\
+ torchaudio==2.7.0\n";
+ let lines = core_constraint_lines(freeze);
+ assert_eq!(lines, vec!["torch==2.7.0", "torchvision==0.22.0", "numpy==1.26.4", "torchaudio==2.7.0"]);
+ // Negative control: neither Pillow nor comfyui-frontend-package,
+ // both real ComfyUI-venv packages, may leak into the constraints.
+ assert!(!lines.iter().any(|l| l.to_lowercase().starts_with("pillow")));
+ assert!(!lines.iter().any(|l| l.to_lowercase().starts_with("comfyui")));
+ }
+
+ #[test]
+ fn core_constraint_lines_is_empty_for_a_freeze_with_no_core_packages() {
+ // Negativkontrolle: a venv that somehow has no torch at all must not
+ // invent a pin; an empty result is what tells the caller not to
+ // write a constraints file.
+ assert!(core_constraint_lines("Pillow==11.0.0\nrequests==2.32.0\n").is_empty());
+ assert!(core_constraint_lines("").is_empty());
+ }
+
+ #[test]
+ fn core_constraint_lines_is_not_fooled_by_a_name_prefix() {
+ // "torch" must not match "torchsde" or "torchdiffeq", real
+ // dependencies in a ComfyUI venv that are not the core packages this
+ // constraints file exists to protect.
+ let freeze = "torchsde==0.2.6\ntorchdiffeq==0.2.4\ntorch==2.7.0\n";
+ let lines = core_constraint_lines(freeze);
+ assert_eq!(lines, vec!["torch==2.7.0"]);
+ }
+
// ── permission-denied → --user retry (Motion install card, 2026-07-19) ──
+ // ── Runde 6, Folgeposten (b): cancel + per-node progress ──────────────
+ #[test]
+ fn the_node_loop_stops_early_when_cancelled_and_reports_it() {
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("comfy");
+ for name in ["AlphaNode", "BetaNode"] {
+ std::fs::create_dir_all(comfy.join("custom_nodes").join(name)).unwrap();
+ // No requirements.txt: a node that WOULD succeed instantly if
+ // reached, so a green "cancelled" result here is only possible
+ // because the loop actually stopped before reaching it.
+ }
+ let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
+ let mut seen: Vec<String> = Vec::new();
+ let outcome = reinstall_all_node_requirements(&comfy, "", None, Some(&cancel), |name| seen.push(name.to_string()));
+
+ assert!(outcome.cancelled, "a pre-set cancel flag did not stop the loop");
+ assert!(seen.is_empty(), "a node was started after cancel was already set: {seen:?}");
+ assert!(outcome.reinstalled.is_empty());
+ assert!(outcome.failures.is_empty());
+ }
+
+ #[test]
+ fn a_negative_control_without_cancel_runs_every_node_and_reports_none_cancelled() {
+ // Negativkontrolle for the test above: without a raised flag, every
+ // node folder is visited and none is reported as cancelled.
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("comfy");
+ for name in ["AlphaNode", "BetaNode", "__pycache__", "GammaNode.disabled"] {
+ std::fs::create_dir_all(comfy.join("custom_nodes").join(name)).unwrap();
+ }
+ let mut seen: Vec<String> = Vec::new();
+ let outcome = reinstall_all_node_requirements(&comfy, "", None, None, |name| seen.push(name.to_string()));
+
+ assert!(!outcome.cancelled);
+ // Deterministic, sorted order; __pycache__ and the disabled node are
+ // never real nodes and must not be visited at all.
+ assert_eq!(seen, vec!["AlphaNode", "BetaNode"]);
+ assert_eq!(outcome.reinstalled, vec!["AlphaNode", "BetaNode"]);
+ assert!(outcome.failures.is_empty());
+ }
}
diff --git a/src-tauri/src/commands/install/venv.rs b/src-tauri/src/commands/install/venv.rs
index 5585e0f5..5f326412 100644
--- a/src-tauri/src/commands/install/venv.rs
+++ b/src-tauri/src/commands/install/venv.rs
@@ -80,28 +80,19 @@ pub fn is_pep668_protected(python_bin: &str) -> bool {
/// file exists, and `python -m venv` writes that file BEFORE it runs
/// `ensurepip`, so leaving the ruin behind would have autostart launching
/// ComfyUI out of an env with an empty site-packages.
+/// Runde 6, B9: this always builds under the fixed name `venv`, never a
+/// staging sibling. See [`retire_for_rebuild`]'s doc for why: a venv's own
+/// scripts bake in the ABSOLUTE path it was built at, so a venv that is ever
+/// going to live at `<comfyui_dir>/venv` has to be BUILT there, not built
+/// somewhere else and renamed in afterwards. The repair calls
+/// [`retire_for_rebuild`] first when an old venv is in the way, so this
+/// always runs against an empty slot.
pub fn create_comfyui_venv(
comfyui_dir: &Path,
python_bin: &str,
cancel: Option<&Arc<AtomicBool>>,
) -> Result<PathBuf, String> {
- create_comfyui_venv_named(comfyui_dir, "venv", python_bin, cancel)
-}
-
-/// Same as [`create_comfyui_venv`], but for an arbitrary venv folder name
-/// instead of the fixed `venv`.
-///
-/// Runde 5, B7(c): the repair's build-then-swap needs to build the NEW venv
-/// under a staging name (`STAGING_VENV_PREFIX`) that is not `venv` at all,
-/// so the old, still-working `venv` is never touched until the new one is
-/// built and verified. Only after that succeeds does the caller rename the
-/// staging folder over the real one.
-pub fn create_comfyui_venv_named(
- comfyui_dir: &Path,
- venv_name: &str,
- python_bin: &str,
- cancel: Option<&Arc<AtomicBool>>,
-) -> Result<PathBuf, String> {
+ let venv_name = "venv";
let venv_dir = comfyui_dir.join(venv_name);
// venv is idempotent: re-running on an existing dir just no-ops, but be
// explicit so the log reads cleanly.
@@ -197,15 +188,18 @@ pub fn create_comfyui_venv_named(
/// autostart and to `resolve_lu_python`.
pub(crate) const RETIRED_VENV_PREFIX: &str = "venv.lu-old-";
-/// Runde 5, B7(c): the name a NEW venv is built under while the old `venv`
-/// is still live. Neither `venv` nor `.venv`, same reasoning as
-/// [`RETIRED_VENV_PREFIX`]: invisible to `resolve_comfyui_venv_python`, the
-/// launcher, autostart and `detect_venv_passengers`, so a repair in
-/// progress never looks like it already has a broken second venv.
+/// Runde 5, B7(c), superseded by Runde 6's B9 fix: the name a NEW venv used
+/// to be built under while the old `venv` was still live. Nothing this LU
+/// version writes carries this prefix any more (see [`retire_for_rebuild`]'s
+/// doc for why that approach broke every console script's shebang), but
+/// `sweep_retired_venvs` still recognizes and clears it, because a customer
+/// upgrading FROM a version that used it can still have one sitting in their
+/// ComfyUI folder from an interrupted repair.
pub(crate) const STAGING_VENV_PREFIX: &str = "venv.lu-new-";
-/// Nanoseconds plus our own process id, so two runs (or a retiring venv and
-/// a staging venv in the same repair) never land on the same folder.
+/// Nanoseconds plus our own process id, so two runs (or a retired venv and a
+/// discarded failed-build venv from the same rebuild) never land on the same
+/// folder.
fn stamped_sibling_name(prefix: &str) -> String {
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -214,13 +208,6 @@ fn stamped_sibling_name(prefix: &str) -> String {
format!("{}{}-{}", prefix, stamp, std::process::id())
}
-/// A fresh, not-yet-existing staging folder NAME (not a path) to build the
-/// new venv under, via [`create_comfyui_venv_named`]. The caller joins it to
-/// the ComfyUI directory itself.
-pub(crate) fn staging_venv_name() -> String {
- stamped_sibling_name(STAGING_VENV_PREFIX)
-}
-
/// Move `<comfy>/venv` out of the way and answer where it went.
///
/// Deleting it in line was the 76 seconds P3 measured: a venv holding PyTorch
@@ -242,74 +229,183 @@ pub(crate) fn retire_venv(venv_dir: &Path) -> std::io::Result<PathBuf> {
Ok(retired)
}
-/// B7(c) (review Runde 4): the swap half of the build-then-swap repair. Only
-/// called once a staging venv has been built AND verified, never before. If
-/// `venv_dir` exists it is retired and `staging_dir` takes its name; on
-/// Windows, where a held-open handle can make that rename fail, the old venv
-/// is deleted in place instead before the same rename. If the FINAL rename
-/// (staging into place) itself fails, the old venv is put straight back
-/// rather than left as a bare retired folder, so this never trades a working
-/// old venv for neither.
+/// Runde 6, BLOCKER B9 (review Runde 5): a venv is not relocatable. Every
+/// console script's shebang (`venv/bin/pip`, `huggingface-cli`, `torchrun`,
+/// every `Scripts\*.exe` launcher on Windows) and every `activate` script
+/// bakes in the ABSOLUTE path the venv was BUILT at. Runde 5's build-then-
+/// swap built the new venv under a staging name and then renamed the folder
+/// to `venv` afterwards, a rename `create_comfyui_venv_named` itself never
+/// does anything to fix up. Measured on this machine (see the Runde 6 report
+/// in `bau/engine.md` for the exact transcript):
///
-/// A pure filesystem operation, deliberately not accepting a comfy_dir plus
-/// hardcoded child names: this is what makes it directly testable with two
-/// plain temp directories, one Attrappe standing in for each venv, and a
-/// negative control (below) that never even builds a staging folder.
-pub(crate) fn swap_in_new_venv(comfy_dir: &Path, venv_dir: &Path, staging_dir: &Path) -> Result<(), String> {
+/// ```text
+/// head -1 venv/bin/pip
+/// #!/.../venvtest/venv.lu-new-123/bin/python3
+/// venv/bin/pip --version
+/// bad interpreter: /.../venv.lu-new-12: no such file or directory
+/// ```
+///
+/// LU never noticed, because every one of ITS OWN pip calls goes through
+/// `<python> -m pip` (`venv/bin/python` survives the rename fine, since its own
+/// `pyvenv.cfg` only points at the BASE interpreter, never at itself), and
+/// the last verification ran against the staging name, before the rename.
+/// The customer notices the first time they `source venv/bin/activate` by
+/// hand, which is exactly how the venv reasonably installs the requirements
+/// a repair does not carry over (F2/#72's territory).
+///
+/// The fix is to never rename a BUILT venv into its final resting place at
+/// all: [`retire_for_rebuild`] moves the OLD venv aside FIRST (a rename is
+/// still fine there, since it is reversible back to the exact same name, so the
+/// path it was originally built at is restored byte-for-byte the moment it
+/// is renamed back), and the caller then builds the NEW venv directly under
+/// the final `venv` name via [`create_comfyui_venv`], so its build path and
+/// its resting path are the same string from the very first `python -m
+/// venv` call. Nothing here renames a fully-built venv into a different
+/// name than it was created with, ever again.
+///
+/// `retire_for_rebuild` alone is the "stilllegen" half B9 asks for; the
+/// "auf jeden Fehlschlag zurueckrollen" half lives in the caller
+/// (`comfy_repair.rs`'s `abort_and_restore`), because only the caller knows
+/// whether the NEW venv got far enough to exist at all when a step fails.
+pub(crate) fn retire_for_rebuild(venv_dir: &Path) -> Result<Option<PathBuf>, String> {
if !venv_dir.exists() {
- return std::fs::rename(staging_dir, venv_dir).map_err(|e| {
+ return Ok(None);
+ }
+ retire_venv(venv_dir).map(Some).map_err(|e| windows_lock_aware_retire_error(venv_dir, &e))
+}
+
+/// Runde 6, B9: on Windows, a process still holding any file inside the old
+/// venv open (a ComfyUI process, including one started OUTSIDE LU, exactly
+/// the K14 shape this task is measured against) makes `retire_venv`'s
+/// rename fail with `ERROR_ACCESS_DENIED` (raw code 5) or
+/// `ERROR_SHARING_VIOLATION` (32). The rename itself is one atomic metadata
+/// operation, so a failure here has not touched the old venv at all: there
+/// is nothing to roll back, but "os error 5" is not a sentence a customer
+/// can act on. This turns that specific pair of codes into the one thing
+/// they actually need to do about it, and falls back to the general wording
+/// for every other failure (permissions, a read-only filesystem, ...).
+fn windows_lock_aware_retire_error(venv_dir: &Path, e: &std::io::Error) -> String {
+ if cfg!(target_os = "windows") && matches!(e.raw_os_error(), Some(5) | Some(32)) {
+ return format!(
+ "Could not rebuild the environment: something is still using the existing venv \
+ folder at {}. This usually means ComfyUI is still running, including a copy \
+ started outside LU. Close ComfyUI first, then retry. Nothing was changed.",
+ venv_dir.display(),
+ );
+ }
+ venv_removal_error(venv_dir, e)
+}
+
+/// Runde 6, B9: the rollback half of the rebuild. Called on ANY failure from
+/// the moment `retire_for_rebuild` has moved the old venv aside up to the
+/// moment the new one passes verification: a failed build, a failed
+/// download, a failed requirements install, a failed verification, or the
+/// user cancelling at any of those points. `retired` is `None` when there
+/// was no old venv to begin with (a first install), in which case there is
+/// nothing to restore and only a half-built `venv` (if any) is cleared away.
+///
+/// The half-built `venv` is renamed to a throwaway sibling FIRST, a fast
+/// metadata operation that frees the `venv` name immediately, the same
+/// reasoning `retire_venv` itself documents for why a rename beats a
+/// blocking delete, and only then deleted, on a background thread, so this
+/// function returns as soon as the customer's old environment is back,
+/// never after walking however many files PyTorch left behind.
+///
+/// A pure filesystem operation, deliberately not accepting a comfy_dir plus
+/// hardcoded child names beyond the one directory it needs to place the
+/// throwaway sibling in: this is what makes it directly testable with plain
+/// temp directories instead of a real ComfyUI checkout.
+pub(crate) fn restore_after_failed_rebuild(comfy_dir: &Path, venv_dir: &Path, retired: Option<PathBuf>) -> Result<(), String> {
+ if venv_dir.exists() {
+ let discard = comfy_dir.join(stamped_sibling_name("venv.lu-failed-"));
+ std::fs::rename(venv_dir, &discard).map_err(|e| venv_removal_error(venv_dir, &e))?;
+ std::thread::spawn(move || {
+ if let Err(e) = std::fs::remove_dir_all(&discard) {
+ warn!(error = %e, folder = %discard.display(), "a failed rebuild's half-built venv could not be deleted");
+ }
+ });
+ }
+ if let Some(retired) = retired {
+ std::fs::rename(&retired, venv_dir).map_err(|e| {
format!(
- "The new environment was verified, but could not be moved into place: {}. It is \
- still on disk at {}; rename that folder to \"venv\" manually to recover it.",
- venv_removal_error(staging_dir, &e),
- staging_dir.display(),
+ "Your previous environment could not be restored: {}. It is still on disk at {}; \
+ rename that folder to \"venv\" manually to recover it.",
+ venv_removal_error(&retired, &e),
+ retired.display(),
)
- });
+ })?;
}
- match retire_venv(venv_dir) {
- Ok(retired) => {
- if let Err(rename_failed) = std::fs::rename(staging_dir, venv_dir) {
- // Extremely unlikely (both are plain renames on the same
- // filesystem, seconds apart), but a customer must never be
- // left with NEITHER a `venv` nor a clear next step. Put the
- // old one straight back rather than leave the folder empty.
- let _ = std::fs::rename(&retired, venv_dir);
- return Err(format!(
- "The new environment was verified, but could not be swapped into place ({}). \
- Your existing environment was restored; nothing was lost, but the repair did \
- not finish.",
- venv_removal_error(staging_dir, &rename_failed)
- ));
+ Ok(())
+}
+
+/// Runde 6, B9: after the new venv (built directly at `venv`, see
+/// [`retire_for_rebuild`]'s doc) has PASSED verification, the retired old
+/// one is no longer needed. Deleted on a background thread, the same
+/// reasoning as the old `swap_in_new_venv`'s deletion, followed by a sweep
+/// for any OTHER leftover a previous, interrupted run left behind.
+pub(crate) fn finish_rebuild(comfy_dir: &Path, retired: Option<PathBuf>) {
+ let sweep_dir = comfy_dir.to_path_buf();
+ std::thread::spawn(move || {
+ if let Some(retired) = retired {
+ if let Err(e) = std::fs::remove_dir_all(&retired) {
+ warn!(error = %e, folder = %retired.display(), "the retired venv could not be deleted");
}
- let sweep_dir = comfy_dir.to_path_buf();
- std::thread::spawn(move || {
- if let Err(e) = std::fs::remove_dir_all(&retired) {
- warn!(error = %e, folder = %retired.display(), "the retired venv could not be deleted");
- }
- sweep_retired_venvs(&sweep_dir);
- });
- Ok(())
}
- Err(rename_failed) => {
- // Windows refuses a rename while a process holds the directory
- // itself open or has its working directory in it. Fall back to
- // deleting the old venv in place, then moving the new
- // (already-verified) one over.
- warn!(error = %rename_failed, "old venv rename failed, deleting it in place before the swap");
- let _ = std::fs::remove_file(venv_python_path(comfy_dir));
- if let Err(e) = std::fs::remove_dir_all(venv_dir) {
- return Err(venv_removal_error(venv_dir, &e));
+ sweep_retired_venvs(&sweep_dir);
+ });
+}
+
+/// Runde 6, B9, "Wiederanlauf": if a previous rebuild died between
+/// `retire_for_rebuild` and the new venv passing verification (a crash, a
+/// power loss, the process being killed), the customer's ComfyUI folder can
+/// be left with a `venv.lu-old-*` sibling and NO working `venv` at all
+/// (`restore_after_failed_rebuild` never got to run). Called at the START of
+/// every Repair and Install run, before anything else touches the folder:
+/// if there is already a usable venv, this does nothing at all. If there is
+/// not, but a retired one exists, the NEWEST retired folder (the one this
+/// run's own interrupted attempt would have made) is restored to `venv`
+/// before the run continues; any OLDER retired or abandoned staging folder
+/// is swept away rather than restored, since it is a leftover from a run
+/// even earlier than the crash this is recovering from.
+pub(crate) fn restore_orphaned_venv_if_needed(comfy_dir: &Path) {
+ if venv_python_path(comfy_dir).exists() {
+ return;
+ }
+ let Ok(entries) = std::fs::read_dir(comfy_dir) else {
+ return;
+ };
+ let mut retired: Vec<(std::time::SystemTime, PathBuf)> = entries
+ .flatten()
+ .filter_map(|e| {
+ let path = e.path();
+ let name = path.file_name()?.to_str()?.to_string();
+ if !name.starts_with(RETIRED_VENV_PREFIX) || !path.is_dir() {
+ return None;
+ }
+ let modified = e.metadata().ok()?.modified().ok()?;
+ Some((modified, path))
+ })
+ .collect();
+ if !retired.is_empty() {
+ retired.sort_by_key(|(t, _)| *t);
+ if let Some((_, newest)) = retired.pop() {
+ let venv_dir = comfy_dir.join("venv");
+ if let Err(e) = std::fs::rename(&newest, &venv_dir) {
+ warn!(error = %e, folder = %newest.display(), "could not restore an orphaned venv left by an interrupted rebuild");
}
- std::fs::rename(staging_dir, venv_dir).map_err(|e| {
- format!(
- "The new environment was verified, but could not be swapped into place: {}. It \
- is still on disk at {}; rename that folder to \"venv\" manually to recover it.",
- venv_removal_error(staging_dir, &e),
- staging_dir.display(),
- )
- })
+ }
+ // Anything older is not restorable to a meaningful state: swept,
+ // not adopted.
+ for (_, leftover) in retired {
+ let _ = std::fs::remove_dir_all(&leftover);
}
}
+ // Always swept, even when there was no retired folder at all: a
+ // customer upgrading FROM the Runde 5 staging approach can still have a
+ // `venv.lu-new-*` leftover with nothing to restore it FROM, and that
+ // must not be left sitting there just because this run found no
+ // RETIRED_VENV_PREFIX folder to act on.
+ sweep_retired_venvs(comfy_dir);
}
/// Delete whatever [`retire_venv`] OR an interrupted staging build left
@@ -870,81 +966,340 @@ mod tests {
}
}
+ // ── Runde 6, BLOCKER B9: retire-then-build-at-final-name ───────────────
+ //
+ // Attrappen fuer die vom Auftrag verlangten Faelle: Erfolg,
+ // Fehlschlag im Bau, Fehlschlag in der Pruefung, Abbruch, Wiederanlauf,
+ // Umbenennen scheitert. Jede benutzt zwei simple Marker-Verzeichnisse
+ // statt echter venvs, so wie die Runde-5-Tests es schon taten; der reale
+ // Beweis mit echtem `python3 -m venv` steht getrennt unten.
+
+ fn marked_dir(path: &Path, marker: &str) {
+ std::fs::create_dir_all(path).unwrap();
+ std::fs::write(path.join("marker.txt"), marker.as_bytes()).unwrap();
+ }
+
+ fn retired_siblings(comfy: &Path) -> Vec<PathBuf> {
+ std::fs::read_dir(comfy)
+ .unwrap()
+ .flatten()
+ .map(|e| e.path())
+ .filter(|p| {
+ p.file_name()
+ .and_then(|n| n.to_str())
+ .is_some_and(|n| n.starts_with(RETIRED_VENV_PREFIX))
+ })
+ .collect()
+ }
+
+ #[test]
+ fn retire_for_rebuild_moves_the_old_venv_aside_and_frees_the_name() {
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ let venv_dir = comfy.join("venv");
+ marked_dir(&venv_dir, "old");
+
+ let retired = retire_for_rebuild(&venv_dir).expect("retire failed").expect("an old venv should have been reported");
+
+ assert!(!venv_dir.exists(), "venv is still there after retiring");
+ assert_eq!(std::fs::read(retired.join("marker.txt")).unwrap(), b"old");
+ }
+
+ #[test]
+ fn retire_for_rebuild_reports_nothing_when_there_is_no_old_venv() {
+ // A first install: nothing to retire, and nothing must be invented.
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ let venv_dir = comfy.join("venv");
+ assert_eq!(retire_for_rebuild(&venv_dir).unwrap(), None);
+ }
+
+ #[test]
+ fn erfolg_the_new_venv_stays_and_the_retired_old_one_is_swept_away() {
+ // Der Erfolgsfall: retire, "bauen" (Attrappe: der Aufrufer legt die
+ // neue venv direkt unter dem finalen Namen an), dann finish_rebuild.
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ let venv_dir = comfy.join("venv");
+ marked_dir(&venv_dir, "old");
+
+ let retired = retire_for_rebuild(&venv_dir).unwrap();
+ marked_dir(&venv_dir, "new"); // built directly at the final name
+ finish_rebuild(&comfy, retired);
+
+ // The delete runs on a background thread; give it a moment, the same
+ // way the rest of this file's swap tests always treated deletion as
+ // best-effort rather than synchronous.
+ for _ in 0..50 {
+ if retired_siblings(&comfy).is_empty() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ assert_eq!(std::fs::read(venv_dir.join("marker.txt")).unwrap(), b"new");
+ assert!(retired_siblings(&comfy).is_empty(), "the retired old venv was not cleared away");
+ }
+
#[test]
- fn swap_puts_the_new_venv_in_place_and_retires_the_old_one() {
- // B7(c) Verhaltenstest, Attrappe: two plain directories stand in for
- // the old and the new venv. What matters is not what pip or `python
- // -m venv` did to build them, only that the swap moves the RIGHT one
- // into `venv` and does not touch the other's own contents while doing
- // it.
+ fn fehlschlag_im_bau_restores_the_old_venv_when_the_new_one_never_got_built() {
+ // Der Bau selbst schlaegt fehl (z. B. `python -m venv` scheitert und
+ // raeumt sich, wie create_comfyui_venv es tut, selbst wieder ab): am
+ // finalen Pfad liegt gar nichts, nur die stillgelegte alte venv.
let tmp = tempfile::tempdir().unwrap();
let comfy = tmp.path().join("ComfyUI");
let venv_dir = comfy.join("venv");
- let staging_dir = comfy.join(format!("{STAGING_VENV_PREFIX}1"));
- std::fs::create_dir_all(&venv_dir).unwrap();
- std::fs::write(venv_dir.join("marker.txt"), b"old").unwrap();
- std::fs::create_dir_all(&staging_dir).unwrap();
- std::fs::write(staging_dir.join("marker.txt"), b"new").unwrap();
+ marked_dir(&venv_dir, "old");
- swap_in_new_venv(&comfy, &venv_dir, &staging_dir).expect("the swap failed");
+ let retired = retire_for_rebuild(&venv_dir).unwrap();
+ assert!(!venv_dir.exists(), "sanity: retiring did not clear the name");
+ // The build never produced anything at venv_dir at all.
+
+ restore_after_failed_rebuild(&comfy, &venv_dir, retired).expect("restore failed");
+
+ assert_eq!(std::fs::read(venv_dir.join("marker.txt")).unwrap(), b"old");
+ assert!(retired_siblings(&comfy).is_empty(), "a retired sibling is still lying around after the restore");
+ }
+
+ #[test]
+ fn fehlschlag_in_der_pruefung_discards_the_half_built_venv_and_restores_the_old_one() {
+ // Der Bau selbst lief durch, aber `verify_and_heal_environment`
+ // scheitert danach: am finalen Pfad liegt eine halb-fertige neue
+ // venv, die verworfen werden muss, waehrend die alte zurueckkommt.
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ let venv_dir = comfy.join("venv");
+ marked_dir(&venv_dir, "old");
+
+ let retired = retire_for_rebuild(&venv_dir).unwrap();
+ marked_dir(&venv_dir, "half-built-new");
+
+ restore_after_failed_rebuild(&comfy, &venv_dir, retired).expect("restore failed");
- assert!(venv_dir.is_dir(), "venv is gone after the swap");
assert_eq!(
std::fs::read(venv_dir.join("marker.txt")).unwrap(),
- b"new",
- "venv still holds the OLD environment after the swap"
+ b"old",
+ "the customer was left with the broken new venv instead of the working old one"
+ );
+ // The half-built venv is discarded on a background thread; give it a
+ // moment, same convention as the success test above.
+ for _ in 0..50 {
+ let leftover_discard = std::fs::read_dir(&comfy)
+ .unwrap()
+ .flatten()
+ .any(|e| e.file_name().to_str().is_some_and(|n| n.starts_with("venv.lu-failed-")));
+ if !leftover_discard {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ assert!(
+ std::fs::read_dir(&comfy)
+ .unwrap()
+ .flatten()
+ .all(|e| !e.file_name().to_str().is_some_and(|n| n.starts_with("venv.lu-failed-"))),
+ "the discarded half-built venv is still on disk"
);
- assert!(!staging_dir.exists(), "the staging folder was not consumed by the swap");
- // The old venv is retired, not deleted in line by this call (deletion
- // runs on its own thread), but it must not still be sitting at the
- // name a fresh repair, the launcher or autostart would read.
- let retired: Vec<_> = std::fs::read_dir(&comfy)
- .unwrap()
- .flatten()
- .filter(|e| {
- e.file_name()
- .to_str()
- .is_some_and(|n| n.starts_with(RETIRED_VENV_PREFIX))
- })
- .collect();
- assert!(!retired.is_empty(), "no trace of the old venv having been retired");
}
#[test]
- fn swap_leaves_the_old_venv_untouched_when_there_is_nothing_to_swap_in() {
- // Negativkontrolle: this is B7(c)'s whole point on its own. No
- // staging folder exists at all (the build never finished, or this is
- // a bug calling the swap too early), the rename must fail, and the
- // OLD venv must be exactly as it was, not retired, not half-renamed,
- // not gone. "Nie wieder: alte weg, neue scheitert."
+ fn abbruch_durch_den_nutzer_rolls_back_exactly_like_any_other_failure() {
+ // Ein Abbruch durch den Nutzer ist am Dateisystem nicht von einem
+ // Fehlschlag zu unterscheiden: beide rufen `restore_after_failed_rebuild`
+ // an genau derselben Stelle auf. Dieser Test haelt fest, dass ein
+ // Abbruch WAEHREND des Baus (halb-fertige neue venv liegt schon da)
+ // genauso sauber zurueckrollt wie ein regulaerer Fehlschlag.
let tmp = tempfile::tempdir().unwrap();
let comfy = tmp.path().join("ComfyUI");
let venv_dir = comfy.join("venv");
- let staging_dir = comfy.join(format!("{STAGING_VENV_PREFIX}1"));
- std::fs::create_dir_all(&venv_dir).unwrap();
- std::fs::write(venv_dir.join("marker.txt"), b"old").unwrap();
- // staging_dir is deliberately never created.
+ marked_dir(&venv_dir, "old");
- let err = swap_in_new_venv(&comfy, &venv_dir, &staging_dir)
- .expect_err("a swap with no staging venv to swap in must fail");
- assert!(!err.is_empty());
+ let retired = retire_for_rebuild(&venv_dir).unwrap();
+ marked_dir(&venv_dir, "half-built-when-cancelled");
+
+ restore_after_failed_rebuild(&comfy, &venv_dir, retired).expect("restore after cancel failed");
+
+ assert_eq!(std::fs::read(venv_dir.join("marker.txt")).unwrap(), b"old");
+ }
+
+ #[test]
+ fn restore_after_failed_rebuild_with_no_retired_venv_just_clears_the_half_built_one() {
+ // Negativkontrolle: ein Fehlschlag bei der ALLERERSTEN Installation
+ // (keine alte venv vorhanden, `retired` also `None`) darf nichts
+ // erfinden; es bleibt schlicht kein `venv` uebrig.
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ let venv_dir = comfy.join("venv");
+ marked_dir(&venv_dir, "half-built-first-install");
+
+ restore_after_failed_rebuild(&comfy, &venv_dir, None).expect("restore failed");
+
+ assert!(!venv_dir.exists(), "a first-install failure invented an old venv to restore");
+ }
+
+ #[test]
+ fn wiederanlauf_restores_the_newest_retired_venv_when_no_valid_venv_exists() {
+ // B9 "Wiederanlauf": ein Absturz zwischen retire_for_rebuild und dem
+ // Verifikationstor laesst eine stillgelegte alte venv und KEIN
+ // brauchbares `venv` zurueck. Der naechste Start von Repair/Install
+ // muss die alte zuerst wiederherstellen, nicht danebenstehen.
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ std::fs::create_dir_all(&comfy).unwrap();
+ let older = comfy.join(format!("{RETIRED_VENV_PREFIX}1"));
+ let newer = comfy.join(format!("{RETIRED_VENV_PREFIX}2"));
+ marked_dir(&older, "even-older-crash-leftover");
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ marked_dir(&newer, "the-one-this-crash-retired");
+
+ restore_orphaned_venv_if_needed(&comfy);
- assert!(venv_dir.is_dir(), "the old venv is gone after a failed swap");
assert_eq!(
- std::fs::read(venv_dir.join("marker.txt")).unwrap(),
- b"old",
- "the old venv was replaced even though the swap failed"
+ std::fs::read(comfy.join("venv").join("marker.txt")).unwrap(),
+ b"the-one-this-crash-retired",
+ "the newest retired venv (the one this crash actually retired) was not restored"
);
- let retired: Vec<_> = std::fs::read_dir(&comfy)
- .unwrap()
- .flatten()
- .filter(|e| {
- e.file_name()
- .to_str()
- .is_some_and(|n| n.starts_with(RETIRED_VENV_PREFIX))
- })
- .collect();
- assert!(retired.is_empty(), "the old venv was retired even though the swap never completed");
+ assert!(!older.exists(), "an older, unrelated retired venv was left instead of swept");
+ assert!(!newer.exists(), "the retired folder is still there after being restored");
+ }
+
+ #[test]
+ fn wiederanlauf_does_nothing_when_a_valid_venv_already_exists() {
+ // Negativkontrolle: ein GESUNDER Nutzer darf davon nichts merken. Ein
+ // brauchbares `venv` (mit Interpreter-Datei) neben einer retirierten
+ // venv ist der normale Zustand kurz vor deren Hintergrund-Loeschung,
+ // kein Absturz, und darf nicht angefasst werden.
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ let venv_dir = comfy.join("venv");
+ marked_dir(&venv_dir, "healthy-current-venv");
+ let interpreter = venv_python_path(&comfy);
+ std::fs::create_dir_all(interpreter.parent().unwrap()).unwrap();
+ std::fs::write(&interpreter, b"#!/bin/sh\n").unwrap();
+ let leftover = comfy.join(format!("{RETIRED_VENV_PREFIX}1"));
+ marked_dir(&leftover, "awaiting background deletion");
+
+ restore_orphaned_venv_if_needed(&comfy);
+
+ assert_eq!(std::fs::read(venv_dir.join("marker.txt")).unwrap(), b"healthy-current-venv");
+ // Whether the leftover survives this particular call is not the
+ // point (its own background delete handles that); the point is that
+ // `venv` itself must be completely untouched.
+ }
+
+ #[test]
+ fn wiederanlauf_sweeps_an_abandoned_staging_folder_from_an_older_lu_version() {
+ // Ein Kunde, der von einer aelteren LU-Version mit dem
+ // Staging-Ansatz (Runde 5) aktualisiert, kann noch einen
+ // `venv.lu-new-*`-Ordner liegen haben. Der neue Wiederanlauf muss
+ // ihn wegraeumen statt ihn stehen zu lassen.
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ std::fs::create_dir_all(&comfy).unwrap();
+ let abandoned = comfy.join(format!("{STAGING_VENV_PREFIX}1"));
+ marked_dir(&abandoned, "old-lu-version-staging-leftover");
+
+ restore_orphaned_venv_if_needed(&comfy);
+
+ assert!(!abandoned.exists(), "an old staging leftover from before this fix survived");
+ assert!(!comfy.join("venv").exists(), "a staging leftover must never be adopted as venv");
+ }
+
+ /// Umbenennen scheitert: what code 5 (Windows ERROR_ACCESS_DENIED, the
+ /// exact code a held-open ComfyUI process produces) and code 32 (Windows
+ /// ERROR_SHARING_VIOLATION) turn into. Runs on every platform because the
+ /// function's own `cfg!(target_os = "windows")` check is exercised either
+ /// way: off this platform it must fall through to the generic wording
+ /// instead of claiming a Windows-only cause.
+ #[test]
+ fn a_locked_old_venv_gets_a_close_comfyui_message_on_windows_only() {
+ let dir = PathBuf::from("C:\\Users\\ddrob\\ComfyUI\\venv");
+ for code in [5, 32] {
+ let e = std::io::Error::from_raw_os_error(code);
+ let msg = windows_lock_aware_retire_error(&dir, &e);
+ if cfg!(target_os = "windows") {
+ assert!(msg.contains("Close ComfyUI first"), "code {code}: {msg}");
+ assert!(msg.contains("Nothing was changed"), "code {code}: {msg}");
+ } else {
+ assert!(!msg.contains("Close ComfyUI first"), "code {code} on a non-Windows box: {msg}");
+ }
+ }
+ }
+
+ /// Negative control: an unrelated failure (permissions, a missing
+ /// folder) must not get the "close ComfyUI" wording on any platform.
+ #[test]
+ fn an_unrelated_retire_failure_keeps_the_generic_wording() {
+ let dir = PathBuf::from("/tmp/ComfyUI/venv");
+ let e = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied");
+ let msg = windows_lock_aware_retire_error(&dir, &e);
+ assert!(!msg.contains("Close ComfyUI first"), "{msg}");
+ assert!(msg.contains("Could not remove the old venv"), "{msg}");
+ }
+
+ #[test]
+ fn restoring_a_retired_venv_that_vanished_underneath_us_fails_loudly_instead_of_silently() {
+ // Umbenennen scheitert, zweite Form: `retired` existiert laut Aufruf,
+ // ist aber tatsaechlich weg (etwa von Hand geloescht zwischen dem
+ // Retire und dem Restore). Der Aufrufer darf nie glauben, die alte
+ // venv sei zurueck, wenn sie es nicht ist.
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ let venv_dir = comfy.join("venv");
+ let phantom_retired = comfy.join(format!("{RETIRED_VENV_PREFIX}vanished"));
+ // phantom_retired is deliberately never created.
+ std::fs::create_dir_all(&comfy).unwrap();
+
+ let err = restore_after_failed_rebuild(&comfy, &venv_dir, Some(phantom_retired))
+ .expect_err("restoring a vanished retired venv must not silently succeed");
+ assert!(!err.is_empty());
+ assert!(!venv_dir.exists(), "a venv was invented out of nothing");
+ }
+
+ /// Runde 6, B9's real proof: an ACTUAL `python3 -m venv`, not a marker
+ /// directory. Builds an "old" venv, retires it, builds the new one
+ /// directly at the final name the way the fixed `repair_comfyui_env`
+ /// now does, and reads `bin/pip`'s shebang back. Before this fix it
+ /// would have named a staging folder that no longer existed; after it,
+ /// it must name the FINAL path, because that is the only path the new
+ /// venv was ever built at.
+ #[test]
+ #[ignore]
+ fn a_rebuilt_venvs_scripts_point_at_the_final_path_not_a_staging_name() {
+ let Some(python) = probe_python() else {
+ eprintln!("no usable Python on this box, skipping the live venv checks");
+ return;
+ };
+ let tmp = tempfile::tempdir().unwrap();
+ let comfy = tmp.path().join("ComfyUI");
+ std::fs::create_dir_all(&comfy).unwrap();
+
+ let _old_py = create_comfyui_venv(&comfy, &python, None).expect("the 'old' venv build failed");
+ let venv_dir = comfy.join("venv");
+ let retired = retire_for_rebuild(&venv_dir).expect("retire failed");
+
+ let new_py = create_comfyui_venv(&comfy, &python, None).expect("the new venv build failed");
+ assert_eq!(new_py, venv_python_path(&comfy), "the new venv was not built at the final path");
+
+ #[cfg(not(windows))]
+ {
+ let pip_path = venv_dir.join("bin").join("pip");
+ let shebang = std::fs::read_to_string(&pip_path).expect("bin/pip is missing");
+ let final_venv = venv_dir.to_string_lossy().into_owned();
+ assert!(
+ shebang.contains(&final_venv),
+ "bin/pip's shebang does not name the final venv path.\nshebang: {shebang}\nfinal path: {final_venv}"
+ );
+ let activate = std::fs::read_to_string(venv_dir.join("bin").join("activate")).expect("bin/activate is missing");
+ assert!(
+ activate.contains(&final_venv),
+ "activate's VIRTUAL_ENV does not name the final venv path"
+ );
+ // And the working end-to-end proof, not just the text: pip itself runs.
+ let out = std::process::Command::new(pip_path).arg("--version").output().expect("pip did not even spawn");
+ assert!(out.status.success(), "bin/pip does not run: {}", String::from_utf8_lossy(&out.stderr));
+ }
+
+ finish_rebuild(&comfy, retired);
}
#[test]