From 37b9a6a0b6ac1e2112869f1f733e4529dee4f540 Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Tue, 22 Sep 2026 11:05:42 +0000 Subject: [PATCH 1/3] xtask: add check-crate-edges CI guard for first-party crate layering rocm-cli's workspace has layering invariants (rocmd must never depend on rocm; rocm-dash-core stays pure; rocm-dash-tui has no rocm-core edge) that were previously enforced by nothing. Add `cargo xtask check-crate-edges`, which pins the allowed first-party dependency edges via `cargo metadata` and fails CI on anything outside that allowlist, naming the offending edge and the rule it breaks. Wired into the existing `clippy` CI job right after the MANIFEST.md check. Dev-dependency edges are exempt since Cargo already permits those to cycle. Signed-off-by: Jussi Elo --- .github/workflows/ci.yml | 4 + xtask/src/crate_edges.rs | 337 +++++++++++++++++++++++++++++++++++++++ xtask/src/main.rs | 6 + 3 files changed, 347 insertions(+) create mode 100644 xtask/src/crate_edges.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77fb99ff0c..ffe08892e7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -769,6 +769,10 @@ jobs: if: needs.changes.outputs.rust == 'true' run: cargo xtask manifest --check + - name: First-party crate dependency edges are within the allowlist + if: needs.changes.outputs.rust == 'true' + run: cargo xtask check-crate-edges + # Surface the cache hit rate for the clippy compile so the effect is visible # in the logs, on the local-only path too — see build-and-test for why this # is gated on sccache being present rather than on the remote backend being diff --git a/xtask/src/crate_edges.rs b/xtask/src/crate_edges.rs new file mode 100644 index 0000000000..50ddaaa287 --- /dev/null +++ b/xtask/src/crate_edges.rs @@ -0,0 +1,337 @@ +// Copyright © Advanced Micro Devices, Inc., or its affiliates. +// +// SPDX-License-Identifier: MIT + +//! Guard the first-party crate dependency graph against undeclared layering +//! edges. +//! +//! `rocm-cli`'s workspace has three layering invariants that are otherwise +//! enforced and documented nowhere else in the repo: +//! +//! 1. `rocmd` must never depend on `rocm` (the reverse holds: `rocm` depends +//! on `rocmd` for the in-process `rocm daemon` foreground path). +//! 2. `rocm-dash-core` must have no first-party dependencies — it is a pure +//! leaf crate other subsystems build on. +//! 3. `rocm-dash-tui` must not depend on `rocm-core`. +//! +//! A literal cycle check would be a no-op: Cargo's resolver already rejects +//! dependency cycles among normal/build dependencies. The value here is +//! entirely in the **allowlist**: every first-party normal/build edge must be +//! declared in [`ALLOWLIST`], so *any* new first-party coupling — not just +//! the three named invariants — requires a conscious, reviewed addition to +//! this file. This file is the only written record of these rules; keep this +//! comment and [`ALLOWLIST`] in sync with reality. +//! +//! Dev-dependencies are exempt: Cargo permits dev-dependency cycles (e.g. +//! `rocm-dash-daemon` dev-depends on `rocm-core` for a test-only contract +//! pin), so they are collected but never checked against the allowlist. + +use std::process::Command; + +use anyhow::{Context, Result, bail}; +use serde::Deserialize; + +/// Every currently-allowed first-party `(source, target)` normal/build +/// dependency edge — `source` depends on `target`. Adding a first-party path +/// dependency anywhere in the workspace requires adding its edge here after +/// review; that review is the entire point of this guard. +const ALLOWLIST: &[(&str, &str)] = &[ + ("rocm", "rocm-core"), + ("rocm", "rocm-deps"), + ("rocm", "rocm-dash-core"), + ("rocm", "rocm-dash-daemon"), + ("rocm", "rocm-dash-tui"), + ("rocm", "rocm-engine-lemonade"), + ("rocm", "rocm-engine-protocol"), + ("rocm", "rocmd"), + ("rocm", "rocm-engine-vllm"), + ("rocmd", "rocm-core"), + ("rocmd", "rocm-engine-protocol"), + ("rocm-engine-protocol", "rocm-core"), + ("rocm-dash-collectors", "rocm-dash-core"), + ("rocm-dash-daemon", "rocm-dash-core"), + ("rocm-dash-daemon", "rocm-dash-collectors"), + ("rocm-dash-tui", "rocm-dash-core"), + ("rocm-dash-tui", "rocm-deps"), + ("rocm-engine-lemonade", "rocm-core"), + ("rocm-engine-lemonade", "rocm-deps"), + ("rocm-engine-lemonade", "rocm-engine-protocol"), + ("rocm-engine-vllm", "rocm-core"), + ("rocm-engine-vllm", "rocm-engine-protocol"), + ("xtask", "e2e-report"), + ("xtask", "rocm-core"), + ("e2e-cucumber", "e2e-report"), +]; + +/// Subset of `cargo metadata --no-deps` output we consume: the manifest-level +/// dependency list per workspace-member package. Unlike +/// `resolve.nodes[].dependencies` (used by [`crate::affected`]), which is a +/// kind-blind union used for "does anything here need rebuilding", this list +/// carries a `kind` per edge so normal/build dependencies can be told apart +/// from dev-dependencies. +#[derive(Deserialize)] +struct Metadata { + packages: Vec, +} + +#[derive(Deserialize)] +struct Package { + name: String, + dependencies: Vec, +} + +#[derive(Deserialize)] +struct Dependency { + name: String, + /// `None` = normal, `Some("build")`, `Some("dev")`. + kind: Option, + /// `Some(_)` for a path dependency (first-party, within this workspace); + /// `None` for a registry/git dependency. + path: Option, +} + +/// Whether a first-party edge is subject to the allowlist. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Kind { + /// Normal or build dependency — checked against [`ALLOWLIST`]. + Enforced, + /// Dev-dependency — Cargo permits these to cycle, so never enforced. + Dev, +} + +fn edge_kind(kind: Option<&String>) -> Kind { + match kind.map(String::as_str) { + Some("dev") => Kind::Dev, + _ => Kind::Enforced, + } +} + +/// Run `cargo metadata --no-deps` and reduce it to first-party edges: +/// `(source, target, kind)` triples for every path dependency declared by a +/// workspace member. `--no-deps` restricts `packages` to workspace members +/// only, so there's no need to resolve or filter out the external dependency +/// tree. +fn load_edges() -> Result> { + let output = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) + .args(["metadata", "--format-version", "1", "--locked", "--no-deps"]) + .output() + .context("failed to run `cargo metadata`")?; + if !output.status.success() { + bail!( + "`cargo metadata` failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + } + let metadata: Metadata = serde_json::from_slice(&output.stdout) + .context("failed to parse `cargo metadata` output")?; + Ok(edges_from_metadata(&metadata)) +} + +fn edges_from_metadata(metadata: &Metadata) -> Vec<(String, String, Kind)> { + metadata + .packages + .iter() + .flat_map(|pkg| { + pkg.dependencies + .iter() + .filter(|dep| dep.path.is_some()) + .map(move |dep| { + ( + pkg.name.clone(), + dep.name.clone(), + edge_kind(dep.kind.as_ref()), + ) + }) + }) + .collect() +} + +/// Whether `source -> target` matches one of the three specifically-named +/// layering invariants, as opposed to being merely an undeclared edge. Shared +/// between [`invariant_for`] (which uses it to pick a specific message) and +/// the `allowlist_never_contains_a_named_invariant_violation` test (which +/// uses it to assert [`ALLOWLIST`] itself can never smuggle one of these +/// three edges back in — otherwise a red CI run could be "fixed" by just +/// allowlisting the very edge these invariants exist to forbid). +fn violates_named_invariant(source: &str, target: &str) -> bool { + matches!( + (source, target), + ("rocmd", "rocm") | ("rocm-dash-tui", "rocm-core") + ) || source == "rocm-dash-core" +} + +/// Explain which named invariant an offending edge breaks, when it matches +/// one of the three documented rules; otherwise a generic explanation. +fn invariant_for(source: &str, target: &str) -> String { + if !violates_named_invariant(source, target) { + return format!( + "not in the declared allowlist; add (\"{source}\", \"{target}\") to ALLOWLIST in \ + xtask/src/crate_edges.rs after review if this edge is intentional" + ); + } + match (source, target) { + ("rocmd", "rocm") => { + "rocmd must never depend on rocm — rocm depends on rocmd, not the reverse".to_string() + } + ("rocm-dash-tui", "rocm-core") => "rocm-dash-tui must not depend on rocm-core".to_string(), + _ => "rocm-dash-core must have no first-party dependencies (pure leaf crate)".to_string(), + } +} + +/// Check a set of edges against [`ALLOWLIST`], returning every violation +/// found. Dev-dependency edges are always skipped. +fn check(edges: &[(String, String, Kind)]) -> Vec { + edges + .iter() + .filter(|(_, _, kind)| *kind == Kind::Enforced) + .filter(|(source, target, _)| { + !ALLOWLIST + .iter() + .any(|(a, b)| *a == source.as_str() && *b == target.as_str()) + }) + .map(|(source, target, _)| { + format!( + "first-party dependency edge `{source} -> {target}` violates a layering rule: {}", + invariant_for(source, target) + ) + }) + .collect() +} + +/// Fetch the current first-party crate dependency graph and fail if any +/// normal/build edge is not in [`ALLOWLIST`]. +pub fn run() -> Result<()> { + let edges = load_edges()?; + let violations = check(&edges); + if !violations.is_empty() { + bail!( + "first-party crate dependency graph has {} disallowed edge(s):\n{}", + violations.len(), + violations.join("\n") + ); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn edge(source: &str, target: &str, kind: Kind) -> (String, String, Kind) { + (source.to_string(), target.to_string(), kind) + } + + fn allowlisted_edges() -> Vec<(String, String, Kind)> { + ALLOWLIST + .iter() + .map(|(a, b)| edge(a, b, Kind::Enforced)) + .collect() + } + + #[test] + fn allowlist_passes() { + assert!(check(&allowlisted_edges()).is_empty()); + } + + #[test] + fn rocmd_depending_on_rocm_fails() { + let mut edges = allowlisted_edges(); + edges.push(edge("rocmd", "rocm", Kind::Enforced)); + let violations = check(&edges); + assert_eq!(violations.len(), 1); + assert!(violations[0].contains("rocmd -> rocm")); + assert!(violations[0].contains("rocmd must never depend on rocm")); + } + + #[test] + fn rocm_dash_core_gaining_a_dependency_fails() { + let mut edges = allowlisted_edges(); + edges.push(edge("rocm-dash-core", "rocm-deps", Kind::Enforced)); + let violations = check(&edges); + assert_eq!(violations.len(), 1); + assert!(violations[0].contains("must have no first-party dependencies")); + } + + #[test] + fn rocm_dash_tui_depending_on_rocm_core_fails() { + let mut edges = allowlisted_edges(); + edges.push(edge("rocm-dash-tui", "rocm-core", Kind::Enforced)); + let violations = check(&edges); + assert_eq!(violations.len(), 1); + assert!(violations[0].contains("rocm-dash-tui must not depend on rocm-core")); + } + + #[test] + fn dev_dependency_edges_never_fail() { + let mut edges = allowlisted_edges(); + // Not in ALLOWLIST, but a dev-dependency edge — must be exempt. + edges.push(edge("rocm-dash-daemon", "rocm-core", Kind::Dev)); + assert!(check(&edges).is_empty()); + } + + #[test] + fn unrelated_disallowed_edge_gets_generic_message() { + let mut edges = allowlisted_edges(); + edges.push(edge("rocm-engine-vllm", "rocm-deps", Kind::Enforced)); + let violations = check(&edges); + assert_eq!(violations.len(), 1); + assert!(violations[0].contains("not in the declared allowlist")); + } + + #[test] + fn allowlist_never_contains_a_named_invariant_violation() { + // Guards against the failure mode this file exists to prevent: a + // contributor hitting a red CI run "fixing" it by adding the + // disallowed edge straight into ALLOWLIST instead of removing it. + for &(source, target) in ALLOWLIST { + assert!( + !violates_named_invariant(source, target), + "ALLOWLIST contains `{source} -> {target}`, which violates a documented \ + layering invariant — the fix is to remove the edge, not allowlist it" + ); + } + } + + #[test] + fn build_dependency_edges_are_enforced_not_exempt() { + // Exercises the `edges_from_metadata`/`edge_kind` path for a + // `kind: "build"` first-party edge, which no real workspace member + // currently has (both first-party-adjacent build-deps, `cc` and + // `toml`, are third-party) — so without this fixture the `_ => + // Kind::Enforced` arm in `edge_kind` is otherwise untested. + let metadata = Metadata { + packages: vec![Package { + name: "rocm-core".to_string(), + dependencies: vec![Dependency { + name: "some-first-party-build-dep".to_string(), + kind: Some("build".to_string()), + path: Some("/workspace/some-first-party-build-dep".to_string()), + }], + }], + }; + let edges = edges_from_metadata(&metadata); + assert_eq!( + edges, + vec![( + "rocm-core".to_string(), + "some-first-party-build-dep".to_string(), + Kind::Enforced, + )] + ); + } + + #[test] + fn current_workspace_has_no_disallowed_edges() { + // Regression guard against the real workspace: exercises the full + // `cargo metadata` -> edge extraction -> allowlist-check path, the + // same path `cargo xtask check-crate-edges` runs in CI, so a real + // accidental edge or a stale allowlist is caught here too. + let edges = load_edges().expect("cargo metadata should succeed in a workspace checkout"); + let violations = check(&edges); + assert!( + violations.is_empty(), + "unexpected first-party edge(s) on the real workspace:\n{}", + violations.join("\n") + ); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 291d0de0a0..11bf032f5a 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -11,6 +11,7 @@ //! alias `cargo xtask `. mod affected; +mod crate_edges; mod demos; mod e2e; mod e2e_prewarm; @@ -95,6 +96,10 @@ enum Command { #[arg(long)] base: Option, }, + /// Fail if any first-party crate has gained a normal/build dependency + /// edge outside the allowlist pinned in `xtask/src/crate_edges.rs`. + /// Dev-dependency edges are exempt (Cargo permits those to cycle). + CheckCrateEdges, /// Regenerate the Cargo dependency table in MANIFEST.md from `cargo metadata`. Manifest { /// Verify the table is up to date without writing; exit non-zero if it would change. @@ -241,6 +246,7 @@ fn run() -> Result<()> { } => signing::verify(public_key.as_deref(), &input, &signature)?, Command::VerifyPinnedKeys => verify_pinned_keys::run()?, Command::Affected { base } => affected::run(base)?, + Command::CheckCrateEdges => crate_edges::run()?, Command::Manifest { check } => manifest::run(check)?, Command::Tpn { check, From 9d31d2e568044618c72512e8a75f519843490fb4 Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Tue, 22 Sep 2026 11:24:36 +0000 Subject: [PATCH 2/3] xtask: reject stale crate-edges allowlist entries too check-crate-edges only checked that every real edge is in ALLOWLIST, never the reverse. A dependency removed from a crate's Cargo.toml left its allowlist entry behind, silently permitting the same edge to be reintroduced later without the review this guard exists to force (ROCm/rocm-cli#422 review comment). Make the check bidirectional: an ALLOWLIST entry with no matching edge now fails too, naming itself as stale. Signed-off-by: Jussi Elo --- xtask/src/crate_edges.rs | 67 +++++++++++++++++++++++++++++++--------- 1 file changed, 53 insertions(+), 14 deletions(-) diff --git a/xtask/src/crate_edges.rs b/xtask/src/crate_edges.rs index 50ddaaa287..d6b3b9c0f1 100644 --- a/xtask/src/crate_edges.rs +++ b/xtask/src/crate_edges.rs @@ -19,8 +19,12 @@ //! entirely in the **allowlist**: every first-party normal/build edge must be //! declared in [`ALLOWLIST`], so *any* new first-party coupling — not just //! the three named invariants — requires a conscious, reviewed addition to -//! this file. This file is the only written record of these rules; keep this -//! comment and [`ALLOWLIST`] in sync with reality. +//! this file. The check is bidirectional: an edge missing from +//! [`ALLOWLIST`] fails, and so does an [`ALLOWLIST`] entry with no +//! matching edge — a removed dependency must have its entry removed too, +//! or it could be silently reintroduced later without the review this +//! guard exists to force. This file is the only written record of these +//! rules; keep this comment and [`ALLOWLIST`] in sync with reality. //! //! Dev-dependencies are exempt: Cargo permits dev-dependency cycles (e.g. //! `rocm-dash-daemon` dev-depends on `rocm-core` for a test-only contract @@ -178,34 +182,56 @@ fn invariant_for(source: &str, target: &str) -> String { } } -/// Check a set of edges against [`ALLOWLIST`], returning every violation -/// found. Dev-dependency edges are always skipped. +/// Check a set of edges against [`ALLOWLIST`] in both directions, returning +/// every violation found. Dev-dependency edges are always skipped. +/// +/// Bidirectional: an enforced edge with no matching [`ALLOWLIST`] entry is a +/// new undeclared edge; an [`ALLOWLIST`] entry with no matching enforced edge +/// is stale (the dependency was removed but its allowlist entry wasn't) — +/// left unchecked, that entry would let the same edge reappear later without +/// the conscious review this guard exists to force. fn check(edges: &[(String, String, Kind)]) -> Vec { - edges + let enforced: Vec<(&str, &str)> = edges .iter() .filter(|(_, _, kind)| *kind == Kind::Enforced) - .filter(|(source, target, _)| { - !ALLOWLIST - .iter() - .any(|(a, b)| *a == source.as_str() && *b == target.as_str()) - }) - .map(|(source, target, _)| { + .map(|(source, target, _)| (source.as_str(), target.as_str())) + .collect(); + + let undeclared = enforced + .iter() + .filter(|(source, target)| !ALLOWLIST.iter().any(|(a, b)| a == source && b == target)); + let stale = ALLOWLIST.iter().filter(|(a, b)| { + !enforced + .iter() + .any(|(source, target)| source == a && target == b) + }); + + undeclared + .map(|(source, target)| { format!( "first-party dependency edge `{source} -> {target}` violates a layering rule: {}", invariant_for(source, target) ) }) + .chain(stale.map(|(source, target)| { + format!( + "ALLOWLIST entry `{source} -> {target}` is stale: no such first-party dependency \ + exists anymore; remove it from ALLOWLIST in xtask/src/crate_edges.rs so a future \ + re-addition requires a conscious review" + ) + })) .collect() } -/// Fetch the current first-party crate dependency graph and fail if any -/// normal/build edge is not in [`ALLOWLIST`]. +/// Fetch the current first-party crate dependency graph and fail if it +/// doesn't exactly match [`ALLOWLIST`] — either a new normal/build edge +/// outside it, or a stale entry with no matching edge. pub fn run() -> Result<()> { let edges = load_edges()?; let violations = check(&edges); if !violations.is_empty() { bail!( - "first-party crate dependency graph has {} disallowed edge(s):\n{}", + "first-party crate dependency graph has {} allowlist violation(s):\n{}", violations.len(), violations.join("\n") ); @@ -278,6 +304,19 @@ mod tests { assert!(violations[0].contains("not in the declared allowlist")); } + #[test] + fn stale_allowlist_entry_fails() { + // A dependency that's been removed from the real graph must have its + // ALLOWLIST entry removed too — otherwise it could be silently + // reintroduced later without the review this guard exists to force. + let mut edges = allowlisted_edges(); + let removed = edges.remove(0); + let violations = check(&edges); + assert_eq!(violations.len(), 1); + assert!(violations[0].contains(&format!("{} -> {}", removed.0, removed.1))); + assert!(violations[0].contains("is stale")); + } + #[test] fn allowlist_never_contains_a_named_invariant_violation() { // Guards against the failure mode this file exists to prevent: a From 0acf9d088f170cf534a13ee09506f8f4131f4016 Mon Sep 17 00:00:00 2001 From: Jussi Elo Date: Tue, 22 Sep 2026 11:57:42 +0000 Subject: [PATCH 3/3] xtask: dedupe crate-edge violations and share cargo metadata plumbing check() now dedupes enforced edges via a BTreeSet so a first-party crate declared under both a normal and build dependency no longer reports the same violation twice. affected::load_graph, crate_edges::load_edges, and manifest::load_metadata all duplicated the same cargo metadata subprocess/error-handling boilerplate; that now lives once in paths::run_cargo_metadata. Signed-off-by: Jussi Elo --- xtask/src/affected.rs | 15 +++------------ xtask/src/crate_edges.rs | 41 ++++++++++++++++++++++++++-------------- xtask/src/manifest.rs | 16 ++++------------ xtask/src/paths.rs | 25 ++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 38 deletions(-) diff --git a/xtask/src/affected.rs b/xtask/src/affected.rs index cb7363263e..369b40b760 100644 --- a/xtask/src/affected.rs +++ b/xtask/src/affected.rs @@ -198,18 +198,9 @@ struct Node { /// `--locked` mirrors [`crate::manifest`]: use the committed `Cargo.lock` /// exactly rather than letting metadata resolve to newer registry versions. pub fn load_graph() -> Result { - let output = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) - .args(["metadata", "--format-version", "1", "--locked"]) - .output() - .context("failed to run `cargo metadata`")?; - if !output.status.success() { - bail!( - "`cargo metadata` failed: {}", - String::from_utf8_lossy(&output.stderr).trim() - ); - } - let metadata: Metadata = serde_json::from_slice(&output.stdout) - .context("failed to parse `cargo metadata` output")?; + let stdout = crate::paths::run_cargo_metadata(&[])?; + let metadata: Metadata = + serde_json::from_slice(&stdout).context("failed to parse `cargo metadata` output")?; let graph = build_graph(&metadata); // A member at the repository root would have an empty source dir and so own // every changed file, silently defeating the conservative full-workspace diff --git a/xtask/src/crate_edges.rs b/xtask/src/crate_edges.rs index d6b3b9c0f1..8c931ad66d 100644 --- a/xtask/src/crate_edges.rs +++ b/xtask/src/crate_edges.rs @@ -30,11 +30,13 @@ //! `rocm-dash-daemon` dev-depends on `rocm-core` for a test-only contract //! pin), so they are collected but never checked against the allowlist. -use std::process::Command; +use std::collections::BTreeSet; use anyhow::{Context, Result, bail}; use serde::Deserialize; +use crate::paths; + /// Every currently-allowed first-party `(source, target)` normal/build /// dependency edge — `source` depends on `target`. Adding a first-party path /// dependency anywhere in the workspace requires adding its edge here after @@ -116,18 +118,9 @@ fn edge_kind(kind: Option<&String>) -> Kind { /// only, so there's no need to resolve or filter out the external dependency /// tree. fn load_edges() -> Result> { - let output = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) - .args(["metadata", "--format-version", "1", "--locked", "--no-deps"]) - .output() - .context("failed to run `cargo metadata`")?; - if !output.status.success() { - bail!( - "`cargo metadata` failed: {}", - String::from_utf8_lossy(&output.stderr).trim() - ); - } - let metadata: Metadata = serde_json::from_slice(&output.stdout) - .context("failed to parse `cargo metadata` output")?; + let stdout = paths::run_cargo_metadata(&["--no-deps"])?; + let metadata: Metadata = + serde_json::from_slice(&stdout).context("failed to parse `cargo metadata` output")?; Ok(edges_from_metadata(&metadata)) } @@ -190,8 +183,14 @@ fn invariant_for(source: &str, target: &str) -> String { /// is stale (the dependency was removed but its allowlist entry wasn't) — /// left unchecked, that entry would let the same edge reappear later without /// the conscious review this guard exists to force. +/// +/// `enforced` is deduplicated (a `BTreeSet`, not a `Vec`): a first-party crate +/// could in principle declare the same target as both a normal and a build +/// dependency, which `cargo metadata` reports as two edges that collapse to +/// the same `(source, target)` pair here — without dedup, an undeclared such +/// edge would be reported twice. fn check(edges: &[(String, String, Kind)]) -> Vec { - let enforced: Vec<(&str, &str)> = edges + let enforced: BTreeSet<(&str, &str)> = edges .iter() .filter(|(_, _, kind)| *kind == Kind::Enforced) .map(|(source, target, _)| (source.as_str(), target.as_str())) @@ -304,6 +303,20 @@ mod tests { assert!(violations[0].contains("not in the declared allowlist")); } + #[test] + fn duplicate_undeclared_edge_reported_once() { + // A first-party crate could declare the same target as both a normal + // and a build dependency; `cargo metadata` reports that as two edges + // that collapse to the same (source, target) pair here, and an + // undeclared such edge must be reported once, not once per duplicate. + let mut edges = allowlisted_edges(); + edges.push(edge("rocm-engine-vllm", "rocm-deps", Kind::Enforced)); + edges.push(edge("rocm-engine-vllm", "rocm-deps", Kind::Enforced)); + let violations = check(&edges); + assert_eq!(violations.len(), 1); + assert!(violations[0].contains("rocm-engine-vllm -> rocm-deps")); + } + #[test] fn stale_allowlist_entry_fails() { // A dependency that's been removed from the real graph must have its diff --git a/xtask/src/manifest.rs b/xtask/src/manifest.rs index ad1fd618cf..9746ac0bb3 100644 --- a/xtask/src/manifest.rs +++ b/xtask/src/manifest.rs @@ -8,11 +8,12 @@ use std::fs; use std::path::Path; -use std::process::Command; use anyhow::{Context, Result, bail}; use serde::Deserialize; +use crate::paths; + /// Marker comments bracketing the generated dependency table in MANIFEST.md. const MANIFEST_BEGIN: &str = ""; @@ -42,17 +43,8 @@ struct Package { /// `Cargo.lock` exactly, keeping them consistent and preventing CI from /// resolving to newer registry versions mid-run. fn load_metadata() -> Result { - let output = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) - .args(["metadata", "--format-version", "1", "--locked"]) - .output() - .context("failed to run `cargo metadata`")?; - if !output.status.success() { - bail!( - "`cargo metadata` failed: {}", - String::from_utf8_lossy(&output.stderr).trim() - ); - } - serde_json::from_slice(&output.stdout).context("failed to parse `cargo metadata` output") + let stdout = paths::run_cargo_metadata(&[])?; + serde_json::from_slice(&stdout).context("failed to parse `cargo metadata` output") } /// Build the markdown dependency table (header, separator, and one row per diff --git a/xtask/src/paths.rs b/xtask/src/paths.rs index 0e6002641c..b9020d3cea 100644 --- a/xtask/src/paths.rs +++ b/xtask/src/paths.rs @@ -110,6 +110,31 @@ pub fn binary_name(name: &str) -> String { format!("{name}{}", std::env::consts::EXE_SUFFIX) } +/// Run `cargo metadata --format-version 1 --locked ` and return its +/// raw stdout, or a descriptive error if the subprocess fails to run or exits +/// non-zero. Shared by every command that reduces `cargo metadata` to its own +/// subset of fields ([`crate::affected`], [`crate::crate_edges`], +/// [`crate::manifest`]), so the subprocess invocation and error handling can't +/// drift between them. +/// +/// Always passes `--locked` so callers read the committed `Cargo.lock` exactly, +/// keeping repeated runs consistent and preventing resolution to newer +/// registry versions mid-run. +pub fn run_cargo_metadata(extra_args: &[&str]) -> Result> { + let output = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) + .args(["metadata", "--format-version", "1", "--locked"]) + .args(extra_args) + .output() + .context("failed to run `cargo metadata`")?; + if !output.status.success() { + bail!( + "`cargo metadata` failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + } + Ok(output.stdout) +} + #[cfg(test)] mod tests { use super::*;