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
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,20 @@ hardware, not something an install or a setting can put right.
`hipInfo.exe` (Windows) query needed to find the index and makes no change.
- `--json`, used without a fix id, prints the catalog manifest as JSON. It
applies no fix and exits 0. Together with a fix id it is refused, with exit
code 1.
code 1. The manifest names every exit code `rocm fix` returns
(`exit_codes`, name to number) and says what each means
(`exit_code_descriptions`, name to text).

Exit code 2 has two causes. It is `unknown_id`, a fix id the catalog does not
have, refused with a stderr line starting `Unknown fix-id:`; and it is also what
the argument parser returns for a malformed command line (an unknown option, a
missing value, or a value it cannot read, such as a non-number for
`--device-index`), refused with a stderr line starting `error:` instead. A
one-time `rocm:` notice can come before either line. A script that needs to know
which happened reads the message, not the code. A negative device index depends
on how it is written: `--device-index=-1` is accepted by the parser and the fix
refuses it with exit 3, while `--device-index -1` (with a space) is read as an
unknown option `-1`, a usage error that exits 2.

### ROCm installation

Expand Down
6 changes: 6 additions & 0 deletions apps/rocm/src/advised_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1291,6 +1291,12 @@ const NOT_INVOCATIONS: &[(&str, &str, &str)] = &[
"rocm services prune --any-age --older-than-hours 0",
"the doc's expected result is that the parser rejects this combination",
),
(
"docs/manual-testing.md",
"rocm fix --no-such-option; echo $?",
"the doc's expected result is that the parser rejects the unknown option \
with exit 2, the code the catalog publishes for an unknown fix-id",
),
];

/// Natural-language examples must reach the planner with a multi-word request:
Expand Down
5 changes: 5 additions & 0 deletions apps/rocm/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,11 @@ pub(crate) enum Command {
#[arg(long)]
device_index: Option<i64>,
/// Emit the catalog as JSON for tooling. Only valid without a fix id.
///
/// It also names each exit code and says what it means. Exit 2 is
/// both an unknown fix id (a stderr line starting `Unknown fix-id:`)
/// and a malformed command line (a stderr line starting `error:`);
/// read the message to tell them apart.
#[arg(long)]
json: bool,
},
Expand Down
128 changes: 128 additions & 0 deletions apps/rocm/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1270,6 +1270,134 @@ pub(crate) mod tests {
);
}

/// The catalog manifest tells a caller that exit 2 is shared between an
/// unknown fix-id and a malformed command line. That claim is about clap,
/// which only this crate links, so it is proved here: a bad `rocm fix`
/// command line really exits with the code published for `unknown_id`,
/// through the same `clap_exit_code -> exit_code_for` chain `main` uses,
/// and the refusal has a line starting with the `error:` the description
/// tells a caller to look for (not `Usage:`, which a missing value does not
/// print). The
/// description's own wording is pinned in
/// `rocm-core` (`the_unknown_id_description_names_the_usage_error_it_shares_a_code_with`).
#[test]
fn a_usage_error_exits_with_the_code_published_for_an_unknown_fix_id() {
let manifest = rocm_core::catalog_manifest();
let published = manifest.exit_codes["unknown_id"];
for argv in [
&["rocm", "fix", "--no-such-option"][..],
&["rocm", "fix", "fix-9-igpu-dgpu", "--device-index"][..],
&[
"rocm",
"fix",
"fix-9-igpu-dgpu",
"--device-index",
"not-a-number",
][..],
] {
let err = super::cli_command()
.try_get_matches_from(argv)
.expect_err("a malformed command line must be a parse error");
let rendered = err.render().to_string();
assert!(
rendered.lines().any(|line| line.starts_with("error:"))
&& !rendered.contains(rocm_core::fix_exit::UNKNOWN_ID_PREFIX),
"{argv:?}: the description promises `error:` and no unknown-id message:\n{rendered}"
);
let result: Result<()> = Err(super::clap_exit_code(err));
assert_eq!(
super::exit_code_for(result),
ExitCode::from(published as u8),
"{argv:?}: a usage error must exit with the code the manifest names for it"
);
}
assert!(
manifest.exit_code_descriptions["unknown_id"].contains("malformed command line"),
"the published description must warn that a usage error exits {published} too"
);
}

/// A negative device index exits with one of two published codes, and the
/// catalog says which by how it is written: `--device-index=-1` reaches the
/// fix, which refuses it as `not_applicable`; `--device-index -1` never gets
/// past the parser, which reads `-1` as an unknown option, a usage error that
/// exits with the `unknown_id` code. Both go through the real parser and
/// the same exit path `main` uses, the first through `dispatch` as well.
/// Under `--dry-run`, so a lost guard in the runner would only preview.
///
/// "Reaches the fix" holds on Windows and Linux, where fix-9 applies. On
/// WSL it does not apply, so `apply` returns 3 from the platform gate before
/// the runner, and the `=-1` half cannot notice a lost runner guard there;
/// `a_negative_device_index_is_not_applicable_and_nothing_runs` in
/// `rocm-core`'s `fix/runners.rs` holds the guard on every host.
#[test]
fn a_negative_device_index_reaches_the_fix_only_when_written_with_equals() {
let manifest = rocm_core::catalog_manifest();
let not_applicable = manifest.exit_codes["not_applicable"];
let unknown_id = manifest.exit_codes["unknown_id"];

let cli = super::Cli::try_parse_from([
"rocm",
"fix",
"fix-9-igpu-dgpu",
"--device-index=-1",
"--dry-run",
])
.expect("`--device-index=-1` must parse: the fix, not the parser, refuses it");
assert!(
matches!(
cli.command,
Some(super::Command::Fix {
device_index: Some(-1),
..
})
),
"the parsed value must be -1"
);
let mut env = ScopedTestEnv::new();
env.set("ROCM_CLI_DISABLE_STARTUP_UPDATE_CHECK", "1");
let result = super::dispatch(cli);
drop(env);
assert_eq!(
super::exit_code_for(result),
ExitCode::from(not_applicable as u8),
"`--device-index=-1` must exit with the code published as not_applicable"
);

let err = super::cli_command()
.try_get_matches_from([
"rocm",
"fix",
"fix-9-igpu-dgpu",
"--device-index",
"-1",
"--dry-run",
])
.expect_err("`--device-index -1` must be a usage error");
let rendered = err.render().to_string();
assert!(
rendered.lines().any(|line| line.starts_with("error:"))
&& !rendered.contains(rocm_core::fix_exit::UNKNOWN_ID_PREFIX),
"`--device-index -1` must be refused as a usage error:\n{rendered}"
);
let result: Result<()> = Err(super::clap_exit_code(err));
assert_eq!(
super::exit_code_for(result),
ExitCode::from(unknown_id as u8),
"`--device-index -1` must exit with the code published as unknown_id"
);

for (name, spelling) in [
("not_applicable", "`--device-index=-1`"),
("unknown_id", "`--device-index -1`"),
] {
assert!(
manifest.exit_code_descriptions[name].contains(spelling),
"the {name} description must name {spelling}"
);
}
}

/// Any other error must still fail with exit 1, matching what
/// `Result<(), anyhow::Error>`'s `Termination` impl already does today for
/// every subcommand other than `fix`.
Expand Down
21 changes: 20 additions & 1 deletion crates/rocm-core/src/fix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pub(crate) use catalog::{ShellRun, run_typed_in_cmd_and_powershell};
#[must_use]
pub fn apply(fix_id: &str, opts: &FixOptions) -> i32 {
let Some(recipe) = find_recipe(fix_id) else {
fail!("Unknown fix-id: {fix_id}");
fail!("{} {fix_id}", exit::UNKNOWN_ID_PREFIX);
if looks_like_a_diagnosis_position(fix_id) {
// `rocm diagnose` ranks findings `#1`, `#2`, and users reach for that
// number here. It is a position in one report, not a name -- and it
Expand Down Expand Up @@ -281,6 +281,25 @@ mod tests {
);
}

/// The published `internal` description: a recipe the catalog says the CLI
/// carries out here, with no runner to carry it out, is the CLI's own fault
/// and exits with the code published as `internal`, not `failed`.
/// `a_recipe_that_acts_has_a_runner` keeps the real catalog off this path;
/// this drives the path itself with a synthetic recipe.
#[test]
fn a_recipe_the_catalog_says_is_applied_with_no_runner_exits_internal() {
// `Auto` is the class that says the CLI applies the fix itself
// (`FixClass::applies_itself`); a runner-less `NeedsArgument` entry only
// prints steps, so it is not this path.
let recipe = unfixable_recipe(FixClass::Auto);
assert_eq!(plan_of(&recipe), Plan::MissingRunner);
assert_eq!(
act_on(&recipe, &FixOptions::default()),
exit::INTERNAL,
"an AUTO entry with no runner must exit with the code published as internal"
);
}

/// A Linux verify line is only worth having on a recipe that applies on
/// Linux or WSL; on any other it could never be run.
#[test]
Expand Down
159 changes: 147 additions & 12 deletions crates/rocm-core/src/fix/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,17 @@ pub struct ManifestEntry {
pub struct CatalogManifest {
pub contract_version: u32,
pub entries: Vec<ManifestEntry>,
/// What each exit code from `rocm fix` means.
/// The number behind each exit-code name from `rocm fix`.
pub exit_codes: std::collections::BTreeMap<String, i32>,
/// What each exit-code name in [`Self::exit_codes`] means, keyed by the same
/// names. A sibling map rather than a richer value in `exit_codes`, so a
/// reader written against name -> number keeps working: an added field,
/// which does not raise the contract version.
///
/// `unknown_id` (2) says that a malformed command line exits 2 as well, and
/// how to tell the two refusals apart.
#[serde(default)]
pub exit_code_descriptions: std::collections::BTreeMap<String, String>,
}

/// Describe the catalog for a machine to read.
Expand Down Expand Up @@ -88,17 +97,14 @@ pub fn catalog_manifest() -> CatalogManifest {
doc_url: r.doc_url.map(ToOwned::to_owned),
})
.collect(),
exit_codes: [
("ok", exit::OK),
("internal", exit::INTERNAL),
("unknown_id", exit::UNKNOWN_ID),
("not_applicable", exit::NOT_APPLICABLE),
("failed", exit::FAILED),
("declined", exit::DECLINED),
]
.into_iter()
.map(|(name, code)| (name.to_owned(), code))
.collect(),
exit_codes: exit::MEANINGS
.iter()
.map(|m| (m.name.to_owned(), m.code))
.collect(),
exit_code_descriptions: exit::MEANINGS
.iter()
.map(|m| (m.name.to_owned(), m.description.to_owned()))
.collect(),
}
}

Expand Down Expand Up @@ -156,6 +162,135 @@ mod tests {
}
}

/// Every published code carries a description, under the same name, and
/// the table they come from names each code once. A name with a number and
/// no meaning is the gap ROCMAI-955 reported; two names for one number would
/// leave a reader unable to say which it got.
#[test]
fn every_published_exit_code_is_described_once() {
let manifest = catalog_manifest();
let named: Vec<&String> = manifest.exit_codes.keys().collect();
let described: Vec<&String> = manifest.exit_code_descriptions.keys().collect();
assert_eq!(named, described, "every exit code needs a description");
for (name, text) in &manifest.exit_code_descriptions {
assert!(!text.trim().is_empty(), "`{name}` is described by nothing");
}
let mut codes: Vec<i32> = exit::MEANINGS.iter().map(|m| m.code).collect();
codes.sort_unstable();
codes.dedup();
assert_eq!(
codes.len(),
exit::MEANINGS.len(),
"two names publish the same exit code"
);
assert_eq!(
manifest.exit_codes.len(),
exit::MEANINGS.len(),
"two entries share a name"
);
}

/// Exit 2 means two things, and the description has to say both and how to
/// tell them apart, or a caller that reads it still cannot. The message it
/// names is the one `apply` prints, held to the same constant; that the
/// argument parser really exits 2 is checked in `apps/rocm`, which owns it
/// (`a_usage_error_exits_with_the_code_published_for_an_unknown_fix_id`).
#[test]
fn the_unknown_id_description_names_the_usage_error_it_shares_a_code_with() {
let manifest = catalog_manifest();
assert_eq!(manifest.exit_codes["unknown_id"], exit::UNKNOWN_ID);
let text = &manifest.exit_code_descriptions["unknown_id"];
for needed in [
exit::UNKNOWN_ID_PREFIX,
"argument parser",
"malformed command line",
"`error:`",
// A one-time `rocm:` notice can precede either refusal, so the
// promise is about a line, not about where stderr starts.
"stderr line",
] {
assert!(
text.contains(needed),
"the unknown_id description must mention `{needed}`: {text}"
);
}
}

/// `MEANINGS` claims to list every code `rocm fix` returns. The runners
/// return the `exit::` constants (held by
/// `fix_runners_return_named_exit_constants_not_integers`), so the set of
/// constants is the set of codes, and this holds the table to it: a new
/// constant fails here until it is described and published.
#[test]
fn every_exit_constant_is_published_and_nothing_else_is() {
let file = syn::parse_file(include_str!("options.rs")).expect("options.rs parses");
let exit_mod = file
.items
.iter()
.find_map(|item| match item {
syn::Item::Mod(m) if m.ident == "exit" => m.content.as_ref(),
_ => None,
})
.expect("options.rs has an inline `mod exit`");
let mut declared: Vec<(String, i32)> = exit_mod
.1
.iter()
.filter_map(|item| match item {
syn::Item::Const(c) if matches!(&*c.ty, syn::Type::Path(p) if p.path.is_ident("i32")) => {
let syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(value),
..
}) = &*c.expr
else {
panic!("exit::{} is not an integer literal", c.ident);
};
Some((
c.ident.to_string(),
value.base10_parse().expect("an i32 literal"),
))
}
_ => None,
})
.collect();
declared.sort_by_key(|(_, code)| *code);
let mut published: Vec<i32> = exit::MEANINGS.iter().map(|m| m.code).collect();
published.sort_unstable();
let declared_codes: Vec<i32> = declared.iter().map(|(_, code)| *code).collect();
assert_eq!(
declared_codes, published,
"every exit:: constant must have exactly one MEANINGS entry, and no entry may \
publish a code no constant names; constants: {declared:?}"
);
// Name by name too: the published name is the constant's, lower-cased,
// so a reader of the manifest and a reader of the code use one word.
for (constant, code) in &declared {
let meaning = exit::MEANINGS
.iter()
.find(|m| m.code == *code)
.expect("checked above");
assert_eq!(
meaning.name,
constant.to_lowercase(),
"exit::{constant} is published under another name"
);
}
}

/// A manifest written before the descriptions existed still reads: the
/// field was added, so the contract version did not move, and that is only
/// true if an older document parses.
#[test]
fn a_manifest_without_descriptions_still_parses() {
let mut value = serde_json::to_value(catalog_manifest()).expect("serializes");
value
.as_object_mut()
.expect("an object")
.remove("exit_code_descriptions");
let older: CatalogManifest = serde_json::from_value(value).expect("an older manifest");
assert!(older.exit_code_descriptions.is_empty());
assert_eq!(older.contract_version, CATALOG_CONTRACT_VERSION);
}

#[test]
fn a_published_doc_url_is_a_url() {
// Most entries carry none, which is the honest answer until someone
Expand Down
Loading
Loading