diff --git a/apps/rocm/src/chat.rs b/apps/rocm/src/chat.rs index 8d05212d59..28cfca266d 100644 --- a/apps/rocm/src/chat.rs +++ b/apps/rocm/src/chat.rs @@ -32,6 +32,7 @@ use crate::managed_service_status::{ }; use crate::runtimes_cmd::render_runtimes_text; use crate::service_launch::is_loopback_host; +use crate::uninstall_plan::render_uninstall_dry_run; use crate::{ ChatInferenceParams, apply_app_path_env, build_codex_bridge_gpu_snapshot, build_codex_bridge_snapshot, builtin_codex_bridge_engine_inventory, cli_version_string, @@ -39,8 +40,8 @@ use crate::{ render_daemon_text, render_engine_inventory_text_with_paths, render_examine_text, render_examine_text_with_paths, render_logs_browser_text, render_logs_text, render_model_registry_verbose_text_with_context_and_host, render_service_logs_text, - render_services_text, render_setup_status_text, render_uninstall_dry_run, render_update_text, - service_model_names_match, therock_install_version_selector, validate_service_id, + render_services_text, render_setup_status_text, render_update_text, service_model_names_match, + therock_install_version_selector, validate_service_id, }; use crate::{chat_host_facts, comfyui, providers, therock}; use anyhow::{Context, Result, bail}; diff --git a/apps/rocm/src/deletion_properties.rs b/apps/rocm/src/deletion_properties.rs index ad27439f9b..f942794c75 100644 --- a/apps/rocm/src/deletion_properties.rs +++ b/apps/rocm/src/deletion_properties.rs @@ -4,7 +4,7 @@ //! Property tests for the recursive-deletion paths that are *not* the runtime //! install-root guard: `rocm uninstall` and `rocm storage remove-downloads`, -//! both of which end in [`crate::remove_path`]. +//! both of which end in [`crate::uninstall_plan::remove_path`]. //! //! The oracle is the real filesystem, not a restatement of the code's own path //! logic. Each case builds a sandbox tree (planted symlinks, sibling folders @@ -26,7 +26,7 @@ use proptest::prelude::*; use proptest::test_runner::{Config, TestCaseError, TestRunner}; use rocm_core::AppPaths; -use crate::{UninstallOptions, build_uninstall_plan, remove_path}; +use crate::uninstall_plan::{UninstallOptions, build_uninstall_plan, remove_path}; // --------------------------------------------------------------------------- // Sandbox + snapshot helpers (the oracle) @@ -669,7 +669,7 @@ fn uninstall_case( }; let plan = build_uninstall_plan(&paths, &options) .map_err(|error| TestCaseError::fail(format!("plan failed: {error:#}")))?; - let rendered = crate::render_uninstall_plan( + let rendered = crate::uninstall_plan::render_uninstall_plan( &plan, &UninstallOptions { dry_run: true, diff --git a/apps/rocm/src/main.rs b/apps/rocm/src/main.rs index 8f989a8fcc..b645cd3461 100644 --- a/apps/rocm/src/main.rs +++ b/apps/rocm/src/main.rs @@ -42,6 +42,7 @@ mod storage; mod test_support; mod therock; mod uninstall; +mod uninstall_plan; // Per-command handlers mechanically relocated into modules — fns, plus the // types (e.g. `ServeArgs`, driver-plan types) that moved with their cluster. @@ -90,6 +91,7 @@ use crate::service_launch::{ managed_service_process_command, }; use crate::uninstall::uninstall; +use crate::uninstall_plan::UninstallOptions; use anyhow::{Context, Result, bail}; use clap::{CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum}; @@ -8163,462 +8165,6 @@ pub(crate) fn render_daemon_text(paths: &AppPaths, config: &RocmCliConfig) -> St output } -#[derive(Debug, Clone, Default)] -struct UninstallOptions { - yes: bool, - dry_run: bool, - keep_binaries: bool, - keep_config: bool, - keep_data: bool, - keep_cache: bool, - force_dev_binaries: bool, -} - -#[derive(Debug, Clone)] -struct UninstallPlanEntry { - kind: &'static str, - path: PathBuf, -} - -#[derive(Debug, Clone, Default)] -struct UninstallPlan { - actions: Vec, - skipped: Vec, - warnings: Vec, - /// Installer PATH changes `rocm uninstall` undoes. - path_edits: Vec, - /// The installer's record of its PATH change, removed once that change is - /// undone. - path_record: Option, - /// The running executable, on Windows, which is deleted as the command exits. - self_delete: Option, -} - -fn build_uninstall_plan(paths: &AppPaths, options: &UninstallOptions) -> Result { - let mut plan = UninstallPlan::default(); - - plan_installed_binaries( - &mut plan, - options, - || daemon_binary_path().context("failed to discover current rocm executable"), - rocm_core::runtime_home_dir().as_deref(), - )?; - - for (keep, kind, path) in [ - (options.keep_config, "config", paths.config_dir.clone()), - (options.keep_data, "data", paths.data_dir.clone()), - (options.keep_cache, "cache", paths.cache_dir.clone()), - ] { - if keep { - plan.skipped - .push(format!("{kind} removal disabled by command line flag")); - continue; - } - // Planned under the spelling `remove_path` acts on, so the review names - // the entry that is actually removed, and `dir/` and `dir` dedup to one - // line. Existence is the entry's own, not its target's: a dangling link - // is listed and then really removed, instead of reported as absent. - // A failed check is not an absence either: it fails the plan, so the - // uninstall stops before removing anything instead of leaving a folder - // that may still be on disk out of the review. - match existing_entry(&path) - .with_context(|| format!("failed to check the {kind} folder {}", path.display()))? - { - Some((entry, _)) => plan.actions.push(UninstallPlanEntry { kind, path: entry }), - None => plan - .skipped - .push(format!("{kind} path not present: {}", path.display())), - } - } - - for note in shared_cache_notes(paths) { - plan.warnings.push(note); - } - - let managed_services = load_managed_services(paths).unwrap_or_default(); - if !managed_services.is_empty() { - plan.warnings.push(format!( - "{} managed service record(s) exist under {}; background processes are not stopped automatically in this pass", - managed_services.len(), - paths.services_dir().display() - )); - } - - // Remote sessions are worse than local ones to drop silently. The model runs - // on someone else's machine and its endpoint is published there, so removing - // the record here does not stop either — it only destroys the last thing that - // knew they existed. Name them and the command that tears them down properly. - // - // A read that fails is reported, not defaulted away. `load_all` already warns - // past an individual unreadable record and keeps going, so an `Err` here is a - // directory-level I/O failure, and a missing directory is `Ok`. Taking the - // default would state "there are none" on the one path where we do not know — - // and this plan goes on to delete the data directory those records live in, - // so the warning that something is still published elsewhere would be lost at - // exactly the moment it was the last copy. - let remote_sessions = match remote::session::load_all(paths) { - Ok(sessions) => sessions, - Err(error) => { - plan.warnings.push(format!( - "could not read the remote session records under {}: {error:#}\n\ - This pass cannot tell whether models are still running on other machines with \ - their endpoints published. Check with `rocm remote status` before continuing.", - paths.remote_sessions_dir().display() - )); - Vec::new() - } - }; - if !remote_sessions.is_empty() { - plan.warnings.push(format!( - "{} remote session record(s) exist under {}; their models keep running on the \ - remote machines and their endpoints stay published. Removing these records only \ - loses track of them - run `rocm remote stop ` for each first: {}", - remote_sessions.len(), - paths.remote_sessions_dir().display(), - remote_sessions - .iter() - .map(|session| session.session_id.as_str()) - .collect::>() - .join(", ") - )); - } - - plan.actions - .sort_by(|left, right| left.path.cmp(&right.path)); - plan.actions.dedup_by(|left, right| left.path == right.path); - Ok(plan) -} - -/// Plan removing the installed binaries beside the running one, which -/// `current_exe` names, and undoing the installer's PATH change for their -/// folder. `--keep-binaries` keeps both, and so does a cargo build's folder. -fn plan_installed_binaries( - plan: &mut UninstallPlan, - options: &UninstallOptions, - current_exe: impl FnOnce() -> Result, - home: Option<&Path>, -) -> Result<()> { - if options.keep_binaries { - // The PATH change only serves the binaries, so it stays with them. - plan.skipped.push( - "binary removal disabled by --keep-binaries, so any PATH change the installer made \ - stays too" - .to_owned(), - ); - return Ok(()); - } - let current_exe = current_exe()?; - if is_dev_binary_layout(¤t_exe) && !options.force_dev_binaries { - plan.skipped.push(format!( - "binary removal skipped because {} looks like a cargo target build; pass --force-dev-binaries to remove sibling debug/release binaries", - current_exe.display() - )); - return Ok(()); - } - let binaries = collect_installed_binary_candidates(¤t_exe)?; - for path in &binaries { - // Windows will not unlink a running image; it is deleted as the - // command exits instead. - if is_running_executable(path, ¤t_exe, cfg!(windows)) { - plan.self_delete = Some(path.clone()); - continue; - } - // The PATH record goes only once its change is undone; see - // `uninstall::plan_path_edits`. - if path.file_name().and_then(|name| name.to_str()) == Some(uninstall::PATH_EDIT_RECORD) { - continue; - } - plan.actions.push(UninstallPlanEntry { - kind: "binary", - path: path.clone(), - }); - } - if let Some(bin_dir) = current_exe.parent() { - uninstall::plan_path_edits(plan, bin_dir, &binaries, home); - } - Ok(()) -} - -/// Whether `path`, an entry of the running executable's folder, is the running -/// executable itself, which only Windows has to treat specially. Windows names -/// are case-insensitive, and the running image may report its own name in -/// another case, or in its 8.3 short form (`ROCM.EXE`), than the folder listing -/// does; missing it would plan an ordinary removal that Windows refuses. -fn is_running_executable(path: &Path, current_exe: &Path, windows: bool) -> bool { - if !windows { - return false; - } - path == current_exe - || (path.parent() == current_exe.parent() - && path - .file_name() - .zip(current_exe.file_name()) - .is_some_and(|(name, exe)| { - name.to_string_lossy() - .eq_ignore_ascii_case(&exe.to_string_lossy()) - })) -} - -pub(crate) fn render_uninstall_dry_run(paths: &AppPaths) -> Result { - let options = UninstallOptions { - dry_run: true, - ..UninstallOptions::default() - }; - let plan = build_uninstall_plan(paths, &options)?; - Ok(render_uninstall_plan(&plan, &options)) -} - -fn render_uninstall_plan(plan: &UninstallPlan, options: &UninstallOptions) -> String { - let mut output = String::new(); - let _ = writeln!(output, "Uninstall review"); - let _ = writeln!(output); - let removals = uninstall::removal_count(plan); - if uninstall::plan_is_empty(plan) { - let _ = writeln!(output, "Nothing managed by rocm-cli would be removed."); - } else if removals > 0 { - let _ = writeln!(output, "{removals} item(s) would be removed:"); - for entry in &plan.actions { - let _ = writeln!(output, " - {}: {}", entry.kind, entry.path.display()); - } - } - uninstall::render_extra_plan(&mut output, plan); - if !plan.warnings.is_empty() { - let _ = writeln!(output); - let _ = writeln!(output, "Please review:"); - } - for warning in &plan.warnings { - let _ = writeln!(output, " - {warning}"); - } - if !plan.skipped.is_empty() { - let _ = writeln!(output); - let _ = writeln!(output, "Left alone:"); - } - for skipped in &plan.skipped { - let _ = writeln!(output, " - {skipped}"); - } - if options.dry_run { - let _ = writeln!(output); - let _ = writeln!(output, "Choose Review uninstall to approve removal."); - } - output -} - -/// Caches that ROCm CLI causes to be filled but does not own, so uninstall -/// leaves them in place. -/// -/// These are usually the largest things on disk after an install, so a plan -/// that stays silent about them reads as a clean slate it does not deliver. -/// Only paths that exist and sit outside everything already being removed are -/// reported, so the notes stay truthful as caches move under the data -/// directory. -fn shared_cache_notes(paths: &AppPaths) -> Vec { - let removed_roots = [ - paths.config_dir.clone(), - paths.data_dir.clone(), - paths.cache_dir.clone(), - ]; - shared_cache_notes_for(&removed_roots, &shared_cache_candidates()) -} - -/// The pure part of [`shared_cache_notes`], so the filtering is testable without -/// depending on the caller's real environment. -fn shared_cache_notes_for( - removed_roots: &[PathBuf], - candidates: &[(PathBuf, &'static str)], -) -> Vec { - candidates - .iter() - .filter(|(path, _)| path.exists()) - .filter(|(path, _)| !removed_roots.iter().any(|root| path.starts_with(root))) - .map(|(path, description)| format!("{description} not removed: {}", path.display())) - .collect() -} - -/// The shared caches worth reporting, with why each is left alone. -fn shared_cache_candidates() -> Vec<(PathBuf, &'static str)> { - let mut candidates = Vec::new(); - - // `uv` writes to `UV_CACHE_DIR` when set, otherwise its own default. Read it - // rather than assuming a location, so this stays correct wherever the cache - // has been pointed. - let uv_cache = env_path("UV_CACHE_DIR") - .or_else(|| rocm_core::runtime_home_dir().map(|home| home.join(".cache").join("uv"))); - if let Some(path) = uv_cache { - candidates.push(( - path, - "the uv package cache is shared with other uv projects on this computer and is", - )); - } - - let hf_cache = env_path("HF_HOME") - .map(|home| home.join("hub")) - .or_else(|| env_path("HUGGINGFACE_HUB_CACHE")) - .or_else(|| { - rocm_core::runtime_home_dir() - .map(|home| home.join(".cache").join("huggingface").join("hub")) - }); - if let Some(path) = hf_cache { - candidates.push(( - path, - "downloaded model files are slow to fetch again and may include your own, so they are", - )); - } - - candidates -} - -fn env_path(name: &str) -> Option { - std::env::var_os(name) - .filter(|value| !value.is_empty()) - .map(PathBuf::from) -} - -fn confirm_uninstall() -> Result { - print!("Proceed with uninstall? [y/N]: "); - io::stdout() - .flush() - .context("failed to flush uninstall prompt")?; - let mut response = String::new(); - io::stdin() - .read_line(&mut response) - .context("failed to read uninstall confirmation")?; - let normalized = response.trim().to_ascii_lowercase(); - Ok(matches!(normalized.as_str(), "y" | "yes")) -} - -fn collect_installed_binary_candidates(current_exe: &Path) -> Result> { - let binary_dir = current_exe - .parent() - .context("current executable has no parent directory")?; - let mut binaries = Vec::new(); - for entry in fs::read_dir(binary_dir) - .with_context(|| format!("failed to read {}", binary_dir.display()))? - { - let entry = entry?; - let path = entry.path(); - let Some(name) = path.file_name().and_then(|value| value.to_str()) else { - continue; - }; - if !path.is_file() { - continue; - } - if is_rocm_install_entry_name(name) { - binaries.push(path); - } - } - binaries.sort(); - Ok(binaries) -} - -fn is_rocm_install_entry_name(name: &str) -> bool { - if name == ".rocm-cli-manifest" || name == uninstall::PATH_EDIT_RECORD { - return true; - } - let normalized = name.strip_suffix(".exe").unwrap_or(name); - normalized == "rocm" - || normalized == "rocmd" - || normalized == "rocm-codex" - || normalized.starts_with("rocm-engine-") -} - -fn is_dev_binary_layout(path: &Path) -> bool { - let Some(parent) = path.parent() else { - return false; - }; - let Some(parent_name) = parent.file_name().and_then(|value| value.to_str()) else { - return false; - }; - if parent_name != "debug" && parent_name != "release" { - return false; - } - parent - .parent() - .and_then(|value| value.file_name()) - .and_then(|value| value.to_str()) - == Some("target") -} - -/// `path` respelled so it names the final entry itself. -/// -/// A trailing separator (`link/`) or a trailing `.` (`link/.`) makes the kernel -/// resolve a final symlink, so `symlink_metadata` reports the link's *target* -/// directory and a recursive delete walks into it. Rebuilding the path from its -/// components drops exactly those spellings (plus repeated separators and -/// interior `.`), none of which otherwise change which entry is named. `..` is -/// kept: dropping it lexically would change the meaning through a link. -fn entry_path(path: &Path) -> PathBuf { - path.components().collect() -} - -/// Does `path`'s text end in a separator or a final `.` (`x/`, `x/.`)? The -/// kernel only lets such a spelling name a directory, so `notes.txt/` names -/// nothing even though `notes.txt` exists. -fn spelled_as_directory(path: &Path) -> bool { - let text = path.as_os_str().as_encoded_bytes(); - let is_separator = |byte: u8| std::path::is_separator(char::from(byte)); - match text { - [.., last] if is_separator(*last) => true, - [.., before, b'.'] => is_separator(*before), - _ => false, - } -} - -/// The entry `path` names, as [`entry_path`] spells it, with its own -/// (link-not-followed) metadata — or `None` when nothing is there. -/// -/// A spelling that can only name a directory (see [`spelled_as_directory`]) -/// names nothing when the entry is a regular file, so that counts as absent -/// rather than letting the respelling turn `notes.txt/` into `notes.txt`. A -/// symlink is still the entry: it is what [`remove_path`] unlinks. -fn existing_entry(path: &Path) -> io::Result> { - let entry = entry_path(path); - // Not `path.exists()`: that follows links, so a dangling link would read as - // already gone, be skipped, and still be reported as removed by the caller. - // "Not a directory" means a folder on the way is really a file (as in - // `notes.txt/../x`), so the path names nothing, the same as "not found". - // Any other failure is a real error, not an absence. - let metadata = match fs::symlink_metadata(&entry) { - Ok(metadata) => metadata, - Err(error) - if matches!( - error.kind(), - io::ErrorKind::NotFound | io::ErrorKind::NotADirectory - ) => - { - return Ok(None); - } - Err(error) => return Err(error), - }; - if spelled_as_directory(path) && !metadata.is_dir() && !metadata.file_type().is_symlink() { - return Ok(None); - } - Ok(Some((entry, metadata))) -} - -/// Remove the entry `path` names: a file or symlink is unlinked (never -/// followed, however `path` is spelled), a real directory is removed -/// recursively, and an entry that is already gone is a no-op. -/// -/// Normalizing here rather than only at plan time covers every caller — -/// `rocm uninstall` and `rocm storage remove-downloads` — whatever spelling -/// their plan carries. -fn remove_path(path: &Path) -> Result<()> { - let Some((path, metadata)) = - existing_entry(path).with_context(|| format!("failed to stat {}", path.display()))? - else { - return Ok(()); - }; - let path = path.as_path(); - if metadata.file_type().is_symlink() || metadata.is_file() { - fs::remove_file(path).with_context(|| format!("failed to remove {}", path.display()))?; - } else if metadata.is_dir() { - fs::remove_dir_all(path).with_context(|| format!("failed to remove {}", path.display()))?; - } else { - bail!("unsupported filesystem entry for {}", path.display()); - } - Ok(()) -} - pub(crate) const fn engine_inventory() -> &'static [(&'static str, &'static str)] { &[ ( @@ -10605,64 +10151,6 @@ pub(crate) mod tests { assert_eq!(super::exit_code_for(result), ExitCode::from(2)); } - /// A cache that has moved inside a directory uninstall already removes must - /// not be reported as "not removed" — the note would be false. - #[test] - fn shared_cache_notes_skip_paths_already_being_removed() { - let root = std::env::temp_dir().join(format!("rocm-shared-cache-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - let data = root.join("data"); - let inside = data.join("uv-cache"); - std::fs::create_dir_all(&inside).unwrap(); - - let notes = super::shared_cache_notes_for( - &[root.join("config"), data, root.join("cache")], - &[(inside, "the uv package cache")], - ); - - assert!( - notes.is_empty(), - "a cache inside a removed directory must not be reported: {notes:?}" - ); - - let _ = std::fs::remove_dir_all(&root); - } - - /// A cache that exists outside everything being removed is reported, with - /// its path, so the plan does not imply a clean slate it will not deliver. - #[test] - fn shared_cache_notes_report_paths_left_behind() { - let root = std::env::temp_dir().join(format!("rocm-shared-out-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - let outside = root.join("elsewhere").join("uv"); - std::fs::create_dir_all(&outside).unwrap(); - - let notes = super::shared_cache_notes_for( - &[root.join("data")], - &[(outside.clone(), "the uv package cache")], - ); - - assert_eq!(notes.len(), 1, "{notes:?}"); - assert!(notes[0].contains("not removed"), "{notes:?}"); - assert!( - notes[0].contains(&outside.display().to_string()), - "{notes:?}" - ); - - let _ = std::fs::remove_dir_all(&root); - } - - /// A cache that does not exist is not worth mentioning. - #[test] - fn shared_cache_notes_ignore_missing_paths() { - let missing = std::env::temp_dir().join("rocm-definitely-not-here-12345"); - let notes = super::shared_cache_notes_for( - &[std::env::temp_dir()], - &[(missing, "the uv package cache")], - ); - assert!(notes.is_empty(), "{notes:?}"); - } - use super::*; use serde_json::json; @@ -12227,12 +11715,6 @@ pub(crate) mod tests { ); } - #[test] - fn uninstall_binary_matcher_includes_packaged_codex_binary() { - assert!(is_rocm_install_entry_name("rocm-codex")); - assert!(is_rocm_install_entry_name("rocm-codex.exe")); - } - #[test] fn freeform_invocation_supports_leading_yes_for_natural_language_only() { let invocation = parse_freeform_invocation(&[ @@ -14229,70 +13711,6 @@ pub(crate) mod tests { Ok(()) } - /// `rocm uninstall`'s review warns that a remote session keeps running on - /// someone else's machine, and names the command that stops it properly. - /// - /// Nothing exercised that warning before: no test planted a remote session - /// record, so the whole sentence -- including the ASCII punctuation this - /// change put in it (ROCMAI-543) -- shipped uncovered. The remediation is - /// asserted alongside the encoding because a warning that stops naming - /// `rocm remote stop` leaves the user with no way to act on it. - #[test] - fn uninstall_warns_about_remote_sessions_in_ascii_and_names_the_stop_command() -> Result<()> { - let (root, paths) = test_paths("uninstall-remote-session-warning"); - paths.ensure()?; - let session = crate::remote::session::RemoteSessionRecord { - session_id: crate::remote::session::RemoteSessionRecord::id_for("dev-box", 8000), - target: "dev-box".to_owned(), - peer_host: "dev-box".to_owned(), - ssh_port: None, - model: "qwen".to_owned(), - remote_service_id: "svc-remote".to_owned(), - remote_cli: "rocm".to_owned(), - remote_port: 8000, - tailnet_port: 8000, - base_url: "http://dev-box:8000/v1".to_owned(), - created_at_unix_ms: 1, - }; - session.write(&paths)?; - - // `keep_binaries` so the plan never reaches outside the sandbox: the - // binary paths are the host's real ones and have nothing to do with - // this warning. - let options = UninstallOptions { - dry_run: true, - keep_binaries: true, - ..UninstallOptions::default() - }; - let plan = build_uninstall_plan(&paths, &options); - let _ = fs::remove_dir_all(&root); - let plan = plan?; - - let warning = plan - .warnings - .iter() - .find(|warning| warning.contains("remote session record(s)")) - .unwrap_or_else(|| { - panic!("a planted remote session must be warned about: {plan:#?}"); - }); - assert!( - warning.contains(&session.session_id), - "the warning must name the session it found: {warning}" - ); - assert!( - warning.contains("rocm remote stop "), - "the warning must name the command that stops the remote model: {warning}" - ); - // ROCMAI-543: printed verbatim by `render_uninstall_plan`, so non-ASCII - // punctuation here renders as mojibake like "ΓÇö" on a Windows console - // using the OEM code page. - assert!( - warning.is_ascii(), - "the remote-session warning must be ASCII-only (ROCMAI-543): {warning}" - ); - Ok(()) - } - /// A file `prune` cannot delete must be *reported*, not swallowed and not /// propagated: the plan, the per-record progress and the audit event all /// have to survive it, because a destructive command that loses its own diff --git a/apps/rocm/src/runtimes_cmd.rs b/apps/rocm/src/runtimes_cmd.rs index 4c74b60aac..120ab4dd00 100644 --- a/apps/rocm/src/runtimes_cmd.rs +++ b/apps/rocm/src/runtimes_cmd.rs @@ -35,9 +35,9 @@ use rocm_core::{ use serde::{Deserialize, Serialize}; use crate::therock; +use crate::uninstall_plan::confirm_uninstall; use crate::{ - ROLLBACK_RECOVERY_HINT, RuntimesCommand, cli_report, confirm_uninstall, record_cli_audit_event, - runtime_services, + ROLLBACK_RECOVERY_HINT, RuntimesCommand, cli_report, record_cli_audit_event, runtime_services, }; /// Refuse `--restart-services` without `--yes`, naming the command the user diff --git a/apps/rocm/src/storage.rs b/apps/rocm/src/storage.rs index 433da34717..b6d0b26f4b 100644 --- a/apps/rocm/src/storage.rs +++ b/apps/rocm/src/storage.rs @@ -30,10 +30,8 @@ use crate::runtimes_cmd::{ ActiveRuntimeMarker, InstallRootDecision, active_runtime_marker_path, should_remove_runtime_install_root, }; -use crate::{ - StorageCommand, UninstallPlan, UninstallPlanEntry, confirm_uninstall, format_bytes, - remove_path, therock, -}; +use crate::uninstall_plan::{UninstallPlan, UninstallPlanEntry, confirm_uninstall, remove_path}; +use crate::{StorageCommand, format_bytes, therock}; /// Recent installs kept per retention bucket by default (see /// [`retention_group`]): the one in use plus one rollback target. This is the diff --git a/apps/rocm/src/uninstall.rs b/apps/rocm/src/uninstall.rs index 7b8c7352d3..8c32f9b7bd 100644 --- a/apps/rocm/src/uninstall.rs +++ b/apps/rocm/src/uninstall.rs @@ -4,9 +4,9 @@ //! `rocm uninstall` command handler. //! -//! The plan itself is built by `build_uninstall_plan` in the crate root, which -//! `rocm storage` shares the plan and removal shape with. This module owns what -//! only uninstall does on top of removing files: +//! The plan itself is built by `build_uninstall_plan` in `uninstall_plan.rs`, +//! which `rocm storage` shares the plan and removal shape with. This module +//! owns what only uninstall does on top of removing files: //! //! - undoing the PATH change the installer recorded making; //! - deleting the running `rocm.exe` on Windows, which cannot unlink itself. @@ -20,7 +20,7 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail}; use rocm_core::{AppPaths, interactive_terminal}; -use crate::{ +use crate::uninstall_plan::{ UninstallOptions, UninstallPlan, build_uninstall_plan, confirm_uninstall, is_rocm_install_entry_name, remove_path, render_uninstall_plan, }; @@ -857,18 +857,6 @@ mod tests { assert!(plan_is_empty(&UninstallPlan::default())); } - #[test] - fn the_running_executable_is_matched_whatever_case_windows_reports_it_in() { - let exe = Path::new(r"C:\Users\me\.local\bin\rocm.exe"); - let listed = Path::new(r"C:\Users\me\.local\bin\ROCM.EXE"); - assert!(crate::is_running_executable(listed, exe, true)); - assert!(crate::is_running_executable(exe, exe, true)); - let rocmd = Path::new(r"C:\Users\me\.local\bin\rocmd.exe"); - assert!(!crate::is_running_executable(rocmd, exe, true)); - // Elsewhere the running binary is unlinked like any other. - assert!(!crate::is_running_executable(exe, exe, false)); - } - #[cfg(unix)] mod plan { use super::*; @@ -927,7 +915,7 @@ mod tests { plan.actions = layout .removed .iter() - .map(|path| crate::UninstallPlanEntry { + .map(|path| crate::uninstall_plan::UninstallPlanEntry { kind: "binary", path: path.clone(), }) @@ -946,7 +934,7 @@ mod tests { fs::write(config.join("config.json"), "{}")?; plan.actions.insert( 0, - crate::UninstallPlanEntry { + crate::uninstall_plan::UninstallPlanEntry { kind: "config", path: config.clone(), }, @@ -1024,10 +1012,11 @@ mod tests { let (mut plan, config) = with_config(&layout, with_binaries(&layout, plan_for(&layout)))?; // A name too long for any filesystem fails to remove, even for root. - plan.actions.push(crate::UninstallPlanEntry { - kind: "binary", - path: layout.bin.join("x".repeat(300)), - }); + plan.actions + .push(crate::uninstall_plan::UninstallPlanEntry { + kind: "binary", + path: layout.bin.join("x".repeat(300)), + }); let (lines, result) = run(&plan); assert!(result.is_err(), "the last removal fails: {lines:?}"); @@ -1269,7 +1258,7 @@ mod tests { keep_binaries, ..UninstallOptions::default() }; - crate::plan_installed_binaries( + crate::uninstall_plan::plan_installed_binaries( &mut plan, &options, || Ok(layout.removed[0].clone()), diff --git a/apps/rocm/src/uninstall_plan.rs b/apps/rocm/src/uninstall_plan.rs new file mode 100644 index 0000000000..996a201d3c --- /dev/null +++ b/apps/rocm/src/uninstall_plan.rs @@ -0,0 +1,659 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. +// +// SPDX-License-Identifier: MIT + +//! The uninstall plan: what would be removed, how that plan is rendered for +//! review, and the filesystem-removal primitive used to carry it out. +//! +//! Mechanically relocated from `main.rs` with no behavior change — Phase 6f +//! (ROCMAI-212) of the `main.rs` modularization (see `docs/architecture.md`). +//! `dispatch()`'s call sites are unaffected: none of this module's functions +//! are called directly from `dispatch()`. +//! +//! This is deliberately a separate file from `uninstall.rs`, not folded into +//! it: `uninstall.rs` owns only what `rocm uninstall` itself does on top of +//! removing files — undoing the installer's PATH change and deleting the +//! running executable on Windows, which cannot unlink itself. `storage.rs` +//! builds and renders a removal plan of its own (`rocm storage +//! remove-downloads`) and reuses this module's plan type and its +//! file-removal helpers to do it, so keeping them in `uninstall.rs` would +//! make `storage.rs` depend on a module whose name and doc comment both +//! describe the `uninstall` command's own, exclusive logic. +//! +//! This module owns: the plan types (`UninstallOptions`, `UninstallPlan`, +//! `UninstallPlanEntry`), building the plan (`build_uninstall_plan`, +//! `plan_installed_binaries`, and the installed-binary/shared-cache +//! discovery helpers behind them), rendering it (`render_uninstall_dry_run`, +//! `render_uninstall_plan`), the `[y/N]` confirmation prompt +//! (`confirm_uninstall`), and the filesystem removal primitive both +//! `uninstall.rs` and `storage.rs` call to carry a plan out (`remove_path`, +//! and the entry-resolution helpers behind it). `uninstall.rs` calls into it +//! for `UninstallOptions`/`UninstallPlan`/`build_uninstall_plan`/ +//! `confirm_uninstall`/`is_rocm_install_entry_name`/`remove_path`/ +//! `render_uninstall_plan`; `storage.rs` calls into it for +//! `UninstallPlan`/`UninstallPlanEntry`/`confirm_uninstall`; `runtimes_cmd.rs` +//! calls into it for `confirm_uninstall` (the same `[y/N]` prompt, reused for +//! `rocm runtimes uninstall`); `chat.rs` calls into it for +//! `render_uninstall_dry_run` (the deterministic uninstall-preview tool +//! result); `deletion_properties.rs`'s recursive-deletion property tests call +//! into it for `UninstallOptions`/`build_uninstall_plan`/`remove_path`/ +//! `render_uninstall_plan`. + +use std::fmt::Write as _; +use std::fs; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use rocm_core::{AppPaths, daemon_binary_path}; + +use crate::managed_service_status::load_managed_services; +use crate::{remote, uninstall}; + +#[derive(Debug, Clone, Default)] +pub(crate) struct UninstallOptions { + pub(crate) yes: bool, + pub(crate) dry_run: bool, + pub(crate) keep_binaries: bool, + pub(crate) keep_config: bool, + pub(crate) keep_data: bool, + pub(crate) keep_cache: bool, + pub(crate) force_dev_binaries: bool, +} + +#[derive(Debug, Clone)] +pub(crate) struct UninstallPlanEntry { + pub(crate) kind: &'static str, + pub(crate) path: PathBuf, +} + +#[derive(Debug, Clone, Default)] +pub(crate) struct UninstallPlan { + pub(crate) actions: Vec, + pub(crate) skipped: Vec, + pub(crate) warnings: Vec, + /// Installer PATH changes `rocm uninstall` undoes. + pub(crate) path_edits: Vec, + /// The installer's record of its PATH change, removed once that change is + /// undone. + pub(crate) path_record: Option, + /// The running executable, on Windows, which is deleted as the command exits. + pub(crate) self_delete: Option, +} + +pub(crate) fn build_uninstall_plan( + paths: &AppPaths, + options: &UninstallOptions, +) -> Result { + let mut plan = UninstallPlan::default(); + + plan_installed_binaries( + &mut plan, + options, + || daemon_binary_path().context("failed to discover current rocm executable"), + rocm_core::runtime_home_dir().as_deref(), + )?; + + for (keep, kind, path) in [ + (options.keep_config, "config", paths.config_dir.clone()), + (options.keep_data, "data", paths.data_dir.clone()), + (options.keep_cache, "cache", paths.cache_dir.clone()), + ] { + if keep { + plan.skipped + .push(format!("{kind} removal disabled by command line flag")); + continue; + } + // Planned under the spelling `remove_path` acts on, so the review names + // the entry that is actually removed, and `dir/` and `dir` dedup to one + // line. Existence is the entry's own, not its target's: a dangling link + // is listed and then really removed, instead of reported as absent. + // A failed check is not an absence either: it fails the plan, so the + // uninstall stops before removing anything instead of leaving a folder + // that may still be on disk out of the review. + match existing_entry(&path) + .with_context(|| format!("failed to check the {kind} folder {}", path.display()))? + { + Some((entry, _)) => plan.actions.push(UninstallPlanEntry { kind, path: entry }), + None => plan + .skipped + .push(format!("{kind} path not present: {}", path.display())), + } + } + + for note in shared_cache_notes(paths) { + plan.warnings.push(note); + } + + let managed_services = load_managed_services(paths).unwrap_or_default(); + if !managed_services.is_empty() { + plan.warnings.push(format!( + "{} managed service record(s) exist under {}; background processes are not stopped automatically in this pass", + managed_services.len(), + paths.services_dir().display() + )); + } + + // Remote sessions are worse than local ones to drop silently. The model runs + // on someone else's machine and its endpoint is published there, so removing + // the record here does not stop either — it only destroys the last thing that + // knew they existed. Name them and the command that tears them down properly. + // + // A read that fails is reported, not defaulted away. `load_all` already warns + // past an individual unreadable record and keeps going, so an `Err` here is a + // directory-level I/O failure, and a missing directory is `Ok`. Taking the + // default would state "there are none" on the one path where we do not know — + // and this plan goes on to delete the data directory those records live in, + // so the warning that something is still published elsewhere would be lost at + // exactly the moment it was the last copy. + let remote_sessions = match remote::session::load_all(paths) { + Ok(sessions) => sessions, + Err(error) => { + plan.warnings.push(format!( + "could not read the remote session records under {}: {error:#}\n\ + This pass cannot tell whether models are still running on other machines with \ + their endpoints published. Check with `rocm remote status` before continuing.", + paths.remote_sessions_dir().display() + )); + Vec::new() + } + }; + if !remote_sessions.is_empty() { + plan.warnings.push(format!( + "{} remote session record(s) exist under {}; their models keep running on the \ + remote machines and their endpoints stay published. Removing these records only \ + loses track of them - run `rocm remote stop ` for each first: {}", + remote_sessions.len(), + paths.remote_sessions_dir().display(), + remote_sessions + .iter() + .map(|session| session.session_id.as_str()) + .collect::>() + .join(", ") + )); + } + + plan.actions + .sort_by(|left, right| left.path.cmp(&right.path)); + plan.actions.dedup_by(|left, right| left.path == right.path); + Ok(plan) +} + +/// Plan removing the installed binaries beside the running one, which +/// `current_exe` names, and undoing the installer's PATH change for their +/// folder. `--keep-binaries` keeps both, and so does a cargo build's folder. +pub(crate) fn plan_installed_binaries( + plan: &mut UninstallPlan, + options: &UninstallOptions, + current_exe: impl FnOnce() -> Result, + home: Option<&Path>, +) -> Result<()> { + if options.keep_binaries { + // The PATH change only serves the binaries, so it stays with them. + plan.skipped.push( + "binary removal disabled by --keep-binaries, so any PATH change the installer made \ + stays too" + .to_owned(), + ); + return Ok(()); + } + let current_exe = current_exe()?; + if is_dev_binary_layout(¤t_exe) && !options.force_dev_binaries { + plan.skipped.push(format!( + "binary removal skipped because {} looks like a cargo target build; pass --force-dev-binaries to remove sibling debug/release binaries", + current_exe.display() + )); + return Ok(()); + } + let binaries = collect_installed_binary_candidates(¤t_exe)?; + for path in &binaries { + // Windows will not unlink a running image; it is deleted as the + // command exits instead. + if is_running_executable(path, ¤t_exe, cfg!(windows)) { + plan.self_delete = Some(path.clone()); + continue; + } + // The PATH record goes only once its change is undone; see + // `uninstall::plan_path_edits`. + if path.file_name().and_then(|name| name.to_str()) == Some(uninstall::PATH_EDIT_RECORD) { + continue; + } + plan.actions.push(UninstallPlanEntry { + kind: "binary", + path: path.clone(), + }); + } + if let Some(bin_dir) = current_exe.parent() { + uninstall::plan_path_edits(plan, bin_dir, &binaries, home); + } + Ok(()) +} + +/// Whether `path`, an entry of the running executable's folder, is the running +/// executable itself, which only Windows has to treat specially. Windows names +/// are case-insensitive, and the running image may report its own name in +/// another case, or in its 8.3 short form (`ROCM.EXE`), than the folder listing +/// does; missing it would plan an ordinary removal that Windows refuses. +fn is_running_executable(path: &Path, current_exe: &Path, windows: bool) -> bool { + if !windows { + return false; + } + path == current_exe + || (path.parent() == current_exe.parent() + && path + .file_name() + .zip(current_exe.file_name()) + .is_some_and(|(name, exe)| { + name.to_string_lossy() + .eq_ignore_ascii_case(&exe.to_string_lossy()) + })) +} + +pub(crate) fn render_uninstall_dry_run(paths: &AppPaths) -> Result { + let options = UninstallOptions { + dry_run: true, + ..UninstallOptions::default() + }; + let plan = build_uninstall_plan(paths, &options)?; + Ok(render_uninstall_plan(&plan, &options)) +} + +pub(crate) fn render_uninstall_plan(plan: &UninstallPlan, options: &UninstallOptions) -> String { + let mut output = String::new(); + let _ = writeln!(output, "Uninstall review"); + let _ = writeln!(output); + let removals = uninstall::removal_count(plan); + if uninstall::plan_is_empty(plan) { + let _ = writeln!(output, "Nothing managed by rocm-cli would be removed."); + } else if removals > 0 { + let _ = writeln!(output, "{removals} item(s) would be removed:"); + for entry in &plan.actions { + let _ = writeln!(output, " - {}: {}", entry.kind, entry.path.display()); + } + } + uninstall::render_extra_plan(&mut output, plan); + if !plan.warnings.is_empty() { + let _ = writeln!(output); + let _ = writeln!(output, "Please review:"); + } + for warning in &plan.warnings { + let _ = writeln!(output, " - {warning}"); + } + if !plan.skipped.is_empty() { + let _ = writeln!(output); + let _ = writeln!(output, "Left alone:"); + } + for skipped in &plan.skipped { + let _ = writeln!(output, " - {skipped}"); + } + if options.dry_run { + let _ = writeln!(output); + let _ = writeln!(output, "Choose Review uninstall to approve removal."); + } + output +} + +/// Caches that ROCm CLI causes to be filled but does not own, so uninstall +/// leaves them in place. +/// +/// These are usually the largest things on disk after an install, so a plan +/// that stays silent about them reads as a clean slate it does not deliver. +/// Only paths that exist and sit outside everything already being removed are +/// reported, so the notes stay truthful as caches move under the data +/// directory. +fn shared_cache_notes(paths: &AppPaths) -> Vec { + let removed_roots = [ + paths.config_dir.clone(), + paths.data_dir.clone(), + paths.cache_dir.clone(), + ]; + shared_cache_notes_for(&removed_roots, &shared_cache_candidates()) +} + +/// The pure part of [`shared_cache_notes`], so the filtering is testable without +/// depending on the caller's real environment. +fn shared_cache_notes_for( + removed_roots: &[PathBuf], + candidates: &[(PathBuf, &'static str)], +) -> Vec { + candidates + .iter() + .filter(|(path, _)| path.exists()) + .filter(|(path, _)| !removed_roots.iter().any(|root| path.starts_with(root))) + .map(|(path, description)| format!("{description} not removed: {}", path.display())) + .collect() +} + +/// The shared caches worth reporting, with why each is left alone. +fn shared_cache_candidates() -> Vec<(PathBuf, &'static str)> { + let mut candidates = Vec::new(); + + // `uv` writes to `UV_CACHE_DIR` when set, otherwise its own default. Read it + // rather than assuming a location, so this stays correct wherever the cache + // has been pointed. + let uv_cache = env_path("UV_CACHE_DIR") + .or_else(|| rocm_core::runtime_home_dir().map(|home| home.join(".cache").join("uv"))); + if let Some(path) = uv_cache { + candidates.push(( + path, + "the uv package cache is shared with other uv projects on this computer and is", + )); + } + + let hf_cache = env_path("HF_HOME") + .map(|home| home.join("hub")) + .or_else(|| env_path("HUGGINGFACE_HUB_CACHE")) + .or_else(|| { + rocm_core::runtime_home_dir() + .map(|home| home.join(".cache").join("huggingface").join("hub")) + }); + if let Some(path) = hf_cache { + candidates.push(( + path, + "downloaded model files are slow to fetch again and may include your own, so they are", + )); + } + + candidates +} + +fn env_path(name: &str) -> Option { + std::env::var_os(name) + .filter(|value| !value.is_empty()) + .map(PathBuf::from) +} + +pub(crate) fn confirm_uninstall() -> Result { + print!("Proceed with uninstall? [y/N]: "); + io::stdout() + .flush() + .context("failed to flush uninstall prompt")?; + let mut response = String::new(); + io::stdin() + .read_line(&mut response) + .context("failed to read uninstall confirmation")?; + let normalized = response.trim().to_ascii_lowercase(); + Ok(matches!(normalized.as_str(), "y" | "yes")) +} + +fn collect_installed_binary_candidates(current_exe: &Path) -> Result> { + let binary_dir = current_exe + .parent() + .context("current executable has no parent directory")?; + let mut binaries = Vec::new(); + for entry in fs::read_dir(binary_dir) + .with_context(|| format!("failed to read {}", binary_dir.display()))? + { + let entry = entry?; + let path = entry.path(); + let Some(name) = path.file_name().and_then(|value| value.to_str()) else { + continue; + }; + if !path.is_file() { + continue; + } + if is_rocm_install_entry_name(name) { + binaries.push(path); + } + } + binaries.sort(); + Ok(binaries) +} + +pub(crate) fn is_rocm_install_entry_name(name: &str) -> bool { + if name == ".rocm-cli-manifest" || name == uninstall::PATH_EDIT_RECORD { + return true; + } + let normalized = name.strip_suffix(".exe").unwrap_or(name); + normalized == "rocm" + || normalized == "rocmd" + || normalized == "rocm-codex" + || normalized.starts_with("rocm-engine-") +} + +fn is_dev_binary_layout(path: &Path) -> bool { + let Some(parent) = path.parent() else { + return false; + }; + let Some(parent_name) = parent.file_name().and_then(|value| value.to_str()) else { + return false; + }; + if parent_name != "debug" && parent_name != "release" { + return false; + } + parent + .parent() + .and_then(|value| value.file_name()) + .and_then(|value| value.to_str()) + == Some("target") +} + +/// `path` respelled so it names the final entry itself. +/// +/// A trailing separator (`link/`) or a trailing `.` (`link/.`) makes the kernel +/// resolve a final symlink, so `symlink_metadata` reports the link's *target* +/// directory and a recursive delete walks into it. Rebuilding the path from its +/// components drops exactly those spellings (plus repeated separators and +/// interior `.`), none of which otherwise change which entry is named. `..` is +/// kept: dropping it lexically would change the meaning through a link. +fn entry_path(path: &Path) -> PathBuf { + path.components().collect() +} + +/// Does `path`'s text end in a separator or a final `.` (`x/`, `x/.`)? The +/// kernel only lets such a spelling name a directory, so `notes.txt/` names +/// nothing even though `notes.txt` exists. +fn spelled_as_directory(path: &Path) -> bool { + let text = path.as_os_str().as_encoded_bytes(); + let is_separator = |byte: u8| std::path::is_separator(char::from(byte)); + match text { + [.., last] if is_separator(*last) => true, + [.., before, b'.'] => is_separator(*before), + _ => false, + } +} + +/// The entry `path` names, as [`entry_path`] spells it, with its own +/// (link-not-followed) metadata — or `None` when nothing is there. +/// +/// A spelling that can only name a directory (see [`spelled_as_directory`]) +/// names nothing when the entry is a regular file, so that counts as absent +/// rather than letting the respelling turn `notes.txt/` into `notes.txt`. A +/// symlink is still the entry: it is what [`remove_path`] unlinks. +fn existing_entry(path: &Path) -> io::Result> { + let entry = entry_path(path); + // Not `path.exists()`: that follows links, so a dangling link would read as + // already gone, be skipped, and still be reported as removed by the caller. + // "Not a directory" means a folder on the way is really a file (as in + // `notes.txt/../x`), so the path names nothing, the same as "not found". + // Any other failure is a real error, not an absence. + let metadata = match fs::symlink_metadata(&entry) { + Ok(metadata) => metadata, + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + return Ok(None); + } + Err(error) => return Err(error), + }; + if spelled_as_directory(path) && !metadata.is_dir() && !metadata.file_type().is_symlink() { + return Ok(None); + } + Ok(Some((entry, metadata))) +} + +/// Remove the entry `path` names: a file or symlink is unlinked (never +/// followed, however `path` is spelled), a real directory is removed +/// recursively, and an entry that is already gone is a no-op. +/// +/// Normalizing here rather than only at plan time covers every caller — +/// `rocm uninstall` and `rocm storage remove-downloads` — whatever spelling +/// their plan carries. +pub(crate) fn remove_path(path: &Path) -> Result<()> { + let Some((path, metadata)) = + existing_entry(path).with_context(|| format!("failed to stat {}", path.display()))? + else { + return Ok(()); + }; + let path = path.as_path(); + if metadata.file_type().is_symlink() || metadata.is_file() { + fs::remove_file(path).with_context(|| format!("failed to remove {}", path.display()))?; + } else if metadata.is_dir() { + fs::remove_dir_all(path).with_context(|| format!("failed to remove {}", path.display()))?; + } else { + bail!("unsupported filesystem entry for {}", path.display()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::test_paths; + + /// A cache that has moved inside a directory uninstall already removes must + /// not be reported as "not removed" — the note would be false. + #[test] + fn shared_cache_notes_skip_paths_already_being_removed() { + let root = std::env::temp_dir().join(format!("rocm-shared-cache-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let data = root.join("data"); + let inside = data.join("uv-cache"); + std::fs::create_dir_all(&inside).unwrap(); + + let notes = shared_cache_notes_for( + &[root.join("config"), data, root.join("cache")], + &[(inside, "the uv package cache")], + ); + + assert!( + notes.is_empty(), + "a cache inside a removed directory must not be reported: {notes:?}" + ); + + let _ = std::fs::remove_dir_all(&root); + } + + /// A cache that exists outside everything being removed is reported, with + /// its path, so the plan does not imply a clean slate it will not deliver. + #[test] + fn shared_cache_notes_report_paths_left_behind() { + let root = std::env::temp_dir().join(format!("rocm-shared-out-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let outside = root.join("elsewhere").join("uv"); + std::fs::create_dir_all(&outside).unwrap(); + + let notes = shared_cache_notes_for( + &[root.join("data")], + &[(outside.clone(), "the uv package cache")], + ); + + assert_eq!(notes.len(), 1, "{notes:?}"); + assert!(notes[0].contains("not removed"), "{notes:?}"); + assert!( + notes[0].contains(&outside.display().to_string()), + "{notes:?}" + ); + + let _ = std::fs::remove_dir_all(&root); + } + + /// A cache that does not exist is not worth mentioning. + #[test] + fn shared_cache_notes_ignore_missing_paths() { + let missing = std::env::temp_dir().join("rocm-definitely-not-here-12345"); + let notes = shared_cache_notes_for( + &[std::env::temp_dir()], + &[(missing, "the uv package cache")], + ); + assert!(notes.is_empty(), "{notes:?}"); + } + + #[test] + fn uninstall_binary_matcher_includes_packaged_codex_binary() { + assert!(is_rocm_install_entry_name("rocm-codex")); + assert!(is_rocm_install_entry_name("rocm-codex.exe")); + } + + /// Windows names are case-insensitive, and the running image may report its + /// own name in another case, or in its 8.3 short form, than the folder + /// listing does; `is_running_executable` must still recognize it. + #[test] + fn the_running_executable_is_matched_whatever_case_windows_reports_it_in() { + let exe = Path::new(r"C:\Users\me\.local\bin\rocm.exe"); + let listed = Path::new(r"C:\Users\me\.local\bin\ROCM.EXE"); + assert!(is_running_executable(listed, exe, true)); + assert!(is_running_executable(exe, exe, true)); + let rocmd = Path::new(r"C:\Users\me\.local\bin\rocmd.exe"); + assert!(!is_running_executable(rocmd, exe, true)); + // Elsewhere the running binary is unlinked like any other. + assert!(!is_running_executable(exe, exe, false)); + } + + /// `rocm uninstall`'s review warns that a remote session keeps running on + /// someone else's machine, and names the command that stops it properly. + /// + /// Nothing exercised that warning before: no test planted a remote session + /// record, so the whole sentence -- including the ASCII punctuation this + /// change put in it (ROCMAI-543) -- shipped uncovered. The remediation is + /// asserted alongside the encoding because a warning that stops naming + /// `rocm remote stop` leaves the user with no way to act on it. + #[test] + fn uninstall_warns_about_remote_sessions_in_ascii_and_names_the_stop_command() -> Result<()> { + let (root, paths) = test_paths("uninstall-remote-session-warning"); + paths.ensure()?; + let session = crate::remote::session::RemoteSessionRecord { + session_id: crate::remote::session::RemoteSessionRecord::id_for("dev-box", 8000), + target: "dev-box".to_owned(), + peer_host: "dev-box".to_owned(), + ssh_port: None, + model: "qwen".to_owned(), + remote_service_id: "svc-remote".to_owned(), + remote_cli: "rocm".to_owned(), + remote_port: 8000, + tailnet_port: 8000, + base_url: "http://dev-box:8000/v1".to_owned(), + created_at_unix_ms: 1, + }; + session.write(&paths)?; + + // `keep_binaries` so the plan never reaches outside the sandbox: the + // binary paths are the host's real ones and have nothing to do with + // this warning. + let options = UninstallOptions { + dry_run: true, + keep_binaries: true, + ..UninstallOptions::default() + }; + let plan = build_uninstall_plan(&paths, &options); + let _ = fs::remove_dir_all(&root); + let plan = plan?; + + let warning = plan + .warnings + .iter() + .find(|warning| warning.contains("remote session record(s)")) + .unwrap_or_else(|| { + panic!("a planted remote session must be warned about: {plan:#?}"); + }); + assert!( + warning.contains(&session.session_id), + "the warning must name the session it found: {warning}" + ); + assert!( + warning.contains("rocm remote stop "), + "the warning must name the command that stops the remote model: {warning}" + ); + // ROCMAI-543: printed verbatim by `render_uninstall_plan`, so non-ASCII + // punctuation here renders as mojibake like "ΓÇö" on a Windows console + // using the OEM code page. + assert!( + warning.is_ascii(), + "the remote-session warning must be ASCII-only (ROCMAI-543): {warning}" + ); + Ok(()) + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 92be4df386..9dbabc89fe 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -55,7 +55,8 @@ Each per-crate module inventory lists one file per line. Flat inventories (every - [`service_launch.rs`](../apps/rocm/src/service_launch.rs) — mechanical relocation, owns private types (Phase 6b, ROCMAI-91): spawning/attaching to a managed service process and streaming its log, plus the endpoint-key/auth checks that gate a public bind — `AttachOutcome`/`RawModeGuard`/`ManagedSpawn`/`AutostartClaim` are its private types; `ManagedLaunchReport` is `pub(crate)`, since [`serve_cmd.rs`](../apps/rocm/src/serve_cmd.rs) reads its fields directly for the interactive summary. Most of this module's functions are `pub(crate)` for the same reason — [`main.rs`](../apps/rocm/src/main.rs), [`serve_cmd.rs`](../apps/rocm/src/serve_cmd.rs), and [`automations.rs`](../apps/rocm/src/automations.rs) all call into it. `ServicesCommand`/`services()` stayed in [`main.rs`](../apps/rocm/src/main.rs) rather than moving alongside — the service-record-management helpers `services()` dispatches to (stop/restart/remove/prune) are entangled with each other; only stop/restart are also reachable from the chat/LLM sandbox tool-calling path, out of scope for Phase 6b. - [`storage.rs`](../apps/rocm/src/storage.rs) — full domain extraction. - [`therock.rs`](../apps/rocm/src/therock.rs) — full domain extraction; owns TheRock SDK install/update and the runtime-manifest model/loaders. The `runtimes` subcommand's own command enum, dispatch fn, and most of its domain logic — rendering, activation, and manifest import — stay in [`main.rs`](../apps/rocm/src/main.rs). -- [`uninstall.rs`](../apps/rocm/src/uninstall.rs) — mechanical relocation, owns private types: `uninstall()`, plus the installer `PATH` undo and running-executable deletion. The shared plan type and its file-removal helpers stay in [`main.rs`](../apps/rocm/src/main.rs) because [`storage.rs`](../apps/rocm/src/storage.rs) reuses them. +- [`uninstall.rs`](../apps/rocm/src/uninstall.rs) — mechanical relocation, owns private types: `uninstall()`, plus the installer `PATH` undo and running-executable deletion. The shared plan type and its file-removal helpers live in [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs) below instead, because [`storage.rs`](../apps/rocm/src/storage.rs) reuses them too. +- [`uninstall_plan.rs`](../apps/rocm/src/uninstall_plan.rs) — mechanical relocation, shares crate-visible types (Phase 6f, ROCMAI-212): the uninstall-plan types (`UninstallOptions`, `UninstallPlan`, `UninstallPlanEntry`), building the plan (`build_uninstall_plan`, `plan_installed_binaries`, and the installed-binary/shared-cache discovery helpers behind them), rendering it (`render_uninstall_dry_run`, `render_uninstall_plan`), the `[y/N]` confirmation prompt (`confirm_uninstall`), and the filesystem removal primitive both [`uninstall.rs`](../apps/rocm/src/uninstall.rs) and [`storage.rs`](../apps/rocm/src/storage.rs) call to carry a plan out (`remove_path`, and the entry-resolution helpers behind it). Kept separate from `uninstall.rs` rather than folded into it, since `uninstall.rs`'s own doc comment and name both describe `uninstall()`'s exclusive logic (the installer `PATH` undo and running-executable deletion), while this module's plan/render/removal helpers are shared with `storage.rs`. `uninstall.rs`, `storage.rs`, `runtimes_cmd.rs`, `chat.rs`, and `deletion_properties.rs` each import the subset of these `pub(crate)` types and helpers they need; see this module's own doc comment for which symbol each one uses. ### `apps/rocmd` — background daemon