rt test: rule 2's scan reads the translator's product sources, and the identity spellings it missed

the_product_sources_take_one_path_for_every_device (rt's tests::one_path) enforces rule 2: product
code names no vendor, device or driver identity, reads no environment variable and declares no
policy type. Until now it read only the runtime's sources and missed several spellings. It now
reads the translator's two crates too, and it catches:
- driver_version, conformance_version, the device, driver and pipeline-cache UUIDs and
  PhysicalDeviceIDProperties;
- ash's device_name_as_c_str, driver_name_as_c_str and driver_info_as_c_str accessors, and
  vk::VendorId;
- the vendor IDs written in decimal;
- getenv;
- the device type, which rule 2 lets decide unified memory alone.

The translator's tests are left out: its tests directories, its tests.rs and *_tests.rs files, the
modules it declares under #[cfg(test)], and its inline #[cfg(test)] modules. A test checks that
exclusion.

The lines the scan may find something on are listed in ALLOWED, by file and text, each with its
reason:
- the device type where unified memory is decided;
- the stage cache's key;
- the translator's DeviceDescription and its two readers;
- DevicePolicy;
- Vulkan's driver enum, mirrored;
- the environment variables' registry;
- the command line's device file;
- three table and grammar numbers that equal a vendor's ID.
A listed line that no longer holds a finding fails the test, so the list cannot go stale. The
module docs say what a scan cannot see: a policy switch spelled as a bool field, a constant or a
cfg(feature) gate, and code after a // inside a string literal.

from_queries_derives_one_profile_whatever_the_identity now also varies the device's name and the
driver's version, and the profile stays the same.

Verified on the CPU with no device, in job m3-max-82544. Probe files were put beside the product
sources; no module declares them, so they were never compiled. They hold one line of each new
form (nine in the runtime's src, one in the translator's):
- the scan at a0d2d2efdd passes over them, which is the gap;
- this change's scan fails, naming all ten lines;
- without the probes, the four one_path tests and the identity test pass;
- the runtime's and the translator's suites: 3091 passed, 22 skipped.
Gate A ran in job m3-max-82570 at a commit of this tree (0339453fe7): signatures, clippy plain,
m2v_gpu and m2v_cpu_icd, doc and privdoc, and the one_path tests again after the one clippy fix
(an explicit auto-deref).
This commit is contained in:
Anees Iqbal committed 2026-12-03 00:05:10 -08:00
1 parent c3d37b4fd3
commit 0912a69508
2 files changed
+451 -25

No files matched your search

+407 -11
View File
@@ -1,14 +1,28 @@
//! One path for every device: the crate's product sources name no vendor, device or driver
//! identity, read no environment variable and declare no policy type. Differences between devices
//! come only from Vulkan's feature, property, format, limit and memory-type queries.
//! One path for every device: the product sources name no vendor, device or driver identity, read
//! no environment variable and declare no policy type. Differences between devices come only from
//! Vulkan's feature, property, format, limit and memory-type queries.
//!
//! The check reads every source file under `src/` except the tests, with line comments removed,
//! so prose may still name what the code must not do.
//! The check reads every product source file of this crate and of the translator's two crates,
//! `metal2vulkan` and `metal2vulkan-air`, with line comments removed, so prose may still name what
//! the code must not do. This crate's tests are its `src/tests/`; the translator's are its `tests`
//! directories, its `tests.rs` and `*_tests.rs` files, the modules it declares under
//! `#[cfg(test)]`, and its inline `#[cfg(test)]` modules. A line [`ALLOWED`] lists may hold what
//! the scan finds on it, and no other line may: the device type where unified memory is decided,
//! the stage cache's key, the translator's `DeviceDescription` and the two readers that fill it,
//! the translator's `DevicePolicy`, Vulkan's enums mirrored, the registry of the translator's
//! environment variables, the command line's device file, and numbers of a table or a grammar that
//! equal a vendor's ID.
//!
//! A scan cannot see all that rule 2 forbids, and review covers the rest: a policy switch spelled
//! as a `bool` field, a constant or a `cfg(feature)` gate reads like any other code, and a `//`
//! inside a string literal ends the part of its line the scan reads.
use crate::tests::product_sources;
use std::path::{Path, PathBuf};
use crate::tests::{crate_dir, product_sources};
/// Identifiers that only an identity-keyed branch needs: Vulkan's vendor, device and driver
/// identity fields and the structures that carry the driver's identity.
/// identity fields, their accessors, and the structures and enums that carry the identity.
const IDENTITY_NAMES: &[&str] = &[
"vendor_id",
"vendorID",
@@ -23,8 +37,24 @@ const IDENTITY_NAMES: &[&str] = &[
"driverInfo",
"device_name",
"deviceName",
"driver_version",
"driverVersion",
"conformance_version",
"conformanceVersion",
"device_uuid",
"deviceUUID",
"driver_uuid",
"driverUUID",
"pipeline_cache_uuid",
"pipelineCacheUUID",
"device_name_as_c_str",
"driver_name_as_c_str",
"driver_info_as_c_str",
"VendorId",
"PhysicalDeviceDriverProperties",
"PhysicalDeviceDriverPropertiesKHR",
"PhysicalDeviceIDProperties",
"PhysicalDeviceIDPropertiesKHR",
];
/// PCI and Khronos vendor IDs of GPU makers, as hex literals (lower case, no separators).
@@ -32,14 +62,154 @@ const VENDOR_LITERALS: &[&str] = &[
"0x1002", "0x10de", "0x8086", "0x106b", "0x13b5", "0x5143", "0x1010", "0x14e4", "0x10005",
];
/// [`VENDOR_LITERALS`] in decimal, in the same order.
const VENDOR_DECIMALS: &[&str] = &[
"4098", "4318", "32902", "4203", "5045", "20803", "4112", "5348", "65541",
];
/// What reading the environment looks like in source.
const ENVIRONMENT_READS: &[&str] = &["env::var", "var_os(", "option_env!", "std::env"];
const ENVIRONMENT_READS: &[&str] = &["env::var", "var_os(", "option_env!", "std::env", "getenv"];
/// The device type's names. Rule 2 lets it decide unified memory alone, so only the lines
/// [`ALLOWED`] lists for it read it.
const DEVICE_TYPE: &[&str] = &["device_type", "deviceType"];
/// The lines that may hold what the scan finds on them, each by its crate's path and its text
/// with the comment removed and trimmed.
const ALLOWED: &[(&str, &str)] = &[
// Unified memory, decided by Vulkan's device type alone (rule 2).
(
"metal2vulkan-runtime/src/device.rs",
"properties.properties.device_type,",
),
// The stage cache's key: a stage kept on disk is read back only on the device and driver that
// made it, as a Vulkan pipeline cache's header keeps its data to them.
(
"metal2vulkan-runtime/src/stage.rs",
"let mut ids = vk::PhysicalDeviceIDProperties::default();",
),
(
"metal2vulkan-runtime/src/stage.rs",
"[ids.device_uuid, ids.driver_uuid]",
),
// The translator's `DeviceDescription`, which carries the identity for reports; nothing that
// derives reads it (`from_queries_derives_one_profile_whatever_the_identity`).
(
"metal2vulkan/src/device/description.rs",
"pub driver_id: Option<vk::DriverId>,",
),
("metal2vulkan/src/device/description.rs", "pub driver_version: u32,"),
("metal2vulkan/src/device/description.rs", "pub vendor_id: u32,"),
("metal2vulkan/src/device/description.rs", "pub device_id: u32,"),
("metal2vulkan/src/device/description.rs", "pub device_name: String,"),
(
"metal2vulkan/src/device/description.rs",
"pub device_type: Option<vk::PhysicalDeviceType>,",
),
("metal2vulkan/src/device/description.rs", "driver_id: None,"),
("metal2vulkan/src/device/description.rs", "driver_version: 0,"),
("metal2vulkan/src/device/description.rs", "vendor_id: 0,"),
("metal2vulkan/src/device/description.rs", "device_id: 0,"),
("metal2vulkan/src/device/description.rs", "device_name: String::new(),"),
("metal2vulkan/src/device/description.rs", "device_type: None,"),
// Its two readers: the Vulkan queries and a Khronos profile document.
(
"metal2vulkan/src/ash_interop/query.rs",
"desc.driver_version = props.driver_version;",
),
(
"metal2vulkan/src/ash_interop/query.rs",
"desc.vendor_id = props.vendor_id;",
),
(
"metal2vulkan/src/ash_interop/query.rs",
"desc.device_id = props.device_id;",
),
("metal2vulkan/src/ash_interop/query.rs", "desc.device_name = props"),
("metal2vulkan/src/ash_interop/query.rs", ".device_name_as_c_str()"),
(
"metal2vulkan/src/ash_interop/query.rs",
"desc.device_type = Some(props.device_type.into());",
),
(
"metal2vulkan/src/ash_interop/query.rs",
"desc.driver_id = Some(properties.v12.driver_id.into());",
),
(
"metal2vulkan/src/device/khronos.rs",
"desc.driver_id = p.enum_value(\"driverID\", vk::DriverId::from_name)?;",
),
(
"metal2vulkan/src/device/khronos.rs",
"desc.driver_version = p.u32(\"driverVersion\")?;",
),
(
"metal2vulkan/src/device/khronos.rs",
"desc.vendor_id = p.u32(\"vendorID\")?;",
),
(
"metal2vulkan/src/device/khronos.rs",
"desc.device_id = p.u32(\"deviceID\")?;",
),
(
"metal2vulkan/src/device/khronos.rs",
"desc.device_name = p.string(\"deviceName\");",
),
(
"metal2vulkan/src/device/khronos.rs",
"desc.device_type = p.enum_value(\"deviceType\", vk::PhysicalDeviceType::from_name)?;",
),
// The translator's `DevicePolicy`: its default is the runtime's, and its one other value the
// validation executor's.
(
"metal2vulkan/src/device/policy.rs",
"pub struct DevicePolicy {",
),
// Vulkan's driver enum, mirrored and converted.
(
"metal2vulkan/src/vk/generated.rs",
"DriverId(i32) = \"VkDriverId\" {",
),
("metal2vulkan/src/ash_interop/convert.rs", "DriverId,"),
// The registry of the `METAL2VULKAN_*` variables: tool paths, operational settings and
// diagnostics, never a translation's branch.
(
"metal2vulkan/src/env_vars.rs",
"std::env::var_os(\"METAL2VULKAN_REPRO_DIR\")",
),
("metal2vulkan/src/env_vars.rs", "std::env::var_os(format!("),
// The command line's device file: its name in a repro bundle, not the device's.
(
"metal2vulkan/src/main.rs",
"let (device_name, device_options, device_bytes) = self.device_file.bundled();",
),
(
"metal2vulkan/src/main.rs",
".file(device_name, device_bytes.to_vec())",
),
// Numbers that equal a vendor's ID: the sRGB curve's table and SPIR-V's grammar.
(
"metal2vulkan/src/metal/format/extended_srgb.rs",
"4169, 4193, 4218, 4243, 4268, 4293, 4318, 4343, 4369, 4394, 4419, 4445, 4471, 4496, 4522, 4548,",
),
(
"metal2vulkan/src/spv.rs",
"HitObjectGetShaderBindingTableRecordIndexEXT = 5348,",
),
(
"metal2vulkan/src/spv.rs",
"5348 => Self::HitObjectGetShaderBindingTableRecordIndexEXT,",
),
("metal2vulkan/src/spv.rs", "PhysicalStorageBuffer64 = 5348,"),
];
/// One finding: the file, the 1-based line and what it named.
#[derive(Debug, PartialEq, Eq)]
struct Finding {
file: String,
line: usize,
/// The line with its comment removed, trimmed.
text: String,
what: String,
}
@@ -52,6 +222,7 @@ fn scan(file: &str, text: &str) -> Vec<Finding> {
findings.push(Finding {
file: file.to_string(),
line: index + 1,
text: code.trim().to_string(),
what,
})
};
@@ -65,10 +236,14 @@ fn scan(file: &str, text: &str) -> Vec<Finding> {
let hex = token.to_ascii_lowercase().replace('_', "");
if let Some(stem) = VENDOR_LITERALS
.iter()
.chain(VENDOR_DECIMALS)
.find(|vendor| hex == **vendor || hex.strip_prefix(**vendor).is_some_and(is_suffix))
{
found(format!("vendor literal `{stem}`"));
}
if DEVICE_TYPE.contains(&token) {
found(format!("device type `{token}`"));
}
}
for read in ENVIRONMENT_READS {
if code.contains(read) {
@@ -93,16 +268,201 @@ fn is_suffix(rest: &str) -> bool {
)
}
/// The product sources the check reads, each labelled with its crate's directory and its path
/// there: this crate's and the translator's two crates'.
fn sources() -> Vec<(String, String)> {
let mut sources: Vec<(String, String)> = product_sources()
.into_iter()
.map(|(label, text)| (format!("metal2vulkan-runtime/src/{label}"), text))
.collect();
for name in ["metal2vulkan", "metal2vulkan-air"] {
sources.extend(translator_sources(name));
}
sources
}
/// The product source files of the translator's crate `name`, each labelled `<name>/src/<path>`
/// with its text, in path order: its tests excepted (the module docs), an inline test module's
/// lines left empty so the others keep their numbers.
fn translator_sources(name: &str) -> Vec<(String, String)> {
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
let mut entries: Vec<PathBuf> = std::fs::read_dir(dir)
.unwrap_or_else(|error| panic!("reading {}: {error}", dir.display()))
.map(|entry| entry.expect("a directory entry").path())
.collect();
entries.sort();
for path in entries {
let file = path.file_name().and_then(|f| f.to_str()).unwrap_or("");
if path.is_dir() {
if file != "tests" {
walk(&path, out);
}
} else if file.ends_with(".rs") && file != "tests.rs" && !file.ends_with("_tests.rs") {
out.push(path);
}
}
}
let root = crate_dir().join("..").join(name).join("src");
let mut files = Vec::new();
walk(&root, &mut files);
assert!(!files.is_empty(), "no source under {}", root.display());
let texts: Vec<(PathBuf, String)> = files
.into_iter()
.map(|path| {
let text = std::fs::read_to_string(&path)
.unwrap_or_else(|error| panic!("reading {}: {error}", path.display()));
(path, text)
})
.collect();
let mut test_modules = Vec::new();
for (path, text) in &texts {
let file = path.file_name().and_then(|f| f.to_str()).unwrap_or("");
let dir = match path.parent() {
Some(parent) if matches!(file, "mod.rs" | "lib.rs" | "main.rs") => parent.to_path_buf(),
_ => path.with_extension(""),
};
for module in test_module_declarations(text) {
test_modules.push(dir.join(format!("{module}.rs")));
test_modules.push(dir.join(module));
}
}
texts
.into_iter()
.filter(|(path, _)| !test_modules.iter().any(|module| path.starts_with(module)))
.map(|(path, text)| {
let label = path
.strip_prefix(&root)
.unwrap_or(&path)
.display()
.to_string();
(format!("{name}/src/{label}"), without_inline_tests(&text))
})
.collect()
}
/// The item an attribute line `at` of `lines` applies to: the first line after it that is no
/// attribute or comment, trimmed, with its visibility removed.
fn item_after<'t>(lines: &[&'t str], at: usize) -> Option<(usize, &'t str)> {
let (index, line) = lines.iter().enumerate().skip(at + 1).find(|(_, line)| {
let line = line.trim_start();
!(line.starts_with("#[") || line.starts_with("//"))
})?;
let line: &'t str = line;
let item = ["pub(crate) ", "pub(super) ", "pub "]
.into_iter()
.fold(line.trim(), |item, vis| {
item.strip_prefix(vis).unwrap_or(item)
});
Some((index, item))
}
/// The names of the modules `text` declares out of line under `#[cfg(test)]` (`mod name;`).
fn test_module_declarations(text: &str) -> Vec<String> {
let lines: Vec<&str> = text.lines().collect();
(0..lines.len())
.filter(|&at| lines[at].trim() == "#[cfg(test)]")
.filter_map(|at| item_after(&lines, at))
.filter_map(|(_, item)| {
item.strip_prefix("mod ")?
.strip_suffix(';')
.map(str::to_string)
})
.collect()
}
/// `text` with each inline `#[cfg(test)]` module's lines, from the attribute to the module's
/// closing brace at the module's indentation, left empty.
fn without_inline_tests(text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let mut kept: Vec<&str> = lines.clone();
let mut at = 0;
while at < lines.len() {
let inline = match lines[at].trim() {
"#[cfg(test)]" => item_after(&lines, at),
_ => None,
}
.filter(|(_, item)| item.starts_with("mod ") && item.ends_with('{'));
let Some((module, _)) = inline else {
at += 1;
continue;
};
let indent = &lines[module][..lines[module].len() - lines[module].trim_start().len()];
let end = (module..lines.len())
.find(|&line| lines[line].strip_prefix(indent) == Some("}"))
.unwrap_or(lines.len() - 1);
kept[at..=end].fill("");
at = end + 1;
}
kept.join("\n")
}
#[test]
fn the_product_sources_take_one_path_for_every_device() {
let findings: Vec<Finding> = product_sources()
let findings: Vec<Finding> = sources()
.iter()
.flat_map(|(label, text)| scan(label, text))
.collect();
let stray: Vec<&Finding> = findings
.iter()
.filter(|f| !ALLOWED.contains(&(f.file.as_str(), f.text.as_str())))
.collect();
assert!(
findings.is_empty(),
"product code must decide by Vulkan queries alone (AGENTS.md, rule 2): {findings:#?}"
stray.is_empty(),
"product code must decide by Vulkan queries alone (AGENTS.md, rule 2): {stray:#?}"
);
for (file, text) in ALLOWED {
assert!(
findings.iter().any(|f| f.file == *file && f.text == *text),
"{file}: `{text}` holds nothing the scan finds, so ALLOWED need not list it"
);
}
}
/// The scan reads the translator's product files, and none of its tests: not a `tests`
/// directory, a `tests.rs` or `*_tests.rs` file, a module declared under `#[cfg(test)]`, or an
/// inline `#[cfg(test)]` module.
#[test]
fn the_scan_reads_the_translators_product_sources_alone() {
let sources = sources();
let read = |label: &str| sources.iter().find(|(l, _)| l == label);
for label in [
"metal2vulkan/src/device/description.rs",
"metal2vulkan/src/pipeline/compile/numbered.rs",
"metal2vulkan-air/src/intrinsics/mod.rs",
] {
assert!(read(label).is_some(), "{label} is read");
}
for label in [
"metal2vulkan/src/pipeline/testing.rs",
"metal2vulkan/src/spirv_binary/table.rs",
"metal2vulkan/src/device/tests/from_queries.rs",
"metal2vulkan-air/src/intrinsics/families_tests.rs",
"metal2vulkan-air/src/canon/tests.rs",
] {
assert!(read(label).is_none(), "{label} is a test");
}
let (_, numbered) = read("metal2vulkan/src/pipeline/compile/numbered.rs").expect("read");
assert!(
!numbered.contains("#[cfg(test)]"),
"its inline test module is left out"
);
let text = "\
fn product() {}
#[cfg(test)]
mod tests {
fn helper() {
let id = props.vendor_id;
}
}
#[cfg(test)]
pub(crate) mod testing;
fn after() {}
";
assert_eq!(
without_inline_tests(text),
"fn product() {}\n\n\n\n\n\n\n#[cfg(test)]\npub(crate) mod testing;\nfn after() {}"
);
assert_eq!(test_module_declarations(text), ["testing"]);
}
#[test]
@@ -124,6 +484,42 @@ fn the_scan_finds_each_forbidden_form() {
),
("pub enum SubmitPolicy {", "policy type `SubmitPolicy`"),
("VK_VENDOR_ID_MESA", "identity name `VK_VENDOR_ID_MESA`"),
(
"if props.driver_version > 3 {",
"identity name `driver_version`",
),
(
"let c = v12.conformance_version;",
"identity name `conformance_version`",
),
("let u = ids.driver_uuid;", "identity name `driver_uuid`"),
(
"let u = props.pipeline_cache_uuid;",
"identity name `pipeline_cache_uuid`",
),
(
"let ids = vk::PhysicalDeviceIDProperties::default();",
"identity name `PhysicalDeviceIDProperties`",
),
(
"let name = props.device_name_as_c_str();",
"identity name `device_name_as_c_str`",
),
(
"let name = floor.vulkan12.driver_name_as_c_str();",
"identity name `driver_name_as_c_str`",
),
("if v == vk::VendorId::MESA {", "identity name `VendorId`"),
("if vendor == 4318 {", "vendor literal `4318`"),
("const INTEL: u32 = 32_902u32;", "vendor literal `32902`"),
(
"let p = unsafe { libc::getenv(name) };",
"environment read `getenv`",
),
(
"if props.device_type == T::DISCRETE_GPU {",
"device type `device_type`",
),
];
for (line, expected) in cases {
let findings = scan("case.rs", line);
@@ -5,53 +5,83 @@ use super::*;
use crate::device::requirements::VkLimit;
use crate::error::{Capability, Feature, Needs};
/// The identities each committed profile is also read under, each with a device type: MoltenVK
/// on an Apple GPU, the NVIDIA driver on a GA10x, RADV, Intel's Mesa driver and none.
fn identities() -> [(Option<vk::DriverId>, u32, u32, vk::PhysicalDeviceType); 5] {
/// One identity a description is read under: the driver, the vendor and device IDs, the device
/// type, the device's name and the driver's version.
struct Identity {
driver: Option<vk::DriverId>,
vendor: u32,
device: u32,
kind: vk::PhysicalDeviceType,
name: &'static str,
version: u32,
}
/// The identities each committed profile is also read under: MoltenVK on an Apple GPU, the
/// NVIDIA driver on a GA10x, RADV, Intel's Mesa driver and none.
fn identities() -> [Identity; 5] {
use vk::PhysicalDeviceType as T;
let identity = |driver, vendor, device, kind, name, version| Identity {
driver,
vendor,
device,
kind,
name,
version,
};
[
(
identity(
Some(vk::DriverId::MOLTENVK),
0x106b,
0x1_0009,
T::INTEGRATED_GPU,
"Apple M3 Max",
0x0001_0002,
),
(
identity(
Some(vk::DriverId::NVIDIA_PROPRIETARY),
0x10de,
0x2204,
T::DISCRETE_GPU,
"NVIDIA GeForce RTX 3090",
0x9140_0000,
),
(
identity(
Some(vk::DriverId::MESA_RADV),
0x1002,
0x744c,
T::DISCRETE_GPU,
"AMD Radeon RX 7900 XTX (RADV NAVI31)",
0x0060_3001,
),
(
identity(
Some(vk::DriverId::INTEL_OPEN_SOURCE_MESA),
0x8086,
0x9a49,
T::INTEGRATED_GPU,
"Intel(R) Iris(R) Xe Graphics (TGL GT2)",
0x0060_2005,
),
(None, 0, 0, T::CPU),
identity(None, 0, 0, T::CPU, "", 0),
]
}
/// On every committed profile, descriptions that differ only in `driver_id`, `vendor_id`,
/// `device_id` and the device type give one profile, which reads YCbCr planes in place.
/// `device_id`, the device type, the device's name and the driver's version give one profile,
/// which reads YCbCr planes in place.
#[test]
fn from_queries_derives_one_profile_whatever_the_identity() {
for (stem, _) in committed_profiles() {
let desc = profile(&stem);
let derived: Vec<Option<DeviceProfile>> = identities()
.into_iter()
.map(|(driver, vendor, device, kind)| {
.map(|id| {
let mut other = desc.clone();
other.driver_id = driver;
other.vendor_id = vendor;
other.device_id = device;
other.device_type = Some(kind);
other.driver_id = id.driver;
other.vendor_id = id.vendor;
other.device_id = id.device;
other.device_type = Some(id.kind);
other.device_name = id.name.to_owned();
other.driver_version = id.version;
Device::from_queries(other, DevicePolicy::RESIDENT_TABLES)
.ok()
.map(|d| d.profile().clone())