From b4b22c7b2c96ca64cc2dd520c11eb3f41013a216 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 17 Nov 2026 05:11:01 -0800 Subject: [PATCH] matrix: the per-commit matrix runner and the user-space instruction counter (WIP) --- CONTRIBUTING.md | 17 + crates/metal2vulkan-devtools/Cargo.toml | 4 + .../metal2vulkan-devtools/src/instructions.rs | 316 ++++++++++ crates/metal2vulkan-devtools/src/lib.rs | 6 +- docs/VALIDATION.md | 54 ++ scripts/matrix/matrix | 586 ++++++++++++++++++ scripts/matrix/results.py | 182 ++++++ scripts/matrix/test_results.py | 147 +++++ 8 files changed, 1310 insertions(+), 2 deletions(-) create mode 100644 crates/metal2vulkan-devtools/src/instructions.rs create mode 100755 scripts/matrix/matrix create mode 100644 scripts/matrix/results.py create mode 100644 scripts/matrix/test_results.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b8012f6c5..b4e258130 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -97,6 +97,23 @@ build fingerprint). kache imports incremental state only between targets inside a `CARGO_TARGET_DIR` outside the worktree neither gives nor takes it. `seed-target new` takes such a path too (`scripts/seed-target new WORKTREE/target SEED WORKTREE`). +### The matrix + +After a landing on `development`, run the matrix on its tip: + +```sh +scripts/matrix/matrix run development # or a sha; --legs 1002:744c,lavapipe for some legs +scripts/matrix/matrix show development # the verdicts already attached to it +``` + +It dispatches every leg through potluck at priority 5, waits for them, writes the commit's note +under `refs/notes/matrix`, and prints one verdict line per leg; it exits 0 only when every leg +passes. `--dry-run` prints the legs and their nodes and dispatches nothing. Runs never overlap: a +second one refuses to start. It keeps its state (its own checkout, workspaces, measured job sizes, +each run's job logs and note) in `~/.cache/metal2vulkan-matrix/`, and reads the lab's builders from +`~/.config/metal2vulkan/matrix.json` (the script's header has the format). +[docs/VALIDATION.md](docs/VALIDATION.md) has the legs and the rules. + ## Where tests go - A test that names an internal item is a unit test of its crate: under `src/tests/` (or its diff --git a/crates/metal2vulkan-devtools/Cargo.toml b/crates/metal2vulkan-devtools/Cargo.toml index a8a20b605..dece70bfe 100644 --- a/crates/metal2vulkan-devtools/Cargo.toml +++ b/crates/metal2vulkan-devtools/Cargo.toml @@ -14,6 +14,10 @@ publish = false # The synthetic metallib writer's function hashes (`metallib`). sha2.workspace = true +# The user-space instruction counters (`instructions`): perf_event_open and its ioctls. +[target.'cfg(target_os = "linux")'.dependencies] +libc.workspace = true + # The scratch locks' file identity on Windows (`scratch.rs`'s `same_file`). [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Storage_FileSystem"] } diff --git a/crates/metal2vulkan-devtools/src/instructions.rs b/crates/metal2vulkan-devtools/src/instructions.rs new file mode 100644 index 000000000..2c58a5c1d --- /dev/null +++ b/crates/metal2vulkan-devtools/src/instructions.rs @@ -0,0 +1,316 @@ +//! The user-space instructions the calling thread retires, read from the kernel's performance +//! counters: what the matrix's `instructions` records (CPU instructions per draw and per dispatch, +//! docs/VALIDATION.md, "The matrix") are measured with. +//! +//! [`InstructionCounter`] counts one thread, in user space alone. That is the form an unprivileged +//! process may open at `perf_event_paranoid` 2 (the lab's Linux nodes all run at 2): a counter +//! that also counts the kernel is refused there. +//! +//! A hybrid x86 CPU has one performance-monitoring unit per core type (`cpu_core`, `cpu_atom`, and +//! on some parts `cpu_lowpower`), and the generic hardware event counts on one of them only: a +//! thread that ran on another core type loses the instructions it retired there (an i9-13900H read +//! 16.0 million of a 25.6-million-instruction loop moved over its CPUs; a Core Ultra 9 275HX read +//! 0 of one that stayed on its efficiency cores). So where the kernel lists such units, the +//! counter opens the event on each and sums them. +//! +//! Only Linux offers the counters (read here on its little-endian targets): elsewhere +//! [`InstructionCounter::new`] answers [`io::ErrorKind::Unsupported`], and a test records no +//! `instructions` line there. + +use std::io; +use std::marker::PhantomData; + +/// User-space instructions retired by the thread that made it, summed over every core type. +/// +/// It counts the thread that called [`InstructionCounter::new`], so it is neither `Send` nor +/// `Sync`. Each [`InstructionCounter::measure`] counts its own work alone. +pub struct InstructionCounter { + #[cfg(all(target_os = "linux", target_endian = "little"))] + events: Vec, + #[cfg(not(all(target_os = "linux", target_endian = "little")))] + never: std::convert::Infallible, + _thread: PhantomData<*const ()>, +} + +impl InstructionCounter { + /// Opens the counters for the calling thread. An error is the kernel's refusal (for one, + /// `perf_event_paranoid` above 2, or no hardware counters in a virtual machine), or + /// [`io::ErrorKind::Unsupported`] off Linux. + pub fn new() -> io::Result { + #[cfg(all(target_os = "linux", target_endian = "little"))] + { + let events = linux::core_events()? + .into_iter() + .map(linux::open) + .collect::>>()?; + Ok(Self { + events, + _thread: PhantomData, + }) + } + #[cfg(not(all(target_os = "linux", target_endian = "little")))] + { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "user-space instruction counters are read through Linux's perf_event_open alone", + )) + } + } + + /// Runs `work` on this thread and returns its result with the user-space instructions the + /// thread retired meanwhile. The count includes a few instructions of the counters' own + /// switching, the same in every call. + pub fn measure(&mut self, work: impl FnOnce() -> R) -> io::Result<(R, u64)> { + #[cfg(all(target_os = "linux", target_endian = "little"))] + { + for event in &self.events { + linux::control(event, linux::IOC_RESET)?; + } + for event in &self.events { + linux::control(event, linux::IOC_ENABLE)?; + } + let result = work(); + for event in &self.events { + linux::control(event, linux::IOC_DISABLE)?; + } + let mut retired = 0; + for event in &self.events { + retired += linux::read(event)?; + } + Ok((result, retired)) + } + #[cfg(not(all(target_os = "linux", target_endian = "little")))] + { + let _ = work; + match self.never {} + } + } +} + +#[cfg(all(target_os = "linux", target_endian = "little"))] +mod linux { + use std::fs::{self, File}; + use std::io::{self, Read}; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + + /// `PERF_TYPE_HARDWARE` and its `PERF_COUNT_HW_INSTRUCTIONS`. + const TYPE_HARDWARE: u32 = 0; + const HW_INSTRUCTIONS: u64 = 1; + /// `perf_event_attr`'s bit fields `disabled`, `exclude_kernel` and `exclude_hv`, in a + /// little-endian target's bit order. + const DISABLED: u64 = 1 << 0; + const EXCLUDE_KERNEL: u64 = 1 << 5; + const EXCLUDE_HV: u64 = 1 << 6; + /// `PERF_FLAG_FD_CLOEXEC`: the descriptor does not pass to a child the test starts. + const FLAG_FD_CLOEXEC: libc::c_ulong = 1 << 3; + /// `PERF_EVENT_IOC_ENABLE`, `_DISABLE` and `_RESET` (`_IO('$', n)`). + pub(super) const IOC_ENABLE: libc::c_ulong = 0x2400; + pub(super) const IOC_DISABLE: libc::c_ulong = 0x2401; + pub(super) const IOC_RESET: libc::c_ulong = 0x2403; + /// Where the kernel lists its performance-monitoring units, each with its `type` number. + const UNITS: &str = "/sys/bus/event_source/devices"; + + /// `struct perf_event_attr` as the kernel first defined it (`PERF_ATTR_SIZE_VER0`), which + /// every later kernel still takes: its `type`, `size`, `config` and bit-field word, at their + /// byte offsets, everything else zero. + const ATTR_SIZE: usize = 64; + const ATTR_TYPE: usize = 0; + const ATTR_SIZE_FIELD: usize = 4; + const ATTR_CONFIG: usize = 8; + const ATTR_FLAGS: usize = 40; + + /// The instructions event's `config` for each core type: on a hybrid x86 CPU (units named + /// `cpu_*`), the event on that unit (its `type` in bits 32 to 63); otherwise the generic one. + pub(super) fn core_events() -> io::Result> { + let mut events = Vec::new(); + if let Ok(units) = fs::read_dir(UNITS) { + for unit in units { + let unit = unit?; + if !unit.file_name().to_string_lossy().starts_with("cpu_") { + continue; + } + let kind = fs::read_to_string(unit.path().join("type"))?; + let kind: u64 = kind.trim().parse().map_err(|error| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("{}/type: {error}", unit.path().display()), + ) + })?; + events.push((kind << 32) | HW_INSTRUCTIONS); + } + } + if events.is_empty() { + events.push(HW_INSTRUCTIONS); + } + Ok(events) + } + + /// The calling thread's user-space instructions event of `config`, disabled until enabled. + pub(super) fn open(config: u64) -> io::Result { + let mut attr = [0u8; ATTR_SIZE]; + attr[ATTR_TYPE..ATTR_TYPE + 4].copy_from_slice(&TYPE_HARDWARE.to_ne_bytes()); + attr[ATTR_SIZE_FIELD..ATTR_SIZE_FIELD + 4] + .copy_from_slice(&(ATTR_SIZE as u32).to_ne_bytes()); + attr[ATTR_CONFIG..ATTR_CONFIG + 8].copy_from_slice(&config.to_ne_bytes()); + attr[ATTR_FLAGS..ATTR_FLAGS + 8] + .copy_from_slice(&(DISABLED | EXCLUDE_KERNEL | EXCLUDE_HV).to_ne_bytes()); + let (thread, any_cpu, no_group): (libc::pid_t, libc::c_int, libc::c_int) = (0, -1, -1); + // SAFETY: `attr` is a valid `perf_event_attr` of the size it states and outlives the + // call; pid 0 and cpu -1 name the calling thread on any CPU, with no group. + let fd = unsafe { + libc::syscall( + libc::SYS_perf_event_open, + attr.as_ptr(), + thread, + any_cpu, + no_group, + FLAG_FD_CLOEXEC, + ) + }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: the kernel just returned this descriptor, and nothing else owns it. + Ok(File::from(unsafe { + OwnedFd::from_raw_fd(fd as libc::c_int) + })) + } + + /// One `ioctl` without an argument on `event`. + pub(super) fn control(event: &File, request: libc::c_ulong) -> io::Result<()> { + // SAFETY: an event descriptor this module opened, and a request that takes no argument. + if unsafe { libc::ioctl(event.as_raw_fd(), request as _, 0) } < 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } + + /// The count of `event` (read format 0: the value alone). + pub(super) fn read(mut event: &File) -> io::Result { + let mut value = [0; 8]; + event.read_exact(&mut value)?; + Ok(u64::from_ne_bytes(value)) + } +} + +#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] +mod tests { + use super::InstructionCounter; + use std::path::Path; + + /// Iterations of the fixed loop on each CPU. + const ITERATIONS: u64 = 200_000; + + /// Whether this host lets an unprivileged process count its own user-space instructions: a + /// hardware unit the kernel lists, and `perf_event_paranoid` at 2 or below. + fn counters_offered() -> bool { + let paranoid = std::fs::read_to_string("/proc/sys/kernel/perf_event_paranoid") + .ok() + .and_then(|level| level.trim().parse::().ok()); + let units = Path::new("/sys/bus/event_source/devices"); + let unit = units.join("cpu").exists() + || std::fs::read_dir(units).is_ok_and(|entries| { + entries + .flatten() + .any(|entry| entry.file_name().to_string_lossy().starts_with("cpu_")) + }); + unit && paranoid.is_some_and(|level| level <= 2) + } + + /// The CPUs this thread may run on. + fn allowed_cpus() -> Vec { + // SAFETY: a zeroed `cpu_set_t` is an empty set, filled in by the call. + let mut set: libc::cpu_set_t = unsafe { std::mem::zeroed() }; + // SAFETY: `set` is a valid `cpu_set_t` of the size passed. + let got = unsafe { libc::sched_getaffinity(0, std::mem::size_of_val(&set), &mut set) }; + assert_eq!( + got, + 0, + "sched_getaffinity: {}", + std::io::Error::last_os_error() + ); + (0..libc::CPU_SETSIZE as usize) + // SAFETY: `cpu` is below `CPU_SETSIZE`. + .filter(|&cpu| unsafe { libc::CPU_ISSET(cpu, &set) }) + .collect() + } + + /// Pins this thread to `cpus`. + fn pin(cpus: &[usize]) { + // SAFETY: a zeroed `cpu_set_t` is an empty set. + let mut set: libc::cpu_set_t = unsafe { std::mem::zeroed() }; + for &cpu in cpus { + // SAFETY: `cpu` came from `allowed_cpus`, so it is below `CPU_SETSIZE`. + unsafe { libc::CPU_SET(cpu, &mut set) }; + } + // SAFETY: `set` is a valid `cpu_set_t` of the size passed. + let got = unsafe { libc::sched_setaffinity(0, std::mem::size_of_val(&set), &set) }; + assert_eq!( + got, + 0, + "sched_setaffinity: {}", + std::io::Error::last_os_error() + ); + } + + /// Exactly two instructions per iteration: a decrement and a branch. + fn fixed_loop(iterations: u64) { + // SAFETY: the loop touches only its own register. + unsafe { + std::arch::asm!( + "2:", + "dec {n}", + "jnz 2b", + n = inout(reg) iterations => _, + options(nomem, nostack), + ); + } + } + + /// The fixed loop counts its two instructions per iteration although it runs on every CPU + /// this thread may use in turn, every core type of a hybrid CPU among them: a counter that + /// counted one core type alone would come up short by the others' share. The record it prints + /// follows the counter itself across commits in the matrix. + #[test] + fn a_fixed_loop_counts_its_instructions_on_every_core_type() { + if !counters_offered() { + let refusal = InstructionCounter::new().err(); + assert!( + refusal.is_some(), + "the host offers no counters, yet a counter opened" + ); + println!("INSTRUCTIONS-UNAVAILABLE: {}", refusal.unwrap()); + return; + } + let cpus = allowed_cpus(); + let mut counter = InstructionCounter::new().expect("the host offers counters"); + let run = |counter: &mut InstructionCounter| { + counter + .measure(|| { + for &cpu in &cpus { + pin(&[cpu]); + fixed_loop(ITERATIONS); + } + }) + .expect("reading the counters") + .1 + }; + // The first round loads what the later ones reuse. + run(&mut counter); + let counts = [run(&mut counter), run(&mut counter)]; + pin(&cpus); + let expected = 2 * ITERATIONS * cpus.len() as u64; + for count in counts { + // The pinning between the loops adds its own instructions, a few hundred per CPU. + assert!( + (expected..expected + expected / 200).contains(&count), + "{count} user-space instructions counted for {expected} on {} CPUs", + cpus.len() + ); + } + println!( + "M2V-MATRIX instructions instruction_counter/per_1000_iterations {}", + counts[0] * 1000 / (ITERATIONS * cpus.len() as u64) + ); + } +} diff --git a/crates/metal2vulkan-devtools/src/lib.rs b/crates/metal2vulkan-devtools/src/lib.rs index 5f7138fcc..05b590ba2 100644 --- a/crates/metal2vulkan-devtools/src/lib.rs +++ b/crates/metal2vulkan-devtools/src/lib.rs @@ -5,8 +5,9 @@ //! ([`linked_signatures`]), a tool's identity, the MoltenVK toolchain the MSL //! checks reproduce, and the generated-program fuzzers ([`fuzz`]) the product's CPU-interpreter //! tests and validation's device tests both run, the extended-range bicubic table both check -//! ([`xr_bicubic`]), and the store-buffering litmus kernel both compile -//! ([`litmus`]). +//! ([`xr_bicubic`]), the store-buffering litmus kernel both compile +//! ([`litmus`]), and the counter of a thread's user-space instructions the matrix's +//! instructions-per-draw records are measured with ([`instructions`]). //! //! Scratch directories every suite's temporaries go in ([`scratch`]): one root under the OS temp //! directory, each run's directory removed when its owner drops and, when its owner is killed @@ -26,6 +27,7 @@ use std::path::{Path, PathBuf}; use std::process::Stdio; pub mod fuzz; +pub mod instructions; pub mod linked_signatures; pub mod litmus; pub mod metallib; diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 33058cc61..65e95a6e4 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -261,6 +261,60 @@ RUSTFLAGS='-Dwarnings --cfg m2v_gpu' cargo nextest run --release -p metal2vulkan --all-features -j 1 -E 'test(/_fuzz::.*_on_the_device/)' ``` +## The matrix + +`scripts/matrix/matrix run SHA` checks one commit on every lab GPU, on lavapipe and on the Windows +host at once, through the lab's potluck cluster, and attaches the results to the commit as a git +note under `refs/notes/matrix`: one JSON document per commit, kept in the local repository and +never pushed. `scripts/matrix/matrix show SHA` prints a note's verdicts, one line per leg. +CONTRIBUTING.md says how to run it. + +A leg is one GPU, named by its PCI `vendor:device`, or `lavapipe`. Each GPU runs on one node, and +the nodes run at once; a node with several leg GPUs runs them in turn in one job that holds them. + +| Leg | Runs | Built | +|---|---|---| +| Each GPU of a Linux node | `metal2vulkan-rt`'s tests under `--cfg m2v_gpu`, the GPU chosen by `VK_DRIVER_FILES` and, on Mesa, `MESA_VK_DEVICE_SELECT='vendor:device!'` | Once per commit as a nextest archive on a CPU node, carried to the GPU nodes, which only run it. The archive holds its build's paths, so every node lays the tree out at the same per-commit path. Its binaries run only where the builder's do: a node of another CPU builds its own, in a job that holds no GPU | +| The Windows host's GPU | The same tests, built on the host under MSYS2 CLANG64 (the pinned nightly's `x86_64-pc-windows-gnullvm` toolchain) | On the host, in a job that holds no GPU | +| `lavapipe` | The gate's suites and the device tests in one build under `--cfg m2v_cpu_icd` (`cargo nextest run --workspace`, then the doctests), `LP_NUM_THREADS=1` | In place, on the builder | + +A leg passes when every suite passed and no rule below fails. Its line names the device and +driver as `vulkaninfo` reported them, the node, the tests passed of those run, the records, the +base it was compared with and the job. + +### Records and rules + +A test records a value by printing one line on its standard output; the matrix collects the lines +of passing and failing tests alike: + +```text +M2V-MATRIX / +``` + +The value is an unsigned integer, and a key appears once per leg. The base is the nearest +first-parent ancestor whose note holds the same leg. + +| Kind | What it counts | Fails when | +|---|---|---| +| `metric` | A deterministic count per frame or per command buffer: submissions, passes, barriers, bytes copied, pipelines created | It is larger than the base's | +| `instructions` | User-space CPU instructions per draw or per dispatch | It is more than 1% over the base's | +| `gauge` | Live objects of one resource kind, the key ending in the point it was read at: `@100` and `@200` (loop iterations), `@drop` (after the device dropped) | `@drop` is not 0, or `@200` differs from `@100` | +| `time` | Nanoseconds | Only as a cross-GPU outlier: its ratio to the base's is more than 1.25 times the median of that ratio over at least 3 GPUs | + +Every cache has a test that fills it past its capacity and records its gauge. + +`metal2vulkan_devtools::instructions::InstructionCounter` measures `instructions`: the calling +thread's user-space instructions from Linux's `perf_event_open`, the form an unprivileged process +may open at `perf_event_paranoid` 2. On a hybrid x86 CPU it sums the event over each core type's +unit, since the generic event counts on one of them only. Off Linux it opens nothing, so the +Windows leg records no `instructions`. + +The rules have their own tests, which need no cluster: + +```sh +PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts/matrix +``` + ## The Linux gate in a container `scripts/linux-gate` runs CI's Linux job, or any command, in a container: Ubuntu 26.04 pinned by diff --git a/scripts/matrix/matrix b/scripts/matrix/matrix new file mode 100755 index 000000000..11ba09449 --- /dev/null +++ b/scripts/matrix/matrix @@ -0,0 +1,586 @@ +#!/usr/bin/env python3 +"""The per-commit matrix: one commit's checks on every lab GPU, lavapipe and the Windows host, +run through potluck, with the results attached to the commit as a git note +(refs/notes/matrix, one JSON document per commit; local, never pushed). + + scripts/matrix/matrix run [SHA] [--legs LEG,...] [--dry-run] + scripts/matrix/matrix show [SHA] + +SHA defaults to development's tip. A leg is a GPU, named by its PCI vendor:device +(`1002:744c`), or `lavapipe`. docs/VALIDATION.md ("The matrix") has the legs, the records and +the rules; CONTRIBUTING.md has how to run it. + +The cluster's own facts come from potluck (its nodes, their GPUs and CPUs) and from +~/.config/metal2vulkan/matrix.json: + + {"builders": [{"node": "A", "gate": "SHELL COMMAND", "portable": true}, {"node": "B"}], + "setup": {"A": "SHELL"}, + "skip_gpus": ["vendor:device"]} + +The first builder whose gate command exits 0 (no gate: always) builds the GPU legs' test archive +and runs the lavapipe leg. Its archive runs on every Linux node when it is `portable`, else only +on nodes of its CPU model; any other node builds its own. `setup` is shell each job on that node +runs first. A GPU in `skip_gpus` gets no leg. +""" + +import fcntl +import json +import math +import os +import re +import shlex +import shutil +import subprocess +import sys +import threading +import time +from datetime import datetime, timezone +from pathlib import Path + +sys.dont_write_bytecode = True +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import results # noqa: E402 + +REPO = Path(__file__).resolve().parents[2] +CONFIG = Path.home() / ".config/metal2vulkan/matrix.json" +STATE = Path.home() / ".cache/metal2vulkan-matrix" +TREE = STATE / "tree" +NOTES = "refs/notes/matrix" +ARCHIVE = "m2v-matrix-gpu.tar.zst" +#: A node's Vulkan driver manifest by PCI vendor, and whether Mesa's device select picks the GPU. +ICDS = {"1002": ("radeon", True), "10de": ("nvidia", False), "8086": ("intel", False)} +#: (RAM GiB, minutes) of each job kind before a run of it was measured. +DEFAULTS = {"build": (6, 15), "gpu": (4, 15), "lavapipe": (32, 60), "winbuild": (12, 30), "winrun": (4, 15)} +#: The awk filter between nextest and the job's log: every line up to the summary, then only the +#: captured output of tests that did not pass, and the records of those that did. +KEEP = r"""f == 0 { print; if ($0 ~ /^ *Summary \[/) f = 1; next } +/^ +[A-Z][A-Z-]* +\[ *[0-9.]+s\]/ { k = ($1 != "PASS") } +k || /M2V-MATRIX / { print }""" +NEXTEST_OUT = "--no-fail-fast --success-output final --failure-output final" +DEVICE_LINES = (r"""vulkaninfo --summary 2>/dev/null | tr -d '\r' | sed -n 's/^[[:space:]]*\(deviceName\|driverName\|driverInfo\)[[:space:]]*= */M2V-DEVICE '"{leg}"' \1 /p'""") + + +def log(msg): + print(f"{time.strftime('%H:%M:%S')} {msg}", flush=True) + + +def git(*args, cwd=REPO, check=True): + r = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True) + if check and r.returncode: + sys.exit(f"git {' '.join(args)}: {r.stderr.strip()}") + return r.stdout.strip() + + +def potluck(*args, cwd=None): + return subprocess.run(["potluck", *args], cwd=cwd or TREE, capture_output=True, text=True, errors="replace") + + +def load(path, default): + try: + return json.loads(path.read_text()) + except (OSError, ValueError): + return default + + +def save(path, value): + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(".tmp") + tmp.write_text(json.dumps(value, indent=1, sort_keys=True) + "\n") + tmp.replace(path) + + +# --- notes ------------------------------------------------------------------------------------- + +def note(sha): + r = subprocess.run(["git", "notes", f"--ref={NOTES}", "show", sha], cwd=REPO, capture_output=True, text=True) + return json.loads(r.stdout) if r.returncode == 0 else None + + +def base_of(sha, leg_id): + """The nearest first-parent ancestor of SHA whose note has leg LEG_ID: (sha, that leg).""" + noted = {line.split()[1] for line in git("notes", f"--ref={NOTES}", "list").splitlines() if line} + for commit in git("rev-list", "--first-parent", "--max-count=500", f"{sha}~1", check=False).splitlines(): + if commit in noted: + leg = (note(commit) or {}).get("legs", {}).get(leg_id) + if leg: + return commit, leg + return None, None + + +# --- the plan ------------------------------------------------------------------------------------ + +class Leg: + def __init__(self, leg_id, node, gpu=None, icd=None, select=False): + self.id, self.node, self.gpu, self.icd, self.select = leg_id, node, gpu, icd, select + self.job = None + self.started = self.ended = None + + +def plan(nodes, cfg, only): + """The legs: each lab GPU on one node, the nodes' loads kept even (the GPUs on fewest nodes + placed first), lavapipe, and each Windows GPU on its host.""" + skip = set(cfg.get("skip_gpus", [])) + linux = {n: f for n, f in nodes.items() if f["os"] == "linux"} + where = {} + for name, facts in sorted(linux.items()): + for g in facts["gpus"]: + vd = f"{g['vendor']}:{g['device']}" + if g["vendor"] in ICDS and vd not in skip: + where.setdefault(vd, []).append((name, g["id"])) + load_of, legs = {n: 0 for n in linux}, [] + for vd, places in sorted(where.items(), key=lambda item: (len(item[1]), item[0])): + icd, select = ICDS[vd.split(":")[0]] + taken = {(leg.node, leg.icd) for leg in legs if not leg.select} + places = [p for p in places if select or (p[0], icd) not in taken] + if not places: + log(f"{vd}: every node holding it already runs a leg on its driver, which cannot pick between two") + continue + node, gpu = min(places, key=lambda p: (load_of[p[0]], p[0])) + load_of[node] += 1 + legs.append(Leg(vd, node, gpu, icd, select)) + for name, facts in sorted(nodes.items()): + if facts["os"] == "windows": + legs += [Leg(f"{g['vendor']}:{g['device']}", name, g["id"]) for g in facts["gpus"] + if f"{g['vendor']}:{g['device']}" not in skip] + legs.append(Leg("lavapipe", None)) + if only: + unknown = set(only) - {leg.id for leg in legs} + if unknown: + sys.exit(f"no such leg: {', '.join(sorted(unknown))}") + legs = [leg for leg in legs if leg.id in only] + return legs + + +def builder(cfg, nodes): + for b in cfg["builders"]: + if b["node"] in nodes and (not b.get("gate") or subprocess.run(b["gate"], shell=True).returncode == 0): + return b + sys.exit("no builder is up with its gate open") + + +# --- job scripts --------------------------------------------------------------------------------- + +def linux_head(short, setup): + """Every Linux job: the per-commit source path the GPU legs' archive is built and run at (the + archive holds the build's paths, so every node lays the tree out at the same one), without + the observations, which nothing it runs reads.""" + return f"""set -u +M="$HOME/.cache/metal2vulkan-matrix"; S="$M/src-{short}"; mkdir -p "$M" +find "$M" -maxdepth 1 -name 'src-*' ! -name 'src-{short}' -mmin +720 -exec rm -rf {{}} + +{setup} +lay_out() {{ + flock "$M/.lock" sh -c 'test -d "$1" || {{ t="$1.tmp.$$" && rm -rf "$t" && mkdir -p "$t" && git archive HEAD -- . ":(exclude)crates/metal2vulkan-validation/corpus/observations" | tar -x -C "$t" && mv "$t" "$1"; }}' sh "$S" +}} +""" + + +def build_script(short, setup): + return linux_head(short, setup) + f"""W=$PWD +lay_out || exit 3 +cd "$S" && RUSTFLAGS='--cfg m2v_gpu' CARGO_TARGET_DIR="$S/target/gpucfg" cargo nextest archive -p metal2vulkan-rt --all-features --archive-file "$W/{ARCHIVE}" +rc=$? +echo "M2V-BUILD exit $rc" +cd "$W" && rm -rf "$S" +exit $rc +""" + + +def gpu_script(short, setup, legs, mirror, rev): + runs = "\n".join(" ".join(["leg", leg.id, leg.icd, shlex.quote(leg.id + "!" if leg.select else "")]) + for leg in legs) + return linux_head(short, setup) + f"""lay_out || exit 3 +A="$PWD/{ARCHIVE}" +git --git-dir="${mirror}" cat-file blob "{rev}:{ARCHIVE}" > "$A" || exit 3 +KEEP='{KEEP}' +all=0 +leg() {{ + echo "M2V-LEG $1 begin" + ( + export VK_DRIVER_FILES="/usr/share/vulkan/icd.d/$2_icd.json" + if [ -n "$3" ]; then export MESA_VK_DEVICE_SELECT="$3"; fi + {DEVICE_LINES.format(leg="$1")} + cargo nextest run --archive-file "$A" --workspace-remap "$S" {NEXTEST_OUT} 2>&1 | awk "$KEEP" + exit ${{PIPESTATUS[0]}} + ) + rc=$? + echo "M2V-SUITE $1 rt exit $rc" + [ $rc -eq 0 ] || all=1 +}} +{runs} +rm -rf "$S" "$A" +m="${mirror}"; rm -rf "$m" "${{m%.git}}.lock" "${{m%.git}}.worktrees.lock" +exit $all +""" + + +def lavapipe_script(setup): + """The gate's suites and the CPU-ICD device tests in one build: `m2v_cpu_icd` adds the device + tests to every test the plain build has.""" + return f"""set -u +{setup} +export RUSTFLAGS='--cfg m2v_cpu_icd' RUSTDOCFLAGS='--cfg m2v_cpu_icd' CARGO_TARGET_DIR=target/cpuicd +export VK_DRIVER_FILES=/usr/share/vulkan/icd.d/lvp_icd.json LP_NUM_THREADS=1 +KEEP='{KEEP}' +echo "M2V-LEG lavapipe begin" +{DEVICE_LINES.format(leg="lavapipe")} +cargo nextest run --workspace --all-features {NEXTEST_OUT} 2>&1 | awk "$KEEP" +a=${{PIPESTATUS[0]}} +echo "M2V-SUITE lavapipe workspace exit $a" +cargo test --workspace --all-features --doc 2>&1 | grep -E '^(test result:|error)|FAILED|panicked' +d=${{PIPESTATUS[0]}} +echo "M2V-SUITE lavapipe doctests exit $d" +[ $a -eq 0 ] && [ $d -eq 0 ] +""" + + +def windows_head(): + """Windows jobs build and run under MSYS2 CLANG64 with the pinned nightly's gnullvm host + toolchain; `scripts/rustc-wrapper` is a shell script, which cargo cannot run there.""" + return """set -u +export PATH="/c/msys64/clang64/bin:$PATH" RUSTC_WRAPPER= +export RUSTUP_TOOLCHAIN="$(sed -n 's/^channel = "\\(.*\\)"$/\\1/p' rust-toolchain.toml)-x86_64-pc-windows-gnullvm" +export RUSTFLAGS='--cfg m2v_gpu' CARGO_TARGET_DIR=target/gpucfg +""" + + +def winbuild_script(): + return windows_head() + """cargo nextest run -p metal2vulkan-rt --all-features --no-run +rc=$? +echo "M2V-BUILD exit $rc" +exit $rc +""" + + +def winrun_script(leg): + return windows_head() + f"""KEEP='{KEEP}' +echo "M2V-LEG {leg.id} begin" +{DEVICE_LINES.format(leg=leg.id)} +cargo nextest run -p metal2vulkan-rt --all-features {NEXTEST_OUT} 2>&1 | awk "$KEEP" +rc=${{PIPESTATUS[0]}} +echo "M2V-SUITE {leg.id} rt exit $rc" +exit $rc +""" + + +# --- running jobs -------------------------------------------------------------------------------- + +class Run: + def __init__(self, sha, cfg, nodes, legs, build_node, rdir): + self.sha, self.short, self.cfg, self.nodes = sha, sha[:12], cfg, nodes + self.legs, self.build_node, self.rdir = legs, build_node, rdir + self.stats = load(STATE / "stats.json", {}) + self.spaces = load(STATE / "workspaces.json", {}) + self.lock = threading.Lock() + self.jobs, self.carries, self.failures = [], [], {} + self.build_info = None + + def setup(self, node): + return self.cfg.get("setup", {}).get(node, "") + + def size(self, kind, node): + """RAM and timeout from this kind's last measured runs on NODE: 1.3x the peak (a run that + peaked at its reservation keeps it; one ended over it gets 1.5x), 1.5x the longest.""" + ram, minutes = DEFAULTS[kind] + runs = self.stats.get(f"{kind}@{node}", [])[-3:] + if runs: + ram = max(math.ceil(r["ram"] * 1.5) if r["killed"] else + r["ram"] if r["peak"] >= 0.95 * r["ram"] else math.ceil(r["peak"] * 1.3 + 0.5) + for r in runs) + minutes = max(5, math.ceil(1.5 * max(r["minutes"] for r in runs))) + return max(ram, 2), minutes + + def job(self, kind, node, script, name, gpus=(), carry=None, space=None): + """Dispatch SCRIPT on NODE, wait for it, and return (exit code, output, job record). + SPACE names a workspace kept for this kind on this node across runs (incremental builds, + and no fresh checkout of the tree).""" + ram, minutes = self.size(kind, node) + args = ["dispatch", "--json", "--priority", "5", "--kill-on-stall", "--label", "agent=matrix", + "--label", f"matrix={self.short}", "--on", f"node={node}", "--ram", str(ram), + "--timeout", f"{minutes}m"] + if self.nodes[node]["os"] == "windows": + args += ["--on", "os=windows"] + for gpu in gpus: + args += ["--gpu", gpu] + if carry: + args += ["--carry", carry] + key = f"{space}@{node}" if space else None + if key: + args += ["--hold", "24h"] + cmd = ["--", "bash", "-c", script] + with self.lock: + ws = self.spaces.get(key) if key else None + r = potluck(*args, *(["--workspace", ws, "--advance"] if ws else []), *cmd) + if r.returncode and ws: + log(f"{name}: workspace {ws} refused ({r.stderr.strip()[:200]}); a fresh one") + potluck("release", ws) + with self.lock: + self.spaces.pop(key, None) + r = potluck(*args, *cmd) + if r.returncode: + return None, f"dispatch failed: {r.stderr.strip()[:500]}", None + jid = json.loads(r.stdout.strip().splitlines()[-1])["job"] + log(f"{name}: job {jid} on {node} ({ram} GiB, {minutes} min)") + with self.lock: + self.jobs.append(jid) + w = subprocess.run(["potluck", "wait", jid], cwd=TREE, capture_output=True, text=True, errors="replace") + out = w.stdout + w.stderr + (self.rdir / f"{name}.log").write_text(out) + rec = self.record(jid) + if rec: + peak = rec.get("usage", {}).get("peak_mem_bytes", 0) / 2**30 + took = (rec.get("ended_at", 0) - rec.get("started_at", 0)) / 60000 + killed = rec.get("exit_code") == 137 and peak >= 0.95 * ram + with self.lock: + self.stats.setdefault(f"{kind}@{node}", []).append( + dict(ram=ram, peak=round(peak, 2), minutes=round(took, 2), killed=killed)) + self.stats[f"{kind}@{node}"] = self.stats[f"{kind}@{node}"][-6:] + if key and rec.get("workspace"): + self.spaces[key] = rec["workspace"] + log(f"{name}: job {jid} ended {w.returncode}") + return w.returncode, out, rec + + def record(self, jid): + r = potluck("status", "--json") + try: + status = json.loads(r.stdout) + except ValueError: + return None + for kind in ("recent", "running"): + for j in status.get(kind, []): + if j.get("id") == jid: + return j + return None + + def carry(self, node, rec): + """Copy a finished build's archive out of its workspace into a git repository of its own, + which GPU jobs name with --carry. Returns (--carry value, mirror variable, commit).""" + name = f"m2v-matrix-{self.short}-{re.sub(r'[^A-Za-z0-9]', '', node)[-12:]}" + cdir = STATE / "carry" / name + shutil.rmtree(cdir, ignore_errors=True) + cdir.mkdir(parents=True) + git("init", "-q", cwd=cdir) + r = potluck("cp", f"{rec['workspace']}:{ARCHIVE}", str(cdir / ARCHIVE)) + if r.returncode: + return None + git("add", ARCHIVE, cwd=cdir) + git("-c", "user.name=matrix", "-c", "user.email=matrix@localhost", "commit", "-q", "-m", self.sha, cwd=cdir) + (cdir / ARCHIVE).unlink() + with self.lock: + self.carries.append(name) + rev = git("rev-parse", "HEAD", cwd=cdir) + return f"{cdir}@{rev}", "POTLUCK_MIRROR_" + re.sub(r"[^A-Za-z0-9_]", "_", name), rev + + def fail(self, legs, why, rec=None): + with self.lock: + for leg in legs: + self.failures[leg.id] = why + if rec: + leg.job = rec.get("id") + + def linux_build(self, node, label): + """Build the GPU legs' archive on NODE (no GPU held) and carry it: (carry, mirror, rev).""" + code, out, rec = self.job("build", node, build_script(self.short, self.setup(node)), label, space="build") + if code != 0 or not rec: + return None, f"the build ({label}, job {rec and rec.get('id')}) failed: exit {code}" + if node == self.build_node["node"]: + self.build_info = dict(node=node, job=rec["id"], minutes=round((rec["ended_at"] - rec["started_at"]) / 60000, 2)) + made = self.carry(node, rec) + return made, None if made else f"the archive of job {rec['id']} could not be copied" + + def gpu_node(self, node, legs, ready): + """One node's GPU legs, in turn, in one job holding their GPUs. READY gives the carry.""" + made, why = ready() + if not made: + return self.fail(legs, why) + carry, mirror, rev = made + for leg in legs: + leg.started = time.time() + code, out, rec = self.job("gpu", node, gpu_script(self.short, self.setup(node), legs, mirror, rev), + f"gpu-{node}", gpus=[leg.gpu for leg in legs], carry=carry, space="gpu") + self.finish(legs, code, out, rec) + + def finish(self, legs, code, out, rec): + parsed = results.parse_job(out or "") + for leg in legs: + leg.ended, leg.job = time.time(), rec and rec.get("id") + if leg.id not in parsed: + self.fail([leg], f"job {leg.job} ran no leg {leg.id} (exit {code}): {(out or '').strip()[-300:]}") + leg.parsed = parsed.get(leg.id) + + def windows(self, leg): + code, out, rec = self.job("winbuild", leg.node, winbuild_script(), f"winbuild-{leg.id}", space="win") + if code != 0: + return self.fail([leg], f"the Windows build (job {rec and rec.get('id')}) failed: exit {code}", rec) + leg.started = time.time() + code, out, rec = self.job("winrun", leg.node, winrun_script(leg), f"win-{leg.id}", gpus=[leg.gpu], space="win") + self.finish([leg], code, out, rec) + + def lavapipe(self, leg): + leg.node = self.build_node["node"] + leg.started = time.time() + code, out, rec = self.job("lavapipe", leg.node, lavapipe_script(self.setup(leg.node)), "lavapipe", + space="lavapipe") + self.finish([leg], code, out, rec) + + def go(self): + """Every chain of jobs at once: the builder (its build, its GPU legs if any, lavapipe), + each other Linux GPU node (its own build where the builder's archive cannot run there, + then its legs), and each Windows host (build, then its leg).""" + b = self.build_node["node"] + by_node = {} + for leg in self.legs: + if leg.id != "lavapipe" and self.nodes[leg.node]["os"] == "linux": + by_node.setdefault(leg.node, []).append(leg) + built = threading.Event() + box = {} + + def from_builder(): + built.wait() + return box["made"] + + threads = [] + + def start(fn, *args): + t = threading.Thread(target=fn, args=args) + t.start() + threads.append(t) + + def builder_chain(): + box["made"] = self.linux_build(b, "build") if by_node else (None, "no GPU leg on Linux") + built.set() + if b in by_node: + self.gpu_node(b, by_node[b], from_builder) + if lavapipe: + self.lavapipe(lavapipe[0]) + + lavapipe = [leg for leg in self.legs if leg.id == "lavapipe"] + start(builder_chain) + cpu = self.nodes[b]["cpu_model"] + for node, legs in sorted(by_node.items()): + if node == b: + continue + if self.build_node.get("portable") or self.nodes[node]["cpu_model"] == cpu: + start(self.gpu_node, node, legs, from_builder) + else: + start(self.gpu_node, node, legs, lambda node=node: self.linux_build(node, f"build-{node}")) + for leg in self.legs: + if leg.id != "lavapipe" and self.nodes[leg.node]["os"] == "windows": + start(self.windows, leg) + for t in threads: + t.join() + + def cleanup(self): + save(STATE / "stats.json", self.stats) + save(STATE / "workspaces.json", self.spaces) + mirrors = Path.home() / ".local/state/potluck/mirrors" + for name in self.carries: + shutil.rmtree(STATE / "carry" / name, ignore_errors=True) + for m in mirrors.glob(f"{name}-*"): + shutil.rmtree(m) if m.is_dir() else m.unlink() + + +# --- commands ------------------------------------------------------------------------------------ + +def leg_entry(run, leg): + """A leg's document in the note, judged against its base where only one leg is needed.""" + parsed = getattr(leg, "parsed", None) or dict(device={}, suites={}) + records, problems = results.leg_records(parsed) + base_sha, base = base_of(run.sha, leg.id) + problems += [run.failures[leg.id]] if leg.id in run.failures else [] + problems += results.leg_problems(parsed, records, base and base["records"]) + if not parsed["suites"] and leg.id not in run.failures: + problems.append("no suite reported") + dev = parsed["device"] + return dict( + node=leg.node, gpu=leg.id if leg.id != "lavapipe" else None, job=leg.job, + device=dev.get("deviceName"), driver=" ".join(v for v in (dev.get("driverName"), dev.get("driverInfo")) if v) or None, + started=leg.started and datetime.fromtimestamp(leg.started, timezone.utc).isoformat(timespec="seconds"), + minutes=leg.started and leg.ended and round((leg.ended - leg.started) / 60, 2), + suites={name: {k: s[k] for k in ("exit", "run", "passed", "failed")} for name, s in parsed["suites"].items()}, + records=records, base=base_sha, base_records=base and base["records"], problems=problems) + + +def run_cmd(sha, only, dry): + cfg = load(CONFIG, None) + if not cfg or not cfg.get("builders"): + sys.exit(f"{CONFIG}: missing or without builders (see {__file__}'s header)") + STATE.mkdir(parents=True, exist_ok=True) + lock = open(STATE / "run.lock", "w") + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + sys.exit("another matrix run is live: runs share their workspaces, so they never overlap") + if not (TREE / ".git").exists(): + subprocess.run([str(REPO / "scripts/lean-tree"), "worktree", str(TREE), "matrix/tree", sha], check=True) + git("switch", "-q", "--detach", sha, cwd=TREE) + git("branch", "-q", "-D", "matrix/tree") + git("switch", "-q", "--detach", sha, cwd=TREE) + if git("status", "--porcelain", cwd=TREE): + sys.exit(f"{TREE} has changes: it must be a clean checkout of {sha}") + nodes_json = json.loads(potluck("nodes", "--json").stdout) + nodes = {n["facts"]["node"]: n["facts"] for n in nodes_json["nodes"] if n.get("alive")} + legs = plan(nodes, cfg, only) + b = builder(cfg, nodes) + for leg in legs: + log(f"leg {leg.id}: {leg.node or b['node']}" + (f" ({leg.icd})" if leg.icd else "")) + log(f"builder {b['node']}{' (portable)' if b.get('portable') else ''}") + if dry: + return + started = time.time() + rdir = STATE / "runs" / f"{sha[:12]}-{time.strftime('%m%d-%H%M%S')}" + rdir.mkdir(parents=True) + run = Run(sha, cfg, nodes, legs, b, rdir) + try: + run.go() + finally: + run.cleanup() + entries = {leg.id: leg_entry(run, leg) for leg in legs} + gpu = {k: e for k, e in entries.items() if e["gpu"]} + for leg_id, problems in results.time_outliers( + {k: e["records"]["time"] for k, e in gpu.items()}, + {k: (e["base_records"] or {}).get("time", {}) for k, e in gpu.items()}).items(): + entries[leg_id]["problems"] += problems + doc = note(sha) or dict(sha=sha, runs=[], legs={}) + for leg_id, e in entries.items(): + e.pop("base_records") + e["verdict"] = "fail" if e["problems"] else "pass" + doc["legs"][leg_id] = e + wall = round((time.time() - started) / 60, 2) + doc["runs"].append(dict(started=datetime.fromtimestamp(started, timezone.utc).isoformat(timespec="seconds"), + minutes=wall, legs=sorted(entries), build=run.build_info, jobs=sorted(run.jobs))) + path = rdir / "note.json" + path.write_text(json.dumps(doc, indent=1, sort_keys=True) + "\n") + git("notes", f"--ref={NOTES}", "add", "-f", "-F", str(path), sha) + for leg_id in sorted(entries): + print(results.verdict_line(leg_id, doc["legs"][leg_id])) + failed = sum(1 for e in entries.values() if e["verdict"] != "pass") + print(f"matrix {sha[:12]}: {len(entries) - failed} of {len(entries)} legs pass, {wall} min wall; note {NOTES}") + return 1 if failed else 0 + + +def show_cmd(sha): + doc = note(sha) + if not doc: + sys.exit(f"no matrix note on {sha}") + for leg_id in sorted(doc["legs"]): + print(results.verdict_line(leg_id, doc["legs"][leg_id])) + last = doc["runs"][-1] + print(f"matrix {sha[:12]}: last run {last['started']}, {last['minutes']} min wall, jobs {' '.join(last['jobs'])}") + + +def main(argv): + if not argv or argv[0] not in ("run", "show"): + sys.exit(__doc__) + rest = [a for a in argv[1:] if not a.startswith("--")] + only = None + if "--legs" in argv: + only = argv[argv.index("--legs") + 1].split(",") + rest.remove(argv[argv.index("--legs") + 1]) + sha = git("rev-parse", "--verify", f"{rest[0] if rest else 'development'}^{{commit}}") + if argv[0] == "show": + return show_cmd(sha) + return run_cmd(sha, only, "--dry-run" in argv) + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/matrix/results.py b/scripts/matrix/results.py new file mode 100644 index 000000000..28a667ab8 --- /dev/null +++ b/scripts/matrix/results.py @@ -0,0 +1,182 @@ +"""The matrix's reading of its jobs' output and its comparison rules (docs/VALIDATION.md, "The +matrix"). Pure functions over text and dictionaries: `test_results.py` checks each one. + +A job prints, per leg, `M2V-LEG begin`, `M2V-DEVICE ` lines, then each +suite's output followed by `M2V-SUITE exit `. A test records a value as a line +`M2V-MATRIX / ` on its standard output. +""" + +import re +import statistics + +KINDS = ("metric", "instructions", "gauge", "time") +#: A gauge's key ends in the point it was read at. +GAUGE_POINTS = ("100", "200", "drop") +#: `instructions` may grow by this fraction over the base before it fails. +INSTRUCTIONS_BAND = 0.01 +#: A GPU's slowdown over the base fails past this multiple of the median slowdown... +TIME_OUTLIER = 1.25 +#: ...of at least this many GPUs. +TIME_MIN_GPUS = 3 + +RECORD = re.compile(r"^\s*M2V-MATRIX (\S+) (\S+) (\S+)\s*$") +LEG = re.compile(r"^M2V-LEG (\S+) begin\s*$") +DEVICE = re.compile(r"^M2V-DEVICE (\S+) (\S+) (.*?)\s*$") +SUITE = re.compile(r"^M2V-SUITE (\S+) (\S+) exit (-?\d+)\s*$") +# nextest: `Summary [ 0.003s] 2 tests run: 1 passed, 1 failed, 0 skipped`. +NEXTEST_SUMMARY = re.compile(r"^\s*Summary \[[^\]]*\]\s+(\d+) tests? run: (\d+) passed") +# nextest's status line of a test that did not pass, as the run prints it. +NEXTEST_FAILED = re.compile( + r"^\s*(FAIL|SIGSEGV|SIGABRT|SIGBUS|SIGILL|SIGKILL|SIGTERM|ABORT|TIMEOUT|LEAK-FAIL)" + r" \[[^\]]*\]\s+(?:\(\s*\d+/\d+\)\s+)?(\S+ \S+)" +) +# libtest (doctests): `test result: ok. 12 passed; 0 failed; 1 ignored; ...`. +LIBTEST_RESULT = re.compile(r"^test result: \w+\. (\d+) passed; (\d+) failed") +LIBTEST_FAILED = re.compile(r"^test (.+) \.\.\. FAILED\s*$") + + +def empty_records(): + return {kind: {} for kind in KINDS} + + +def parse_suite(lines): + """One suite's output: tests run and passed, the tests that failed, and its records, with + the problems of the records themselves (an unknown kind, a value that is not a count, a key + recorded twice, a gauge key without its point).""" + run = passed = 0 + failed, problems = [], [] + records = empty_records() + summary = False + for line in lines: + m = NEXTEST_SUMMARY.match(line) + if m and not summary: + summary = True + run, passed = int(m.group(1)), int(m.group(2)) + continue + m = LIBTEST_RESULT.match(line) + if m: + run += int(m.group(1)) + int(m.group(2)) + passed += int(m.group(1)) + continue + m = NEXTEST_FAILED.match(line) or LIBTEST_FAILED.match(line) + if m: + name = m.group(m.lastindex) + if name not in failed: + failed.append(name) + continue + m = RECORD.match(line) + if m: + kind, key, value = m.groups() + if kind not in KINDS: + problems.append(f"record {key}: unknown kind {kind}") + elif not value.isdigit(): + problems.append(f"record {kind} {key}: {value} is not a count") + elif kind == "gauge" and key.rpartition("@")[2] not in GAUGE_POINTS: + problems.append(f"gauge {key}: the key ends in none of @100, @200, @drop") + elif key in records[kind]: + problems.append(f"record {kind} {key}: recorded twice") + else: + records[kind][key] = int(value) + return dict(run=run, passed=passed, failed=failed, records=records, problems=problems) + + +def parse_job(text): + """A job's legs: {leg: {"device": {field: value}, "suites": {suite: parsed suite + "exit"}}}. + Output between a leg's markers belongs to the suite whose `M2V-SUITE` line ends it.""" + legs, leg, buffer = {}, None, [] + for raw in text.splitlines(): + line = raw.rstrip("\r") + m = LEG.match(line) + if m: + leg = legs.setdefault(m.group(1), dict(device={}, suites={})) + buffer = [] + continue + m = DEVICE.match(line) + if m and m.group(1) in legs: + legs[m.group(1)]["device"].setdefault(m.group(2), m.group(3)) + continue + m = SUITE.match(line) + if m and m.group(1) in legs: + suite = parse_suite(buffer) + suite["exit"] = int(m.group(3)) + legs[m.group(1)]["suites"][m.group(2)] = suite + buffer = [] + continue + if leg is not None: + buffer.append(line) + return legs + + +def leg_records(leg): + """A leg's records over its suites, and the problems of a key two suites both recorded.""" + records, problems = empty_records(), [] + for suite in leg["suites"].values(): + for kind, values in suite["records"].items(): + for key, value in values.items(): + if key in records[kind]: + problems.append(f"record {kind} {key}: recorded by two suites") + records[kind][key] = value + return records, problems + + +def leg_problems(leg, records, base): + """What fails a leg: a suite that failed, a record's own problem, and the rules against the + base leg's records (BASE None: no base, so only the rules that need none).""" + problems = [] + for name, suite in leg["suites"].items(): + if suite["exit"] != 0 or suite["failed"]: + shown = ", ".join(suite["failed"][:5]) + (" ..." if len(suite["failed"]) > 5 else "") + problems.append(f"suite {name} exited {suite['exit']}" + + (f", {len(suite['failed'])} failed: {shown}" if suite["failed"] else "")) + problems += suite["problems"] + gauges = records["gauge"] + for key, value in sorted(gauges.items()): + name, _, point = key.rpartition("@") + if point == "drop" and value != 0: + problems.append(f"gauge {name}: {value} live at device drop") + if point == "200" and f"{name}@100" in gauges and value != gauges[f"{name}@100"]: + problems.append(f"gauge {name}: {gauges[f'{name}@100']} at iteration 100, {value} at 200") + if base is not None: + for key, value in sorted(records["metric"].items()): + was = base["metric"].get(key) + if was is not None and value > was: + problems.append(f"metric {key}: {was} -> {value}") + for key, value in sorted(records["instructions"].items()): + was = base["instructions"].get(key) + if was is not None and value > was * (1 + INSTRUCTIONS_BAND): + problems.append(f"instructions {key}: {was} -> {value} (+{(value / was - 1) * 100:.1f}%)") + return problems + + +def time_outliers(times, bases): + """Timing fails only as a cross-GPU outlier. TIMES and BASES: {leg: {key: nanoseconds}} of + the GPU legs now and at their bases. For each key that at least TIME_MIN_GPUS legs timed at + both, a leg whose slowdown (now over base) is more than TIME_OUTLIER times the legs' median + slowdown fails. Returns {leg: [problems]}.""" + out = {} + keys = {key for values in times.values() for key in values} + for key in sorted(keys): + ratios = {leg: values[key] / bases[leg][key] + for leg, values in times.items() + if key in values and bases.get(leg, {}).get(key)} + if len(ratios) < TIME_MIN_GPUS: + continue + median = statistics.median(ratios.values()) + for leg, ratio in sorted(ratios.items()): + if ratio > TIME_OUTLIER * median: + out.setdefault(leg, []).append( + f"time {key}: {ratio:.2f}x its base, against a median of {median:.2f}x " + f"over {len(ratios)} GPUs") + return out + + +def verdict_line(leg_id, leg): + """The one line `run` and `show` print for a leg of a note.""" + tests = ", ".join(f"{name} {s['passed']}/{s['run']}" for name, s in leg.get("suites", {}).items()) + counted = sum(len(values) for values in leg.get("records", {}).values()) + where = " ".join(part for part in (leg.get("device"), leg.get("driver")) if part) + head = f"{'PASS' if leg['verdict'] == 'pass' else 'FAIL'} {leg_id:10} {where or '?'} on {leg.get('node', '?')}" + tail = f"{tests or 'no suite ran'}; {counted} records; base {(leg.get('base') or 'none')[:10]}; job {leg.get('job', '?')}" + if leg["problems"]: + tail += " | " + " | ".join(leg["problems"][:4]) + (" ..." if len(leg["problems"]) > 4 else "") + return f"{head}: {tail}" diff --git a/scripts/matrix/test_results.py b/scripts/matrix/test_results.py new file mode 100644 index 000000000..b92870b78 --- /dev/null +++ b/scripts/matrix/test_results.py @@ -0,0 +1,147 @@ +"""The matrix's reading of job output and its rules, on inputs whose answers are known. + + PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts/matrix + +The job output below is nextest's own layout (0.9.140 and 0.9.151 print it alike): status lines, +the summary, then each test's captured output, indented, after a header naming the test. +""" + +import unittest + +import results + +NEXTEST = """\ + Starting 3 tests across 1 binary + FAIL [ 0.002s] (1/3) metal2vulkan-rt tests::breaks + PASS [ 0.003s] (2/3) metal2vulkan-rt tests::counts + PASS [ 0.003s] (3/3) metal2vulkan-rt tests::loops + Summary [ 0.003s] 3 tests run: 2 passed, 1 failed, 0 skipped + PASS [ 0.003s] (2/3) metal2vulkan-rt tests::counts + stdout ─── + M2V-MATRIX metric compute/submissions 3 + M2V-MATRIX instructions compute/per_dispatch 2000 + PASS [ 0.003s] (3/3) metal2vulkan-rt tests::loops + stdout ─── + M2V-MATRIX gauge loop/buffers@100 12 + M2V-MATRIX gauge loop/buffers@200 12 + M2V-MATRIX gauge loop/buffers@drop 0 + M2V-MATRIX time loop/gpu 1000 + FAIL [ 0.002s] (1/3) metal2vulkan-rt tests::breaks + stdout ─── + test tests::breaks ... FAILED + test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 2 filtered out +""" + + +def job(*legs): + """A job's output holding LEGS: (leg, suite, exit, output) each.""" + out = [] + for leg, suite, code, text in legs: + out += [f"M2V-LEG {leg} begin", f"M2V-DEVICE {leg} deviceName AMD Radeon RX 7900 XTX (RADV NAVI31)", + f"M2V-DEVICE {leg} driverInfo Mesa 26.2.6", text, f"M2V-SUITE {leg} {suite} exit {code}"] + return "\n".join(out) + "\n" + + +class ParseTests(unittest.TestCase): + def test_a_suite_gives_its_counts_failures_and_records(self): + legs = results.parse_job(job(("1002:744c", "rt", 100, NEXTEST))) + suite = legs["1002:744c"]["suites"]["rt"] + self.assertEqual((suite["run"], suite["passed"], suite["exit"]), (3, 2, 100)) + self.assertEqual(suite["failed"], ["metal2vulkan-rt tests::breaks"]) + self.assertEqual(suite["records"]["metric"], {"compute/submissions": 3}) + self.assertEqual(suite["records"]["instructions"], {"compute/per_dispatch": 2000}) + self.assertEqual(suite["records"]["gauge"], {"loop/buffers@100": 12, "loop/buffers@200": 12, + "loop/buffers@drop": 0}) + self.assertEqual(suite["records"]["time"], {"loop/gpu": 1000}) + self.assertEqual(suite["problems"], []) + self.assertEqual(legs["1002:744c"]["device"]["driverInfo"], "Mesa 26.2.6") + + def test_output_goes_to_the_leg_and_suite_it_came_in(self): + text = job(("1002:744c", "rt", 0, " M2V-MATRIX metric a/x 1"), + ("10de:1e87", "rt", 0, " M2V-MATRIX metric a/x 2")) + legs = results.parse_job(text) + self.assertEqual(legs["1002:744c"]["suites"]["rt"]["records"]["metric"], {"a/x": 1}) + self.assertEqual(legs["10de:1e87"]["suites"]["rt"]["records"]["metric"], {"a/x": 2}) + + def test_a_doctest_suite_counts_libtest_results(self): + text = job(("lavapipe", "doctests", 101, "test result: ok. 10 passed; 0 failed; 1 ignored\n" + "test src/lib.rs - f (line 3) ... FAILED\n" + "test result: FAILED. 4 passed; 1 failed; 0 ignored")) + suite = results.parse_job(text)["lavapipe"]["suites"]["doctests"] + self.assertEqual((suite["run"], suite["passed"]), (15, 14)) + self.assertEqual(suite["failed"], ["src/lib.rs - f (line 3)"]) + + def test_malformed_records_are_problems(self): + suite = results.parse_suite([ + "M2V-MATRIX colour a/x 1", + "M2V-MATRIX metric a/y 1.5", + "M2V-MATRIX gauge a/buffers 3", + "M2V-MATRIX metric a/z 1", + "M2V-MATRIX metric a/z 2", + ]) + self.assertEqual(len(suite["problems"]), 4, suite["problems"]) + self.assertEqual(suite["records"]["metric"], {"a/z": 1}) + + +def leg_of(records, code=0): + suite = dict(run=1, passed=1 if code == 0 else 0, failed=[], records=records, problems=[], exit=code) + return dict(device={}, suites={"rt": suite}) + + +def recs(**kinds): + out = results.empty_records() + out.update(kinds) + return out + + +class RuleTests(unittest.TestCase): + def problems(self, now, base): + leg = leg_of(now) + records, problems = results.leg_records(leg) + return problems + results.leg_problems(leg, records, base) + + def test_a_metric_fails_on_any_increase_and_passes_a_decrease(self): + base = recs(metric={"a/barriers": 4, "a/passes": 2}) + self.assertEqual(self.problems(recs(metric={"a/barriers": 4, "a/passes": 1}), base), []) + self.assertEqual(self.problems(recs(metric={"a/barriers": 5, "a/passes": 2}), base), + ["metric a/barriers: 4 -> 5"]) + + def test_instructions_fail_past_one_percent(self): + base = recs(instructions={"a/per_draw": 10000}) + self.assertEqual(self.problems(recs(instructions={"a/per_draw": 10100}), base), []) + self.assertEqual(len(self.problems(recs(instructions={"a/per_draw": 10101}), base)), 1) + + def test_no_base_compares_nothing_but_the_gauges(self): + now = recs(metric={"a/x": 9}, gauge={"l/b@100": 1, "l/b@200": 2, "l/b@drop": 1}) + self.assertEqual(self.problems(now, None), + ["gauge l/b: 1 at iteration 100, 2 at 200", "gauge l/b: 1 live at device drop"]) + + def test_flat_gauges_that_reach_zero_pass(self): + now = recs(gauge={"l/b@100": 7, "l/b@200": 7, "l/b@drop": 0}) + self.assertEqual(self.problems(now, None), []) + + def test_a_failed_suite_fails_the_leg(self): + leg = leg_of(recs(), code=100) + self.assertEqual(results.leg_problems(leg, recs(), None), ["suite rt exited 100"]) + + def test_two_suites_recording_one_key_is_a_problem(self): + leg = leg_of(recs(metric={"a/x": 1})) + leg["suites"]["other"] = dict(leg["suites"]["rt"]) + self.assertEqual(results.leg_records(leg)[1], ["record metric a/x: recorded by two suites"]) + + def test_time_fails_only_as_a_cross_gpu_outlier(self): + bases = {"a": {"t": 100}, "b": {"t": 200}, "c": {"t": 50}, "d": {"t": 10}} + # Every GPU 10% slower: no outlier. + times = {"a": {"t": 110}, "b": {"t": 220}, "c": {"t": 55}, "d": {"t": 11}} + self.assertEqual(results.time_outliers(times, bases), {}) + # One GPU 50% slower while the others hold: it alone fails. + times["d"] = {"t": 15} + self.assertEqual(list(results.time_outliers(times, bases)), ["d"]) + + def test_time_needs_three_gpus(self): + bases = {"a": {"t": 100}, "b": {"t": 100}} + self.assertEqual(results.time_outliers({"a": {"t": 100}, "b": {"t": 300}}, bases), {}) + + +if __name__ == "__main__": + unittest.main()