Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 109 additions & 13 deletions apps/rocm/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11601,6 +11601,30 @@ fn runtime_keys_text(manifests: &[&therock::InstalledRuntimeManifest]) -> String
.join(", ")
}

/// Resolves a user-typed selector to the one installed runtime it names.
///
/// Matching a `runtime_key` regardless of letter case is a deliberate
/// convenience, but it only names one runtime while no two installed keys
/// differ just in case — and they can. Generated keys are slugified to lower
/// case, while `runtimes adopt --runtime-key` takes the key the user typed and
/// `runtimes import` takes it from the supplied manifest; neither slugifies,
/// so the key is stored verbatim. The registry keeps one file per key, so
/// `ABC.json` and `abc.json` are two entries on a case-sensitive filesystem
/// and nothing rejects the pair.
///
/// So an exact key match is taken first and wins outright: it is the one
/// reading of the selector that cannot be mistaken. The case-insensitive
/// fallback applies only when it lands on a single record; two case twins are
/// reported as the ambiguity they are, the same way a `runtime_id` naming
/// several installs already is.
///
/// Callers rely on that being a function of the key alone, because several of
/// them resolve the same key more than once and must land on the same record
/// every time: `storage remove-old-installs` decides about a manifest and then
/// names it to the deleter by key, and the uninstall revalidation re-derives
/// its plan from disk after the confirmation prompt. Resolving by "newest
/// case-insensitive match" made that decide about one install and act on
/// another.
fn select_runtime_manifest<'a>(
manifests: &'a [therock::InstalledRuntimeManifest],
selector: &str,
Expand All @@ -11612,28 +11636,35 @@ fn select_runtime_manifest<'a>(

if let Some(manifest) = manifests
.iter()
.find(|manifest| manifest.runtime_key.eq_ignore_ascii_case(selector))
.find(|manifest| manifest.runtime_key == selector)
{
return Ok(manifest);
}

let matches = manifests
let key_matches = manifests
.iter()
.filter(|manifest| manifest.runtime_key.eq_ignore_ascii_case(selector))
.collect::<Vec<_>>();
match key_matches.as_slice() {
[manifest] => return Ok(manifest),
[] => {}
_ => bail!(
"runtime selector `{selector}` matches several installed runtime keys that differ only in letter case; name one of them exactly: {}",
runtime_keys_text(&key_matches)
),
}

let id_matches = manifests
.iter()
.filter(|manifest| manifest.runtime_id.eq_ignore_ascii_case(selector))
.collect::<Vec<_>>();
match matches.as_slice() {
match id_matches.as_slice() {
[manifest] => Ok(manifest),
[] => bail!("installed runtime not found: {selector}"),
_ => {
let keys = matches
.iter()
.map(|manifest| manifest.runtime_key.as_str())
.collect::<Vec<_>>()
.join(", ");
bail!(
"runtime selector `{selector}` matches multiple installed runtimes; activate one by runtime_key: {keys}"
);
}
_ => bail!(
"runtime selector `{selector}` matches multiple installed runtimes; activate one by runtime_key: {}",
runtime_keys_text(&id_matches)
),
}
}

Expand Down Expand Up @@ -33480,6 +33511,71 @@ ID_LIKE="suse opensuse"
Ok(())
}

/// Matching a key regardless of case is a convenience for a user who typed
/// the wrong one; it must not quietly pick between two installs whose keys
/// differ only in case. `runtimes adopt --runtime-key` stores the key
/// verbatim while generated keys are lower-cased, so such a pair is
/// reachable, and a caller that resolves the same key twice — prune decides
/// about a manifest and then names it to the deleter by key — has to get
/// the same install both times.
///
/// No registry is involved here: the manifests are handed straight to the
/// resolver, so this holds on every platform even though only a
/// case-sensitive filesystem can store such a pair.
#[test]
fn runtime_selector_prefers_the_exact_key_over_a_case_twin() -> Result<()> {
let (root, paths) = test_paths("runtime-case-twin");
let base = write_test_pip_runtime(
&paths,
"release-pip-gfx120x-all-7-13-0",
"therock-release:gfx120X-all",
"7.13.0",
20,
)?;
// Newest first, as `load_runtime_manifests` hands them over. The
// adopted twin is stamped with the moment it was adopted, so it leads.
let manifests = vec![
therock::InstalledRuntimeManifest {
runtime_key: "RELEASE-PIP-GFX120X-ALL-7-13-0".to_owned(),
installed_at_unix_ms: 99,
read_only: true,
..base.clone()
},
base.clone(),
];

let exact = select_runtime_manifest(&manifests, &base.runtime_key)?;
assert_eq!(
exact.runtime_key, base.runtime_key,
"the key as stored resolves to its own record, not to the newer twin"
);
let twin = select_runtime_manifest(&manifests, "RELEASE-PIP-GFX120X-ALL-7-13-0")?;
assert_eq!(twin.runtime_key, "RELEASE-PIP-GFX120X-ALL-7-13-0");

// Neither key matches exactly, so the selector genuinely names both.
// Reported as the ambiguity it is, like a runtime_id naming several.
let error = select_runtime_manifest(&manifests, "Release-Pip-Gfx120X-All-7-13-0")
.unwrap_err()
.to_string();
assert!(
error.contains("differ only in letter case"),
"an ambiguous selector must be refused, not silently resolved: {error}"
);
assert!(error.contains("release-pip-gfx120x-all-7-13-0"));
assert!(error.contains("RELEASE-PIP-GFX120X-ALL-7-13-0"));

// The convenience itself is untouched: with one candidate, any casing
// still resolves.
let only = vec![base.clone()];
assert_eq!(
select_runtime_manifest(&only, "Release-Pip-Gfx120X-All-7-13-0")?.runtime_key,
base.runtime_key
);

let _ = fs::remove_dir_all(root);
Ok(())
}

#[test]
fn runtime_activation_rejects_unusable_manifest() -> Result<()> {
let (root, paths) = test_paths("runtime-unusable");
Expand Down
122 changes: 122 additions & 0 deletions apps/rocm/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,11 @@ pub(crate) fn storage(command: Option<StorageCommand>) -> Result<()> {
}

// Per-key delegation keeps config/marker cleanup in one place.
// It rests on `select_runtime_manifest` resolving a key back to
// the very manifest the policy decided about — keys that differ
// only in letter case are distinct installs here, so a lookup
// that folded them together would delete a different runtime
// than the one the user just confirmed.
let result = crate::uninstall_runtime(&paths, &mut config, &entry.runtime_key)
.with_context(|| format!("failed to remove {}", entry.runtime_key))?;
// `uninstall_runtime` re-evaluates ownership itself and can
Expand Down Expand Up @@ -1704,6 +1709,123 @@ mod tests {
Ok(())
}

/// `rocm runtimes adopt --runtime-key` stores the key the user typed
/// verbatim, so an adopted runtime can carry a key that differs from an
/// installed one only in case. The registry is one file per key, and
/// `ABC.json` and `abc.json` are two files, so nothing rejects the pair.
///
/// Prune resolves the key it selected twice: `build_prune_plan` finds the
/// manifest with `==`, and the removal it delegates to resolves the same
/// string through `select_runtime_manifest`. While that second lookup
/// preferred the newest case-insensitive match, an adopted record — stamped
/// with the moment it was adopted, so always the newest — won it, and prune
/// de-registered the adopted runtime while leaving the install the user
/// confirmed in place, reclaiming nothing.
///
/// Two case twins are only two registry files on a case-sensitive
/// filesystem, so the situation cannot arise — and cannot be staged — on
/// Windows, where the second fixture would overwrite the first.
#[cfg_attr(
not(target_os = "linux"),
ignore = "needs a case-sensitive filesystem to hold two registry entries differing only in case"
)]
#[test]
fn prune_removes_the_install_it_named_and_not_a_case_twin_of_it() -> Result<()> {
let (root, paths) = test_paths("case-twin");
let old = install_fixture(
&paths,
manifest("release-wheel-gfx110x-7-9-0", "gfx110X-all", "7.9.0", 5),
2048,
)?;
let middle = install_fixture(
&paths,
manifest("release-wheel-gfx110x-7-10-0", "gfx110X-all", "7.10.0", 10),
2048,
)?;
let newer = install_fixture(
&paths,
manifest("release-wheel-gfx110x-7-11-0", "gfx110X-all", "7.11.0", 20),
2048,
)?;
// `rocm runtimes adopt --runtime-key RELEASE-WHEEL-GFX110X-7-9-0`.
// Adoption always sets read_only and imported_from, and stamps
// installed_at with the moment it ran, so it is the newest record.
let mut adopted = manifest("RELEASE-WHEEL-GFX110X-7-9-0", "gfx110X-all", "7.9.0", 99);
adopted.read_only = true;
adopted.imported_from = Some(PathBuf::from("/opt/rocm"));
let adopted = install_fixture(&paths, adopted, 2048)?;
// The runtime in use is a third one, so neither twin is force-kept by
// the active pointer. (A pointer at either twin holds *both*, because
// the holds compare case-insensitively — that is what hides this.)
let mut config = RocmCliConfig {
active_runtime_key: Some("release-wheel-gfx110x-7-11-0".to_owned()),
..RocmCliConfig::default()
};

let plan = build_prune_plan(&paths, &config, 1)?;
let planned: Vec<&str> = plan
.remove
.iter()
.map(|entry| entry.runtime_key.as_str())
.collect();
assert_eq!(
planned,
vec!["release-wheel-gfx110x-7-9-0"],
"the plan the user confirms names the lowercase install: {:?}",
plan.skipped
);

// The removal loop in `storage()`, including its last-second re-check.
for entry in &plan.remove {
let manifests = therock::load_runtime_manifests(&paths)?;
let marker = read_active_runtime_marker(&paths);
let inputs = RetentionInputs::from_config(&config, marker.as_ref());
let default_key = resolved_default_runtime_key(&manifests, &inputs);
if let Some(manifest) = manifests
.iter()
.find(|manifest| manifest.runtime_key == entry.runtime_key)
&& unconditional_hold(manifest, &inputs, default_key.as_deref()).is_some()
{
continue;
}
crate::uninstall_runtime(&paths, &mut config, &entry.runtime_key)?;
}

let registry = paths.data_dir.join("runtimes").join("registry");
assert!(
!old.install_root.exists(),
"the install the plan named must be the one that is gone"
);
assert!(newer.install_root.is_dir());
assert!(middle.install_root.is_dir());
assert!(
adopted.install_root.is_dir(),
"the adopted runtime's folder must survive"
);
assert!(
!registry.join("release-wheel-gfx110x-7-9-0.json").is_file(),
"the named install is de-registered too, not just emptied"
);
assert!(
registry.join("RELEASE-WHEEL-GFX110X-7-9-0.json").is_file(),
"the adopted runtime must still be registered"
);
// Belt as well as braces: even if the policy ever did select the
// adopted twin, the ownership guard would still refuse its folder.
assert_eq!(
should_remove_runtime_install_root(&adopted)?,
InstallRootDecision::ReadOnly,
"an adopted install's folder stays off-limits to deletion"
);
assert_eq!(
config.active_runtime_key.as_deref(),
Some("release-wheel-gfx110x-7-11-0"),
"removing an old install must not deactivate the runtime in use"
);

let _ = std::fs::remove_dir_all(root);
Ok(())
}
/// `--yes` is required when there is nobody to answer the prompt. This is
/// the gate standing between a scripted invocation and a multi-gigabyte
/// deletion, so it is worth a test of its own.
Expand Down