From 2124331c53f05ac8d8a5c6f7002637af53ec161f Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 19 Nov 2026 11:19:30 +0900 Subject: [PATCH] ci(bench): measure scheduler scaling and RTLMeter designs on CodSpeed CodSpeed's ARM64 Macro Runner now measures, besides compile time: - `benches/scaling.rs`: N clock-alias domains (`assign l1clk = clk`, as in VeeR-EH1's 1,451 copies) and N clock-gated flops, at N = 16 and 1024, compile and 1,000-cycle simulation, so the history shows the slope; and a fixed 64-lane combinational design with ONE comb `$display`, `assert final`, DPI-C call in `always @*`, `string` array or `final` block next to the same design without it, so a construct that moves the whole design to a slower path shows as a gap to the baseline. - `benches/rtlmeter.rs`: `celox run` (native, O2, two-state, one thread) on VeeR-EL2, VeeR-EH1 and XuanTie-E906 CoreMark, reporting the analysis and code generation time and the per-cycle time of a fixed `+max_cycles` window from the command's CELOX_TEST_TIMING record. BlackParrot 1x1 runs nightly, on dispatch or with the `bench-blackparrot` label. `run-rtlmeter-bench.py codspeed-layout` lays the cases of `benchmarks/rtlmeter/codspeed_manifest.json` out at the pinned RTLMeter revision, merging configuration include files, common arguments and Verilator parameter overrides as RTLMeter does. The workflow runs on every push to master, each commit in a concurrency group of its own so a burst of pushes keeps every measurement, and on pull requests labelled `bench`, instead of only daily. It also builds with `cranelift`, which the compilation benchmark requires (every run since 2026-10-25 failed to build), and every manual schedule takes at least two rounds, the fewest samples the walltime analysis accepts (one round panicked). The runner (32 GB, 16 Cortex-A72 cores) lost its connection twice: in the build, linking four fat-LTO binaries at once, and in the benchmarks, where the walltime profiler sampled every process with 8 KiB stack copies for tens of minutes (the compilation benchmark alone takes 9.6 minutes and 6.9 GB on x86-64). The benchmarks now build with thin LTO and run without the profiler; each RTLMeter run is killed and fails its benchmark past 20 GiB resident or an hour and prints its start and peak memory, and the build and run print memory and disk use each minute. Locally (x86-64, heliodor-dev profile) the scaling benchmarks show `fallback/deferred_assert` at 4.9x and `fallback/string_array` at 2.2x the baseline, and clock-alias simulation at 0.05 us/cycle for N = 16 against 2.8 us/cycle for N = 1024; they peak at 1.0 GB resident. Change-Id: I7ff427b9a4206224c1bb7c47e198ae0c83625094 --- .github/workflows/actions.lock | 1 + .github/workflows/codspeed.yml | 80 ++++- CONTRIBUTING.md | 16 +- benchmarks/rtlmeter/codspeed_manifest.json | 40 +++ crates/celox/Cargo.toml | 10 + crates/celox/benches/compilation.rs | 18 +- crates/celox/benches/rtlmeter.rs | 368 +++++++++++++++++++++ crates/celox/benches/scaling.rs | 240 ++++++++++++++ docs/benchmarks/index.md | 56 +++- docs/ja/benchmarks/index.md | 42 ++- scripts/benchmark-workflows.test.mjs | 93 +++++- scripts/run-rtlmeter-bench.py | 102 ++++++ scripts/tests/test_rtlmeter_bench.py | 84 +++++ scripts/with-resource-log.sh | 20 ++ 14 files changed, 1112 insertions(+), 58 deletions(-) create mode 100644 benchmarks/rtlmeter/codspeed_manifest.json create mode 100644 crates/celox/benches/rtlmeter.rs create mode 100644 crates/celox/benches/scaling.rs create mode 100644 scripts/with-resource-log.sh diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 6a32968efd3..7550f381d00 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -46,6 +46,7 @@ workflows: - 'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066' '.github/workflows/codspeed.yml': - 'actions/checkout@v7' + - 'actions/setup-python@v7' - 'codspeedhq/action@v5' - 'dtolnay/rust-toolchain@master' - 'swatinem/rust-cache@v2' diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index 4f68187f790..76c549d1b81 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -1,22 +1,46 @@ -name: Compile-time Benchmarks +name: CodSpeed Benchmarks +# Compile-time, scheduler-scaling and RTLMeter benchmarks on CodSpeed's ARM64 +# Macro Runner (walltime). Every push to master is measured, so a regression +# shows on its commit; a pull request is measured only with the `bench` label +# (`bench-blackparrot` adds the BlackParrot case) because a run takes one to +# two hours of the runner. on: schedule: - cron: "17 2 * * *" + push: + branches: [master] + paths-ignore: + - "docs/**" + - "**/*.md" + pull_request: + types: [opened, reopened, synchronize, labeled] workflow_dispatch: inputs: runner_probe: description: Check Macro Runner availability without building or benchmarking type: boolean default: false + blackparrot: + description: Also measure BlackParrot 1x1 CoreMark (about an hour more) + type: boolean + default: false concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: false + # One group per commit outside pull requests: GitHub keeps only one pending + # run per group, so a shared master group would drop the measurements of a + # burst of pushes. A newer push to a pull request replaces its older run. + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} env: CARGO_INCREMENTAL: "0" CARGO_PROFILE_BENCH_DEBUG: "0" + # Fat LTO links of four celox binaries (three benchmarks and the CLI) at + # once, with the debug info CodSpeed adds, starved the 32 GB Cortex-A72 + # runner until it lost its connection (and took over 40 minutes). + CARGO_PROFILE_BENCH_LTO: thin + PYTHONDONTWRITEBYTECODE: "1" permissions: {} @@ -32,14 +56,35 @@ jobs: codspeed: name: CodSpeed - if: inputs.runner_probe != true - timeout-minutes: 60 + # A pull request runs only with a benchmark label, and adding another + # label does not start it again. + if: >- + inputs.runner_probe != true && (github.event_name != 'pull_request' || + ((contains(github.event.pull_request.labels.*.name, 'bench') || + contains(github.event.pull_request.labels.*.name, 'bench-blackparrot')) && + (github.event.action != 'labeled' || github.event.label.name == 'bench' || + github.event.label.name == 'bench-blackparrot'))) + timeout-minutes: 210 runs-on: codspeed-macro-arm64-graviton-ubuntu-22-04 outputs: run-id: ${{ steps.benchmarks.outputs.run-id }} permissions: contents: read id-token: write + env: + # BlackParrot compiles for about 8 minutes on x86-64 and loads its + # program for about 3 more, several times that on this runner: nightly, + # on request, or with the `bench-blackparrot` label. + BLACKPARROT: ${{ github.event_name == 'schedule' || inputs.blackparrot == true || contains(github.event.pull_request.labels.*.name, 'bench-blackparrot') }} + CELOX_RTLMETER_LAYOUT: ${{ github.workspace }}/work/rtlmeter-layout + # Each RTLMeter run is killed (and fails its benchmark) past 20 GiB + # resident, so one case cannot take the 32 GB runner down. + CELOX_RTLMETER_MEMORY_LIMIT_MIB: "20480" + # The walltime profiler samples every benchmarked process, the celox + # commands of the RTLMeter cases included, copying 8 KiB of stack per + # sample for tens of minutes; with it the runner lost its connection + # during the benchmarks. Measurements do not need it. + CODSPEED_PROFILER_ENABLED: "false" steps: - uses: actions/checkout@v7 @@ -54,16 +99,31 @@ jobs: with: tool: cargo-codspeed@5.0.1 - - name: Build compile-time benchmarks - run: cargo codspeed build --locked --measurement-mode walltime -p celox --bench compilation + - uses: actions/setup-python@v7 + with: + python-version: "3.13" + + - name: Lay out the pinned RTLMeter cases + run: | + python -m pip install -r benchmarks/rtlmeter/requirements.txt + python scripts/run-rtlmeter-bench.py prepare "$RUNNER_TEMP/rtlmeter" + optional=() + if [ "$BLACKPARROT" = true ]; then optional=(--optional); fi + python scripts/run-rtlmeter-bench.py codspeed-layout "$RUNNER_TEMP/rtlmeter" "$CELOX_RTLMETER_LAYOUT" "${optional[@]}" + + - name: Build benchmarks + # `compilation` measures the Cranelift backend too. Memory and disk + # are logged each minute, so a starved runner leaves evidence. + run: bash scripts/with-resource-log.sh cargo codspeed build --locked --measurement-mode walltime -p celox --features cranelift --bench compilation --bench scaling --bench rtlmeter - - name: Run compile-time benchmarks + - name: Run benchmarks id: benchmarks - timeout-minutes: 15 + timeout-minutes: 120 uses: CodSpeedHQ/action@v5 with: mode: walltime - run: cargo codspeed run --measurement-mode walltime -p celox --bench compilation + # Memory and disk each minute, so a starved runner leaves evidence. + run: bash scripts/with-resource-log.sh cargo codspeed run --measurement-mode walltime -p celox --bench compilation --bench scaling --bench rtlmeter report: name: Report CodSpeed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1236bc0c9e4..2140a8c152b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -167,15 +167,19 @@ Affected PR and full CI retain small nested-write semantic regressions on interpreter, native and Cranelift backends in both two-state and four-state modes, wide-value latch checks, and a small sorter compilation smoke test. The 257/512-bit per-bit graph cases and sorter sizes 4/8/16/32 are measured by -`benches/compilation.rs` in the existing daily/manual CodSpeed workflow. +`benches/compilation.rs` in the CodSpeed workflow. Compilation benchmarks use CodSpeed walltime measurement on its ARM64 Graviton Macro Runner: CPU simulation made -a single 512-bit case take tens of minutes. The benchmark step has a 15-minute -timeout and the complete job a 60-minute limit; a timeout is reported as failure. +a single 512-bit case take tens of minutes. The same job runs `benches/scaling.rs` +and `benches/rtlmeter.rs`; its benchmark step has a 120-minute timeout and the +complete job a 210-minute limit; a timeout is reported as failure. The +benchmarks build with thin LTO: fat LTO of all of them at once starved the +32 GB runner. The organization runner group must allow this public repository to use CodSpeed Macro Runners. Simulation and walltime measurements have separate baselines. Nested-write benchmarks reuse the same semantic assertions as the small tests. -Scaling cases use one iteration without per-case warmups or adaptive sampling; +Scaling cases run twice (the fewest samples the walltime analysis accepts), +without per-case warmups or adaptive sampling; a small counter warms process-global analyzer state before measurement. Sorter sizes are separate CodSpeed measurements; performance comparisons replace process-time ratio assertions in ordinary tests. Failures use the existing @@ -184,7 +188,7 @@ CodSpeed reporting workflow. Build and run them with the same CodSpeed harness as CI: ```sh -cargo codspeed build --locked --measurement-mode walltime -p celox --bench compilation +cargo codspeed build --locked --measurement-mode walltime -p celox --features cranelift --bench compilation cargo codspeed run --measurement-mode walltime -p celox --bench compilation ``` @@ -452,7 +456,7 @@ Local validation uses the behavior-based matrix above. | Daily at 01:17 UTC (10:17 JST) | Full `ci.yml` on the default branch, with every change-classifier output enabled. Includes native/WASI NAPI, JS/browser tests, ARM64, script tests, and all ordinary Celox workspace tests. | | Daily from `nightly.yml` at 02:43 UTC (11:43 JST) | Dispatch the same full CI on `develop`, with detection of its Veryl dependency lane. Queue nightly packages. External simulator comparisons and Heliodor are not dispatched on `develop`. | | Daily at 01:47 UTC (10:47 JST) | `bench.yml` measures Rust, Verilator, and TypeScript on one host and publishes master history. Manual dispatch supports branch measurements. | -| Daily at 02:17 UTC (11:17 JST) | `codspeed.yml` measures compile time on the default branch using CPU simulation. Execution failures and CodSpeed performance-check failures open or update a branch issue; the next healthy run closes it. Manual dispatch supports branch measurements. PRs, merge groups, and pushes do not run CodSpeed. | +| Every push to `master`, daily at 02:17 UTC (11:17 JST), and pull requests labelled `bench` | `codspeed.yml` measures compile time, scheduler scaling, whole-design fallbacks and RTLMeter designs on CodSpeed's ARM64 Macro Runner (walltime); see [Benchmarks](docs/benchmarks/index.md). Execution failures and CodSpeed performance-check failures on `master` and `develop` open or update a branch issue; the next healthy run closes it. Manual dispatch supports branch measurements; BlackParrot runs nightly, on dispatch with `blackparrot`, or with the `bench-blackparrot` label. Other PRs and merge groups do not run CodSpeed. | | Daily at 02:37 UTC (11:37 JST) | `heliodor-bench.yml` runs the complete master Linux suite on x86-64 and AArch64. Explicit manual selections retain focused suite runs and ARM64 profiling. PRs do not run this workflow; its tooling tests run in `Lint & Format` with the other script tests. | | Every full CI run | Run the pinned upstream `common_cells` Gray code SV TB through `celox run --project`, plus an assertion negative control. Logs are retained for 14 days and failures feed the Full CI issue. See [the reproduction instructions](conformance/common-cells/README.md). | | Daily at 03:47 UTC (12:47 JST) on the default branch, and on demand | Independent `external-comparisons.yml` runs every shared Veryl and SystemVerilog case against Verilator, Icarus, and xezim, with locked Nix tools. Run the live adapter tests normally marked ignored because they need external tools. Preserve reports and per-case diagnostics as artifacts for 14 days, including on failure; matrix failures do not cancel the other comparisons. | diff --git a/benchmarks/rtlmeter/codspeed_manifest.json b/benchmarks/rtlmeter/codspeed_manifest.json new file mode 100644 index 00000000000..cd1b0704599 --- /dev/null +++ b/benchmarks/rtlmeter/codspeed_manifest.json @@ -0,0 +1,40 @@ +{ + "schemaVersion": 1, + "contract": "rtlmeter-codspeed-v1", + "repository": "https://github.com/verilator/rtlmeter.git", + "revision": "4fdd6c3fd154e9b99d3a9d713cf3f4977e284f94", + "cases": { + "veer-el2-cmark": { + "design": "VeeR-EL2", + "configuration": "default", + "test": "cmark", + "window": 20000, + "rounds": 2 + }, + "veer-eh1-cmark": { + "design": "VeeR-EH1", + "configuration": "default", + "test": "cmark", + "window": 20000, + "rounds": 2 + }, + "e906-cmark": { + "design": "XuanTie-E906", + "test": "cmark", + "window": 100000, + "rounds": 2 + }, + "blackparrot-1x1-cmark": { + "design": "BlackParrot", + "configuration": "1x1", + "test": "cmark", + "window": 20000, + "rounds": 2, + "optional": true, + "diagnostics": [ + "mixed_timescale=warn", + "inferred_latch=warn" + ] + } + } +} diff --git a/crates/celox/Cargo.toml b/crates/celox/Cargo.toml index 87711ddcf5b..0be22789686 100644 --- a/crates/celox/Cargo.toml +++ b/crates/celox/Cargo.toml @@ -163,6 +163,16 @@ bench = false name = "tiered" harness = false +[[bench]] +name = "scaling" +harness = false + +# Needs the RTLMeter layout of `scripts/run-rtlmeter-bench.py codspeed-layout`. +[[bench]] +name = "rtlmeter" +harness = false +bench = false + [[example]] name = "sv_tests" path = "examples/sv_tests.rs" diff --git a/crates/celox/benches/compilation.rs b/crates/celox/benches/compilation.rs index 984d896b73d..5e36d1a6661 100644 --- a/crates/celox/benches/compilation.rs +++ b/crates/celox/benches/compilation.rs @@ -57,13 +57,13 @@ fn benchmark_compilation(c: &mut Criterion) { fn benchmark_scaling(c: &mut Criterion) { // Warm analyzer state before any measured span, including filtered runs. compile_default(COUNTER, "Top", Some(("N", 1))); - // Each large design runs once: no five-run warmup or adaptive resampling. - // Walltime uses this fixed schedule even for the largest graphs. + // Each large design runs twice, the fewest samples the walltime analysis + // accepts: no five-run warmup or adaptive resampling. Walltime uses this + // fixed schedule even for the largest graphs. + let twice = IterManualOptions::new().rounds(2); for n in [4, 8, 16, 32] { c.bench_function(&format!("compile/sorter_tree/n{n}"), |b| { - b.iter_manual_unstable(IterManualOptions::new(), || { - black_box(sorter_tree::compile(black_box(n))) - }); + b.iter_manual_unstable(twice, || black_box(sorter_tree::compile(black_box(n)))); }); } macro_rules! backend { @@ -74,7 +74,7 @@ fn benchmark_scaling(c: &mut Criterion) { c.bench_function( &format!("scaling/nested_write/{}/{state}/complete_{width}", $name), |b| { - b.iter_manual_unstable(IterManualOptions::new(), || { + b.iter_manual_unstable(twice, || { nested_write::complete!($build, black_box(width), four_state) }) }, @@ -83,7 +83,7 @@ fn benchmark_scaling(c: &mut Criterion) { c.bench_function( &format!("scaling/nested_write/{}/{state}/incomplete_512", $name), |b| { - b.iter_manual_unstable(IterManualOptions::new(), || { + b.iter_manual_unstable(twice, || { nested_write::incomplete!($build, black_box(512), four_state) }) }, @@ -95,9 +95,7 @@ fn benchmark_scaling(c: &mut Criterion) { backend!("native", build_native); backend!("cranelift", build_cranelift); c.bench_function("scaling/nested_write/strict_reject_512", |b| { - b.iter_manual_unstable(IterManualOptions::new(), || { - nested_write::strictly_reject(black_box(512)) - }); + b.iter_manual_unstable(twice, || nested_write::strictly_reject(black_box(512))); }); } diff --git a/crates/celox/benches/rtlmeter.rs b/crates/celox/benches/rtlmeter.rs new file mode 100644 index 00000000000..ffb0ad1122f --- /dev/null +++ b/crates/celox/benches/rtlmeter.rs @@ -0,0 +1,368 @@ +//! RTLMeter designs through the `celox` command, on CodSpeed's walltime +//! instrument. +//! +//! `scripts/run-rtlmeter-bench.py codspeed-layout SOURCE DIR` lays out the +//! cases of `benchmarks/rtlmeter/codspeed_manifest.json`; this benchmark runs +//! the cases in `CELOX_RTLMETER_LAYOUT=DIR` (none without it). Each run is +//! one `celox run --backend native -O O2 --two-state --threads 1 --report` +//! process that simulates a fixed window (`+max_cycles`), and reports two +//! benchmarks from the times the command records (`CELOX_TEST_TIMING`): +//! +//! - `rtlmeter//compile`: analysis and code generation (`compile_ns`); +//! - `rtlmeter//cycle`: the window's execution (`execute_ns`, which +//! includes the testbench's start-up such as program loading) divided by +//! its clock cycles. +//! +//! Both come from the same runs, so the compile time of a multi-minute +//! design is paid once per sample, not once per benchmark. The celox binary +//! is the one Cargo builds next to this benchmark, or `CELOX_RTLMETER_BIN`. +//! +//! A run whose resident memory passes `CELOX_RTLMETER_MEMORY_LIMIT_MIB` +//! (default [`MEMORY_LIMIT_MIB`]) or whose time passes +//! `CELOX_RTLMETER_TIMEOUT_SECS` (default [`TIMEOUT_SECS`]) is killed and +//! fails its benchmark, so one case cannot take the runner down. Each run +//! prints its start, peak memory and times, and leaves its output in +//! `/run/celox.log`. + +// The layout and binary come from the environment, and CodSpeed's harness +// reads its own. +#![allow(clippy::disallowed_methods)] + +use std::{ + path::{Path, PathBuf}, + process::{Command, ExitStatus, Stdio}, + sync::mpsc::{Receiver, Sender, channel}, + time::{Duration, Instant}, +}; + +/// Resident memory a run may use. CodSpeed's ARM64 Macro Runner has 32 GB; +/// VeeR-EH1 peaks at about 7 GB. +const MEMORY_LIMIT_MIB: u64 = 20 * 1024; +/// Time a run may take (a BlackParrot compile takes several minutes). +const TIMEOUT_SECS: u64 = 60 * 60; + +use codspeed_criterion_compat::{ + Criterion, IterManualOptions, + measurement::{Measurement, ValueFormatter, WallTime}, +}; + +/// A duration the measured routine reports instead of the wall time around +/// it: the routine sends it, the measurement of its round receives it. +struct Reported { + values: Receiver, + wall_time: WallTime, +} + +impl Measurement for Reported { + type Intermediate = (); + type Value = Duration; + + fn start(&self) { + // Drop values of unmeasured (warm-up) rounds. + while self.values.try_recv().is_ok() {} + } + + fn end(&self, (): ()) -> Duration { + self.values.try_iter().sum() + } + + fn add(&self, v1: &Duration, v2: &Duration) -> Duration { + *v1 + *v2 + } + + fn zero(&self) -> Duration { + Duration::ZERO + } + + fn to_f64(&self, value: &Duration) -> f64 { + value.as_nanos() as f64 + } + + fn formatter(&self) -> &dyn ValueFormatter { + self.wall_time.formatter() + } +} + +/// A case written by `codspeed-layout`. +struct Case { + name: String, + /// Holds `case.json`; the process runs in its `run` directory. + directory: PathBuf, + args: Vec, + window: u64, + rounds: u64, +} + +impl Case { + fn load(directory: PathBuf) -> Self { + let path = directory.join("case.json"); + let text = std::fs::read_to_string(&path) + .unwrap_or_else(|error| panic!("{}: {error}", path.display())); + let json: serde_json::Value = serde_json::from_str(&text) + .unwrap_or_else(|error| panic!("{}: {error}", path.display())); + let field = |key: &str| { + json.get(key) + .unwrap_or_else(|| panic!("{}: missing {key}", path.display())) + }; + Self { + name: field("name") + .as_str() + .expect("name is a string") + .to_string(), + args: field("args") + .as_array() + .expect("args is an array") + .iter() + .map(|arg| arg.as_str().expect("args are strings").to_string()) + .collect(), + window: field("window").as_u64().expect("window is a count"), + rounds: field("rounds").as_u64().expect("rounds is a count"), + directory, + } + } +} + +/// The times one run of a case recorded. +struct Run { + compile: Duration, + execute: Duration, + cycles: u64, +} + +impl Run { + fn per_cycle(&self) -> Duration { + self.execute / u32::try_from(self.cycles).expect("window fits u32") + } +} + +/// Output that a passing window never prints (as `accept` in +/// `scripts/run-rtlmeter-bench.py`). +const FAILURES: &[&str] = &[ + "TEST FAIL", + "TEST_FAIL", + "Time Out !!!", + "simulation finished with error", + "%Error:", + "$fatal", +]; + +fn failed(name: &str, status: &ExitStatus, output: &str, reason: &str) -> ! { + let lines: Vec<&str> = output.lines().collect(); + let tail = lines[lines.len().saturating_sub(40)..].join("\n"); + panic!("{name}: {reason} ({status}); last output:\n{tail}") +} + +/// Limits of one run of the `celox` command. +struct Limits { + memory_kib: u64, + timeout: Duration, +} + +impl Limits { + fn from_env() -> Self { + let number = |key: &str, default: u64| { + std::env::var(key) + .ok() + .map(|value| { + value + .parse::() + .unwrap_or_else(|_| panic!("{key}={value} is not a number")) + }) + .unwrap_or(default) + }; + Self { + memory_kib: number("CELOX_RTLMETER_MEMORY_LIMIT_MIB", MEMORY_LIMIT_MIB) * 1024, + timeout: Duration::from_secs(number("CELOX_RTLMETER_TIMEOUT_SECS", TIMEOUT_SECS)), + } + } +} + +/// The resident memory of process `pid` in KiB: (current, peak). +fn resident_kib(pid: u32) -> Option<(u64, u64)> { + let status = std::fs::read_to_string(format!("/proc/{pid}/status")).ok()?; + let field = |key: &str| { + status.lines().find_map(|line| { + line.strip_prefix(key)? + .trim() + .strip_suffix("kB")? + .trim() + .parse::() + .ok() + }) + }; + Some((field("VmRSS:")?, field("VmHWM:")?)) +} + +/// Run `command` to its end, killing it past `limits`. Returns its status, +/// its peak resident memory in KiB and why it was killed, if it was. +fn run_limited(command: &mut Command, limits: &Limits) -> (ExitStatus, u64, Option) { + let mut child = command.spawn().expect("celox starts"); + let start = Instant::now(); + let mut peak = 0; + let mut killed = None; + loop { + if let Some(status) = child.try_wait().expect("celox is waitable") { + return (status, peak, killed); + } + if killed.is_none() { + if let Some((current, high)) = resident_kib(child.id()) { + peak = peak.max(high); + if current > limits.memory_kib { + killed = Some(format!( + "killed at {} MiB resident, over the {} MiB limit", + current / 1024, + limits.memory_kib / 1024 + )); + } + } + if start.elapsed() > limits.timeout { + killed = Some(format!("killed after {:?}", limits.timeout)); + } + if killed.is_some() { + let _ = child.kill(); + } + } + std::thread::sleep(Duration::from_millis(100)); + } +} + +fn run_case(binary: &Path, case: &Case, limits: &Limits) -> Run { + let run_directory = case.directory.join("run"); + let cycles_file = run_directory.join("_rtlmeter_cycles.txt"); + let _ = std::fs::remove_file(&cycles_file); + let log = run_directory.join("celox.log"); + let log_file = std::fs::File::create(&log).expect("celox log is writable"); + let mut command = Command::new(binary); + command + .args(&case.args) + .current_dir(&run_directory) + .stdin(Stdio::null()) + .stdout(log_file.try_clone().expect("celox log handle")) + .stderr(log_file); + // No caller-specific simulator settings or extra workers. + for (key, _) in std::env::vars_os() { + if key.to_string_lossy().starts_with("CELOX_") { + command.env_remove(key); + } + } + command + .env("RAYON_NUM_THREADS", "1") + .env("RUST_LOG", "warn"); + println!("{}: run starts", case.name); + let (status, peak_kib, killed) = run_limited(&mut command, limits); + let text = String::from_utf8_lossy(&std::fs::read(&log).unwrap_or_default()).into_owned(); + macro_rules! fail { + ($($reason:tt)*) => { + failed(&case.name, &status, &text, &format!($($reason)*)) + }; + } + println!( + "{}: run ends ({status}), peak {} MiB resident", + case.name, + peak_kib / 1024 + ); + if let Some(reason) = killed { + fail!("{reason}"); + } + if !status.success() { + fail!("celox failed"); + } + if let Some(marker) = FAILURES.iter().find(|marker| text.contains(**marker)) { + fail!("the testbench reported a failure ({marker})"); + } + if !text.contains("RTLMeter: +max_cycles reached, exiting") { + fail!("the run ended before its window"); + } + let cycles = std::fs::read_to_string(&cycles_file) + .ok() + .and_then(|count| count.trim().parse::().ok()) + .unwrap_or_else(|| fail!("no RTLMeter cycle count")); + if cycles != case.window { + fail!("ran {cycles} cycles, not {}", case.window); + } + let timing = text + .lines() + .find(|line| line.starts_with("CELOX_TEST_TIMING ")) + .unwrap_or_else(|| fail!("no CELOX_TEST_TIMING record")); + let field = |key: &str| { + timing + .split_whitespace() + .find_map(|entry| entry.strip_prefix(key)?.strip_prefix('=')) + .and_then(|value| value.parse::().ok()) + .map(Duration::from_nanos) + .unwrap_or_else(|| fail!("no {key} in {timing}")) + }; + let run = Run { + compile: field("compile_ns"), + execute: field("execute_ns"), + cycles, + }; + println!( + "{}: compile {:.2} s, {cycles} cycles in {:.2} s ({:.2} us/cycle)", + case.name, + run.compile.as_secs_f64(), + run.execute.as_secs_f64(), + run.per_cycle().as_secs_f64() * 1e6, + ); + run +} + +fn benchmark_rtlmeter(c: &mut Criterion, reports: &Sender) { + let Some(layout) = std::env::var_os("CELOX_RTLMETER_LAYOUT").map(PathBuf::from) else { + println!("CELOX_RTLMETER_LAYOUT is not set; no RTLMeter case to run"); + return; + }; + let limits = Limits::from_env(); + let binary = std::env::var_os("CELOX_RTLMETER_BIN") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_celox"))); + let mut directories: Vec = std::fs::read_dir(&layout) + .unwrap_or_else(|error| panic!("{}: {error}", layout.display())) + .map(|entry| entry.expect("layout entry").path()) + .filter(|path| path.join("case.json").is_file()) + .collect(); + directories.sort(); + assert!( + !directories.is_empty(), + "{} holds no case", + layout.display() + ); + for case in directories.into_iter().map(Case::load) { + let rounds = IterManualOptions::new().rounds(case.rounds); + let mut runs = Vec::new(); + c.bench_function(&format!("rtlmeter/{}/compile", case.name), |b| { + b.iter_manual_unstable(rounds, || { + let run = run_case(&binary, &case, &limits); + reports.send(run.compile).expect("measurement receives"); + runs.push(run); + }); + }); + c.bench_function(&format!("rtlmeter/{}/cycle", case.name), |b| { + b.iter_manual_unstable(rounds, || { + // A filter that skips the compile benchmark leaves no run. + let run = runs + .pop() + .unwrap_or_else(|| run_case(&binary, &case, &limits)); + reports.send(run.per_cycle()).expect("measurement receives"); + }); + }); + } +} + +// `criterion_group!` gives its targets no way to reach the measurement, so +// this is its expansion with the sender passed along. +fn main() { + let (reports, values) = channel(); + let mut criterion = Criterion::default() + .with_measurement(Reported { + values, + wall_time: WallTime, + }) + .configure_from_args(); + if std::env::var("CODSPEED_ENV").is_ok() { + criterion.set_current_file(codspeed_criterion_compat::abs_file!()); + criterion.set_macro_group("rtlmeter::benchmark_rtlmeter"); + } + benchmark_rtlmeter(&mut criterion, &reports); + Criterion::default().configure_from_args().final_summary(); +} diff --git a/crates/celox/benches/scaling.rs b/crates/celox/benches/scaling.rs new file mode 100644 index 00000000000..e190d5e2679 --- /dev/null +++ b/crates/celox/benches/scaling.rs @@ -0,0 +1,240 @@ +//! Scheduler scaling and whole-design fallback benchmarks. +//! +//! Each design is a generated SystemVerilog design with its own clock +//! generator, built like the `celox` command builds an RTLMeter testbench +//! (native backend, O2, two-state, one thread) and run by the timed +//! simulation. +//! +//! - `scaling//{compile,sim}/n`: the same shape at two sizes, so +//! the CodSpeed history shows the slope in N. `clock_alias` gives every +//! flop its own copy of the clock (VeeR's `assign l1clk = clk`) while the +//! testbench senses the clock at the other edge; `gated_clock` gives every +//! flop a clock gate (`en_ff` captured at negedge, `gclk = clk & en_ff`). +//! - `fallback//sim`: a fixed design of 64 combinational lanes +//! with ONE extra construct, next to `fallback/baseline/sim`. A construct +//! that makes the whole design take a slower path (no settle skipping, no +//! partitioned settle, one compiled run per slot, the reference walk) +//! shows as a gap to the baseline; the pair should stay close. +//! +//! Simulation benchmarks report the time of [`WINDOW`] clock cycles. + +// CodSpeed's Criterion harness reads its own environment during macro expansion. +#![allow(clippy::disallowed_methods)] + +use std::path::Path; + +use celox::{DefaultBackend, OptLevel, Simulation, SimulatorBuilder}; +use codspeed_criterion_compat::{ + Criterion, IterManualOptions, black_box, criterion_group, criterion_main, +}; + +/// Clock cycles per simulation sample. +const WINDOW: u64 = 1_000; +/// Simulated time of one clock cycle (`always #5 clk = ~clk` at 1ns/1ns). +const PERIOD: u64 = 10; +/// The two sizes of each scaling shape. +const SIZES: [usize; 2] = [16, 1024]; + +const PRELUDE: &str = "`timescale 1ns/1ns\n"; + +/// Clock and a cycle counter sensed at negedge, as VeeR's `tb_top` senses +/// `core_clk`: a copy of `clk` sensed at posedge is then a domain of its own. +const CLOCK: &str = " + bit clk = 0; + always #5 clk = ~clk; + logic [31:0] cycle = 0; + always @(negedge clk) cycle <= cycle + 1; +"; + +/// `n` flops in a chain, each clocked by its own `assign l1clk = clk`. +fn clock_alias(n: usize) -> String { + format!( + "{PRELUDE} +module AliasFlop(input logic clk, input logic [31:0] d, output logic [31:0] q); + logic l1clk; + assign l1clk = clk; + always_ff @(posedge l1clk) q <= d; +endmodule + +module Top(output logic [31:0] obs); +{CLOCK} + logic [31:0] chain [0:{n}]; + assign chain[0] = cycle; + for (genvar i = 0; i < {n}; i++) begin : g + AliasFlop flop(.clk(clk), .d(chain[i] + 32'(i)), .q(chain[i + 1])); + end + assign obs = chain[{n}]; +endmodule +" + ) +} + +/// `n` flops in a chain, each behind a clock gate whose enable is captured +/// at negedge; flop `i` skips one cycle in 16. +fn gated_clock(n: usize) -> String { + format!( + "{PRELUDE} +module Icg(input logic clk, input logic en, output logic gclk); + logic en_ff; + always @(negedge clk) en_ff <= en; + assign gclk = clk & en_ff; +endmodule + +module GatedFlop(input logic clk, input logic en, input logic [31:0] d, output logic [31:0] q); + logic gclk; + Icg icg(.clk(clk), .en(en), .gclk(gclk)); + always_ff @(posedge gclk) q <= d; +endmodule + +module Top(output logic [31:0] obs); +{CLOCK} + logic [31:0] chain [0:{n}]; + assign chain[0] = cycle; + for (genvar i = 0; i < {n}; i++) begin : g + GatedFlop flop(.clk(clk), .en(cycle[3:0] != 4'(i)), .d(chain[i] + 32'(i)), .q(chain[i + 1])); + end + assign obs = chain[{n}]; +endmodule +" + ) +} + +/// 64 combinational lanes between flops, plus `extra` (one construct). +/// `verbose` is a top input nothing drives, so code under it never runs +/// but cannot be folded away. +fn lanes(extra: &str) -> String { + format!( + "{PRELUDE} +module Top(input logic verbose, output logic [31:0] obs); + bit clk = 0; + always #5 clk = ~clk; + logic [31:0] r [64]; + logic [31:0] c [64]; + for (genvar i = 0; i < 64; i++) begin : lane + assign c[i] = (r[i] ^ (r[(i + 1) % 64] >> 3)) + 32'h9E3779B9 * 32'(i + 1); + always_ff @(posedge clk) r[i] <= c[i] + r[(i + 63) % 64]; + end + logic [31:0] acc; + always_comb begin + acc = 0; + for (int i = 0; i < 64; i++) acc ^= c[i]; + end + logic [31:0] extra = 0; + assign obs = acc ^ extra; +{extra} +endmodule +" + ) +} + +/// The constructs of the fallback benchmarks, each added alone to [`lanes`]. +const FALLBACKS: &[(&str, &str)] = &[ + ("baseline", ""), + ( + "comb_display", + " always_comb if (verbose) $display(\"acc %h\", acc);", + ), + ( + "deferred_assert", + " always_comb assert final (!verbose || acc != 0);", + ), + ( + "dpi_always_star", + " import \"DPI-C\" function int unsigned celox_bench_mix(input int unsigned x); + always @* extra = celox_bench_mix(acc);", + ), + ( + "string_array", + " string names [4]; + initial foreach (names[i]) names[i] = $sformatf(\"lane%0d\", i); + always_ff @(posedge clk) extra <= 32'(names[r[0][1:0]].len());", + ), + ( + "final_block", + " final if (verbose) $display(\"obs %h\", obs);", + ), +]; + +/// The DPI-C function of `dpi_always_star`: a cheap pure mix. +extern "C" fn celox_bench_mix(x: u32) -> u32 { + x.rotate_left(7) ^ 0x5bd1_e995 +} + +fn builder(source: &str) -> SimulatorBuilder<'_, Simulation> { + let builder = Simulation::from_sv_sources(vec![(source, Path::new("bench.sv"))], "Top") + .opt_level(OptLevel::O2) + .four_state(false) + .threads(1); + // SAFETY: `celox_bench_mix` has the signature of its import + // (`int unsigned` in, `int unsigned` out) and lives for the program. + unsafe { builder.dpi_function("celox_bench_mix", celox_bench_mix as *const ()) } +} + +fn build(source: &str) -> Simulation { + builder(source) + .build_native() + .expect("benchmark design should build") +} + +fn run_window(sim: &mut Simulation) { + let end = sim.time() + WINDOW * PERIOD; + sim.run_until(end).expect("benchmark design should run"); +} + +/// Build `source`, run one window to leave start-up behind, print how the +/// scheduler runs it (which explains a gap), then measure windows. +fn bench_simulation(c: &mut Criterion, name: &str, source: &str) { + // Built inside the benchmark, so a filtered-out benchmark builds nothing. + c.bench_function(name, |b| { + let mut sim = build(source); + run_window(&mut sim); + let stats = sim.scheduler_stats(); + let reference = stats + .kernels + .iter() + .filter(|kernel| !matches!(kernel, celox::KernelSchedule::Compiled)) + .count(); + println!( + "{name}: compiled_slots={} compiled_runs={} reference_steps={} reference_kernels={reference}", + stats.compiled_slots, stats.compiled_runs, stats.reference_steps, + ); + b.iter_manual_unstable(IterManualOptions::new().rounds(10).warmup(1), || { + run_window(&mut sim) + }); + }); +} + +/// Compile `source` `rounds` times (at least 2, which the walltime +/// analysis needs; the large sizes take seconds each). +fn bench_compile(c: &mut Criterion, name: &str, source: &str, rounds: u64) { + c.bench_function(name, |b| { + b.iter_manual_unstable(IterManualOptions::new().rounds(rounds), || { + black_box(build(black_box(source))) + }); + }); +} + +fn benchmark_scaling(c: &mut Criterion) { + // Warm process-global frontend state outside the measured spans. + drop(build(&clock_alias(1))); + for (shape, generate) in [ + ("clock_alias", clock_alias as fn(usize) -> String), + ("gated_clock", gated_clock), + ] { + for n in SIZES { + let source = generate(n); + let rounds = if n <= 64 { 5 } else { 2 }; + bench_compile(c, &format!("scaling/{shape}/compile/n{n}"), &source, rounds); + bench_simulation(c, &format!("scaling/{shape}/sim/n{n}"), &source); + } + } +} + +fn benchmark_fallbacks(c: &mut Criterion) { + for (construct, extra) in FALLBACKS { + bench_simulation(c, &format!("fallback/{construct}/sim"), &lanes(extra)); + } +} + +criterion_group!(benches, benchmark_scaling, benchmark_fallbacks); +criterion_main!(benches); diff --git a/docs/benchmarks/index.md b/docs/benchmarks/index.md index a78adaddb8c..20afb3f1c86 100644 --- a/docs/benchmarks/index.md +++ b/docs/benchmarks/index.md @@ -75,10 +75,15 @@ split by CPU model the same way. Every chart uses a zero baseline. ## Run locally ```bash -# Compile-time benchmarks with CodSpeed +# CodSpeed benchmarks, as CI runs them. The rtlmeter benchmark runs the +# cases laid out in CELOX_RTLMETER_LAYOUT (PyYAML; --optional adds +# BlackParrot) and none without it. +python3 scripts/run-rtlmeter-bench.py prepare work/rtlmeter +python3 scripts/run-rtlmeter-bench.py codspeed-layout work/rtlmeter work/rtlmeter-layout +export CELOX_RTLMETER_LAYOUT=$PWD/work/rtlmeter-layout cargo install cargo-codspeed --locked --version 5.0.1 -cargo codspeed build --locked -p celox --bench compilation -cargo codspeed run -p celox +cargo codspeed build --locked -p celox --features cranelift --bench compilation --bench scaling --bench rtlmeter +cargo codspeed run -p celox --bench compilation --bench scaling --bench rtlmeter # Rust benchmarks cargo bench -p celox @@ -96,16 +101,41 @@ python3 scripts/compare-vcd-verilator.py The [VCD benchmark methodology and results](../internals/vcd-performance.md#verilator-comparison) cover idle, sparse, and dense recording, with tracing disabled and enabled. -The CodSpeed workflow runs daily on the default branch at 02:17 UTC (11:17 JST) -and supports manual dispatch on any branch. Pull requests, merge groups, and -pushes do not run it. Deterministic CPU simulation results are uploaded to -CodSpeed for comparison with earlier measurements using the repository's CodSpeed -regression thresholds. On `master` and `develop`, execution failures or a failed -performance analysis open or update the issue `CodSpeed is failing on `; -the next successful execution and analysis close it. Missing or incomplete -analysis is reported as a failure, rather than treated as healthy. The issue -includes the run link and, for regressions, the performance comparison and -benchmark details. The local command only checks that the benchmark suite runs. +The CodSpeed workflow runs on CodSpeed's ARM64 Macro Runner +(`codspeed-macro-arm64-graviton-ubuntu-22-04`) with the walltime instrument: +on every push to `master`, daily at 02:17 UTC (11:17 JST), on manual dispatch, +and on pull requests labelled `bench` (`bench-blackparrot` also measures +BlackParrot). Other pull requests and merge groups do not run it, because one +run takes one to two hours of the runner. Results are compared with earlier +measurements using the repository's CodSpeed regression thresholds. On +`master` and `develop`, execution failures or a failed performance analysis +open or update the issue `CodSpeed is failing on `; the next successful +execution and analysis close it. Missing or incomplete analysis is reported as +a failure, rather than treated as healthy. The issue includes the run link and, +for regressions, the performance comparison and benchmark details. The local +command only checks that the benchmark suite runs. + +| Benchmark | What it measures | Regression it guards | +|---|---|---| +| `compile/*`, `scaling/nested_write/*`, `compile/sorter_tree/*` (`compilation.rs`) | Build time of Veryl designs | Compile-time slowdowns and super-linear passes | +| `scaling/clock_alias/{compile,sim}/n{16,1024}` (`scaling.rs`) | N flops, each clocked by its own `assign l1clk = clk` while the testbench senses `clk` at negedge (VeeR-EH1 has 1,451 such copies) | Per-event scheduler cost that grows with the number of clock domains | +| `scaling/gated_clock/{compile,sim}/n{16,1024}` | N flops behind clock gates (`en_ff` captured at negedge, `gclk = clk & en_ff`) | Cost per gated or derived clock | +| `fallback//sim` vs `fallback/baseline/sim` | 64 combinational lanes plus ONE comb `$display`, `assert final`, DPI-C call in `always @*`, `string` array or `final` block | One construct moving the whole design to a slower path: no settle skipping or partitioned settle, one compiled run per slot, the reference walk. Each should stay close to the baseline | +| `rtlmeter//compile` (`rtlmeter.rs`) | `celox run` analysis and code generation of VeeR-EL2, VeeR-EH1 and XuanTie-E906 CoreMark (BlackParrot 1x1 with `bench-blackparrot` or nightly) | Compile-time regressions on real designs | +| `rtlmeter//cycle` | Execution time of a fixed `+max_cycles` window divided by its cycles (native, O2, two-state, one thread; includes the testbench start-up such as program loading) | Per-cycle regressions on real designs, including a construct that slows the whole design | + +Simulation benchmarks (`sim`) report the time of 1,000 clock cycles. The +RTLMeter cases come from `benchmarks/rtlmeter/codspeed_manifest.json` (pinned +RTLMeter revision, windows and rounds); every run must reach its window +without a testbench failure, or the benchmark fails. +A run whose resident memory passes `CELOX_RTLMETER_MEMORY_LIMIT_MIB` (20 GiB +in CI; VeeR-EH1 peaks at about 7 GB) or whose time passes +`CELOX_RTLMETER_TIMEOUT_SECS` is killed and fails its benchmark, and each run +prints its start and peak memory. The workflow runs without CodSpeed's +walltime profiler: it sampled every benchmarked process, the celox commands +included, with 8 KiB stack copies for tens of minutes, and the runner (32 GB, +16 Cortex-A72 cores) lost its connection. The build and the run print memory +and disk use every minute (`scripts/with-resource-log.sh`). Local measurements are most useful for comparing two revisions on the same machine. CI history is better for long-term trends than for small one-off deltas. diff --git a/docs/ja/benchmarks/index.md b/docs/ja/benchmarks/index.md index 7e6be84d9c4..912f2d42510 100644 --- a/docs/ja/benchmarks/index.md +++ b/docs/ja/benchmarks/index.md @@ -60,10 +60,15 @@ Heliodor のグラフは、異なるランナー間の結果を直接比較し ## ローカル実行 ```bash -# CodSpeed によるコンパイル時間ベンチマーク +# CI と同じ CodSpeed ベンチマーク。rtlmeter ベンチマークは CELOX_RTLMETER_LAYOUT に +# 配置したケースを実行し、未設定なら何も実行しない(PyYAML が必要。--optional で +# BlackParrot も追加) +python3 scripts/run-rtlmeter-bench.py prepare work/rtlmeter +python3 scripts/run-rtlmeter-bench.py codspeed-layout work/rtlmeter work/rtlmeter-layout +export CELOX_RTLMETER_LAYOUT=$PWD/work/rtlmeter-layout cargo install cargo-codspeed --locked --version 5.0.1 -cargo codspeed build --locked -p celox --bench compilation -cargo codspeed run -p celox +cargo codspeed build --locked -p celox --features cranelift --bench compilation --bench scaling --bench rtlmeter +cargo codspeed run -p celox --bench compilation --bench scaling --bench rtlmeter # Rust ベンチマーク cargo bench -p celox @@ -81,16 +86,39 @@ python3 scripts/compare-vcd-verilator.py [VCD の測定条件と結果](../../internals/vcd-performance.md#verilator-comparison)には、 idle・sparse・dense の各負荷で、記録なし/ありを比較した結果をまとめています。 -CodSpeed ワークフローは毎日 02:17 UTC(11:17 JST)にデフォルトブランチで -実行し、任意のブランチでの手動実行にも対応します。pull request、merge queue、 -push では実行しません。決定的な CPU simulation の測定結果を CodSpeed に送信し、 -リポジトリの CodSpeed 回帰しきい値に従って過去の測定と比較します。 +CodSpeed ワークフローは CodSpeed の ARM64 Macro Runner +(`codspeed-macro-arm64-graviton-ubuntu-22-04`)上で walltime 計測を行います。 +`master` への push ごと、毎日 02:17 UTC(11:17 JST)、手動実行、`bench` ラベルの +付いた pull request(`bench-blackparrot` では BlackParrot も計測)で実行します。 +1 回の実行でランナーを 1〜2 時間使うため、その他の pull request と merge queue では +実行しません。結果はリポジトリの CodSpeed 回帰しきい値に従って過去の測定と比較します。 `master` と `develop` では、実行失敗や性能解析の失敗時に `CodSpeed is failing on ` Issue を作成・更新し、次の実行と解析が 成功すると閉じます。解析結果の欠落や未完了も失敗として報告します。 Issue には実行へのリンクと、性能低下の場合は比較結果とベンチマークの詳細を 含めます。ローカル実行ではベンチマーク suite が動作することだけを確認します。 +| ベンチマーク | 計測内容 | 検出する回帰 | +|---|---|---| +| `compile/*`、`scaling/nested_write/*`、`compile/sorter_tree/*`(`compilation.rs`) | Veryl 設計のビルド時間 | コンパイル時間の悪化、超線形なパス | +| `scaling/clock_alias/{compile,sim}/n{16,1024}`(`scaling.rs`) | それぞれ独自の `assign l1clk = clk` でクロックされる N 個のフロップ。テストベンチは `clk` を negedge で検出(VeeR-EH1 にはこのコピーが 1,451 個ある) | クロックドメイン数に比例して増えるイベントあたりのスケジューラコスト | +| `scaling/gated_clock/{compile,sim}/n{16,1024}` | クロックゲート(negedge で `en_ff` を取り込み、`gclk = clk & en_ff`)の後ろの N 個のフロップ | ゲート・派生クロックあたりのコスト | +| `fallback//sim` と `fallback/baseline/sim` | 64 本の組合せレーンに、組合せ `$display`、`assert final`、`always @*` 内の DPI-C 呼び出し、`string` 配列、`final` ブロックのいずれか 1 つを追加 | 1 つの構文で設計全体が遅い経路に移る回帰(settle skip や partitioned settle の無効化、スロットごとの compiled run、reference walk)。いずれも baseline に近いままであるべき | +| `rtlmeter//compile`(`rtlmeter.rs`) | VeeR-EL2、VeeR-EH1、XuanTie-E906 の CoreMark に対する `celox run` の解析とコード生成(BlackParrot 1x1 は `bench-blackparrot` または nightly) | 実設計でのコンパイル時間の回帰 | +| `rtlmeter//cycle` | 固定 `+max_cycles` ウィンドウの実行時間をサイクル数で割った値(native、O2、2-state、1 スレッド。プログラムのロードなどテストベンチの起動を含む) | 設計全体を遅くする構文を含む、実設計でのサイクルあたりの回帰 | + +シミュレーションベンチマーク(`sim`)は 1,000 クロックサイクルの時間を報告します。 +RTLMeter ケースは `benchmarks/rtlmeter/codspeed_manifest.json`(固定した RTLMeter +リビジョン、ウィンドウ、回数)から作ります。各実行はテストベンチの失敗なしに +ウィンドウの終わりまで到達しなければならず、そうでなければベンチマークは失敗します。 +常駐メモリが `CELOX_RTLMETER_MEMORY_LIMIT_MIB`(CI では 20 GiB。VeeR-EH1 のピークは約 7 GB) +または時間が `CELOX_RTLMETER_TIMEOUT_SECS` を超えた実行は強制終了され、そのベンチマークは +失敗します。各実行は開始とピークメモリを出力します。ワークフローは CodSpeed の walltime +プロファイラを使いません。プロファイラは celox コマンドを含むすべての計測対象プロセスを +8 KiB のスタックコピー付きで数十分間サンプリングし、ランナー(32 GB、Cortex-A72 16 コア)が +接続を失いました。ビルドと実行の間、メモリとディスクの使用量を毎分出力します +(`scripts/with-resource-log.sh`)。 + ローカル計測は、同じマシン上で 2 つのリビジョンを比較する場合に最も有効です。 CI 履歴は、単発の小さな差より長期的な傾向の確認に向いています。 diff --git a/scripts/benchmark-workflows.test.mjs b/scripts/benchmark-workflows.test.mjs index d6f3c3a6c1c..b84f2108e14 100644 --- a/scripts/benchmark-workflows.test.mjs +++ b/scripts/benchmark-workflows.test.mjs @@ -29,13 +29,27 @@ function runs(name, event, ref, inputs = {}, validation = event === "workflow_di )); } +// The `if` of a CodSpeed job, evaluated for one event. +function codspeedRuns(name, { event = "schedule", action, label, labels = [], inputs = {} } = {}) { + const condition = expression(job(codspeed, name), "if") + .replaceAll("github.event.pull_request.labels.*.name", "labels"); + return Boolean(new Function("github", "inputs", "labels", "contains", "always", `return (${condition});`)( + { event_name: event, ref_name: "master", event: { action, label: label && { name: label } } }, + inputs, labels, (list, item) => list.includes(item), () => true, + )); +} + test("benchmarks run daily and manually; required lint tests the Heliodor tooling", () => { for (const workflow of [heliodor, bench, codspeed]) { const triggers = workflow.match(/^on:\n([\s\S]*?)\n\S/m)[1]; - assert.doesNotMatch(triggers, /^\s+(push|pull_request|merge_group):/m); + assert.doesNotMatch(triggers, /^\s+merge_group:/m); assert.match(triggers, /^\s+schedule:/m); assert.match(triggers, /^\s+workflow_dispatch:/m); } + for (const workflow of [heliodor, bench]) { + const triggers = workflow.match(/^on:\n([\s\S]*?)\n\S/m)[1]; + assert.doesNotMatch(triggers, /^\s+(push|pull_request):/m); + } const scriptTests = read("ci").match(/name: Test repository scripts\n[\s\S]*?\n\n/)[0]; for (const fixture of ["convert-heliodor-bench", "run-heliodor-bench-results", "run-heliodor-bench-gate"]) { assert.match(scriptTests, new RegExp(`bash scripts/tests/${fixture}\\.sh`)); @@ -50,7 +64,7 @@ test("CodSpeed reports the current upload even after failure or cancellation", ( const benchmark = job(codspeed, "codspeed"); const report = job(codspeed, "report"); assert.match(benchmark, /run-id: \$\{\{ steps\.benchmarks\.outputs\.run-id \}\}/); - assert.match(benchmark, /id: benchmarks\n\s+timeout-minutes: 15\n\s+uses: CodSpeedHQ\/action@v5/); + assert.match(benchmark, /id: benchmarks\n\s+timeout-minutes: 120\n\s+uses: CodSpeedHQ\/action@v5/); assert.match(report, /needs: codspeed/); assert.match(report, /checks: read/); assert.match(report, /issues: write/); @@ -58,7 +72,17 @@ test("CodSpeed reports the current upload even after failure or cancellation", ( assert.match(report, /CODSPEED_RUN_ID: \$\{\{ needs\.codspeed\.outputs\.run-id \}\}/); assert.match(report, /run: node scripts\/report-codspeed\.mjs/); assert.doesNotMatch(codspeed, /continue-on-error:/); - assert.match(codspeed, /cancel-in-progress: false/); + // Master keeps every commit's run: one concurrency group per commit, since + // a group holds only one pending run. Only pull request runs replace each other. + assert.match(codspeed, /cancel-in-progress: \$\{\{ github\.event_name == 'pull_request' \}\}/); + const group = new Function("github", `return (${ + codspeed.match(/^ group: \$\{\{ github\.workflow \}\}-\$\{\{ (.+) \}\}$/m)[1] + });`); + const push = sha => group({ event_name: "push", ref: "refs/heads/master", sha }); + assert.notEqual(push("a1"), push("b2")); + assert.equal(group({ event_name: "schedule", ref: "refs/heads/master", sha: "a1" }), "a1"); + const pr = sha => group({ event_name: "pull_request", ref: "refs/pull/1/merge", sha }); + assert.equal(pr("a1"), pr("b2")); const condition = new Function("github", "always", "inputs", `return (${expression(report, "if")});`); for (const branch of ["master", "develop", "feature"]) { assert.equal(condition({ ref_name: branch }, () => true, { runner_probe: false }), branch !== "feature"); @@ -169,15 +193,62 @@ test("profiling reuse rejects pre-CLI artifacts before capture", () => { test("compilation scaling uses walltime consistently and has a bounded execution", () => { const benchmark = job(codspeed, "codspeed"); + const benches = "-p celox --bench compilation --bench scaling --bench rtlmeter"; assert.match(benchmark, /runs-on: codspeed-macro-arm64-graviton-ubuntu-22-04/); - assert.match(benchmark, /timeout-minutes: 60/); - assert.match(benchmark, /cargo codspeed build --locked --measurement-mode walltime -p celox --bench compilation/); - assert.match(benchmark, /id: benchmarks\n timeout-minutes: 15\n uses: CodSpeedHQ\/action@v5/); + assert.match(benchmark, /timeout-minutes: 210/); + assert.ok(benchmark.includes(`cargo codspeed build --locked --measurement-mode walltime -p celox --features cranelift ${benches.slice(9)}\n`)); + // Fat LTO of four binaries at once starved the 32 GB runner. + assert.match(codspeed, /^ CARGO_PROFILE_BENCH_LTO: thin$/m); + // The layout exists before the run, which reads it from the job environment. + assert.match(benchmark, /^ CELOX_RTLMETER_LAYOUT: /m); + assert.ok(benchmark.indexOf("codspeed-layout") < benchmark.indexOf("cargo codspeed run")); + assert.match(benchmark, /id: benchmarks\n timeout-minutes: 120\n uses: CodSpeedHQ\/action@v5/); assert.match(benchmark, /mode: walltime/); - assert.match(benchmark, /run: cargo codspeed run --measurement-mode walltime -p celox --bench compilation/); + assert.ok(benchmark.includes(`run: bash scripts/with-resource-log.sh cargo codspeed run --measurement-mode walltime ${benches}\n`)); + // One RTLMeter case cannot take the runner down, and the profiler does not + // sample the celox commands for tens of minutes. + assert.match(benchmark, /^ CELOX_RTLMETER_MEMORY_LIMIT_MIB: "20480"$/m); + assert.match(benchmark, /^ CODSPEED_PROFILER_ENABLED: "false"$/m); assert.doesNotMatch(benchmark, /simulation|continue-on-error/); }); +test("RTLMeter cases come from the pinned manifest; BlackParrot only when asked", () => { + const benchmark = job(codspeed, "codspeed"); + assert.match(benchmark, /run-rtlmeter-bench\.py prepare "\$RUNNER_TEMP\/rtlmeter"/); + assert.match(benchmark, /codspeed-layout "\$RUNNER_TEMP\/rtlmeter" "\$CELOX_RTLMETER_LAYOUT" "\$\{optional\[@\]\}"/); + assert.match(benchmark, /if \[ "\$BLACKPARROT" = true \]; then optional=\(--optional\); fi/); + const blackparrot = new Function("github", "inputs", "contains", `return (${ + benchmark.match(/BLACKPARROT: \$\{\{ (.+) \}\}/)[1].replaceAll("github.event.pull_request.labels.*.name", "github.labels") + });`); + const contains = (list, item) => (list ?? []).includes(item); + assert.equal(blackparrot({ event_name: "schedule" }, {}, contains), true); + assert.equal(blackparrot({ event_name: "push" }, {}, contains), false); + assert.equal(blackparrot({ event_name: "workflow_dispatch" }, { blackparrot: true }, contains), true); + assert.equal(blackparrot({ event_name: "workflow_dispatch" }, { blackparrot: false }, contains), false); + assert.equal(blackparrot({ event_name: "pull_request", labels: ["bench"] }, {}, contains), false); + assert.equal(blackparrot({ event_name: "pull_request", labels: ["bench-blackparrot"] }, {}, contains), true); +}); + +test("CodSpeed measures master pushes and labelled pull requests only", () => { + const triggers = codspeed.match(/^on:\n([\s\S]*?)\n\S/m)[1]; + assert.match(triggers, /^ push:\n branches: \[master\]/m); + assert.match(triggers, /^ pull_request:\n types: \[opened, reopened, synchronize, labeled\]/m); + assert.equal(codspeedRuns("codspeed", { event: "push" }), true); + assert.equal(codspeedRuns("codspeed", { event: "schedule" }), true); + assert.equal(codspeedRuns("codspeed", { event: "workflow_dispatch", inputs: { runner_probe: true } }), false); + for (const action of ["opened", "reopened", "synchronize"]) { + assert.equal(codspeedRuns("codspeed", { event: "pull_request", action }), false, action); + assert.equal(codspeedRuns("codspeed", { event: "pull_request", action, labels: ["bench"] }), true, action); + assert.equal(codspeedRuns("codspeed", { event: "pull_request", action, labels: ["bench-blackparrot"] }), true, action); + } + for (const label of ["bench", "bench-blackparrot"]) { + assert.equal(codspeedRuns("codspeed", { event: "pull_request", action: "labeled", label, labels: [label] }), true, label); + } + // Another label on a benchmarked pull request does not measure it again. + assert.equal(codspeedRuns("codspeed", { event: "pull_request", action: "labeled", label: "merge-ready", labels: ["bench", "merge-ready"] }), false); + assert.equal(codspeedRuns("codspeed", { event: "pull_request", action: "labeled", label: "merge-ready", labels: ["merge-ready"] }), false); +}); + test("runner probe cannot build or benchmark and does not report a skipped benchmark as failure", () => { const probe = job(codspeed, "runner-probe"); @@ -186,13 +257,11 @@ test("runner probe cannot build or benchmark and does not report a skipped bench assert.doesNotMatch(probe, /checkout|cargo|CodSpeedHQ\/action/); assert.match(probe, /timeout-minutes: 2/); const probeCondition = new Function("github", "inputs", `return (${expression(probe, "if")});`); - const benchCondition = new Function("inputs", `return (${expression(job(codspeed, "codspeed"), "if")});`); - const reportCondition = new Function("github", "inputs", "always", `return (${expression(job(codspeed, "report"), "if")});`); for (const runner_probe of [true, false]) { const inputs = { runner_probe }; assert.equal(Boolean(probeCondition({ event_name: "workflow_dispatch" }, inputs)), runner_probe); - assert.equal(benchCondition(inputs), !runner_probe); - assert.equal(reportCondition({ ref_name: "master" }, inputs, () => true), !runner_probe); + assert.equal(codspeedRuns("codspeed", { event: "workflow_dispatch", inputs }), !runner_probe); + assert.equal(codspeedRuns("report", { event: "workflow_dispatch", inputs }), !runner_probe); } - assert.equal(benchCondition({}), true); + assert.equal(codspeedRuns("codspeed", { event: "workflow_dispatch" }), true); }); diff --git a/scripts/run-rtlmeter-bench.py b/scripts/run-rtlmeter-bench.py index 8818e2d1856..f9b7b8e8b95 100644 --- a/scripts/run-rtlmeter-bench.py +++ b/scripts/run-rtlmeter-bench.py @@ -16,6 +16,7 @@ ROOT = Path(__file__).resolve().parent.parent DEFAULT_MANIFEST_PATH = ROOT / 'benchmarks/rtlmeter/manifest.json' +CODSPEED_MANIFEST_PATH = ROOT / 'benchmarks/rtlmeter/codspeed_manifest.json' MANIFEST = json.loads(DEFAULT_MANIFEST_PATH.read_text()) ENGINES = ('celox', 'verilator', 'xezim') STATES = ('two-state', 'four-state') @@ -401,12 +402,104 @@ def check_case(case_name, source, celox, states=('two-state',), timeout=300, out return results +def codspeed_specification(name, source, manifest): + """A case of the CodSpeed manifest, merged as RTLMeter merges a + descriptor: the configuration's compile inputs and every execute level's + files and arguments (common, then test).""" + import yaml + case = manifest['cases'][name] + design = source / 'designs' / case['design'] + descriptor = yaml.safe_load((design / 'descriptor.yaml').read_text()) + configurations = descriptor.get('configurations') or {} + configuration = configurations.get(case.get('configuration', 'default')) or {} + compile_root, compile_config = descriptor['compile'], configuration.get('compile') or {} + execute_root, execute_config = descriptor.get('execute') or {}, configuration.get('execute') or {} + test = case['test'] + executes = [execute_root.get('common') or {}, (execute_root.get('tests') or {}).get(test) or {}, + execute_config.get('common') or {}, (execute_config.get('tests') or {}).get(test) or {}] + if test not in (execute_root.get('tests') or {}) and test not in (execute_config.get('tests') or {}): + raise ValueError(f'{name}: {case["design"]} has no test {test}') + if compile_root.get('prepHook') or any(level.get('prepHook') for level in executes): + raise ValueError(f'{name}: prepare hooks are not supported') + + def listed(key, *levels): + return [entry for level in levels for entry in (level.get(key) or [])] + + defines = {**(compile_root.get('verilogDefines') or {}), **(compile_config.get('verilogDefines') or {}), + '__RTLMETER_MAIN_CLOCK': compile_config.get('mainClock') or compile_root['mainClock']} + verilator = [str(arg) for arg in listed('verilatorArgs', compile_root, compile_config)] + # Verilator's parameter overrides and time scale belong to the design's + # build; its other options (lint waivers, --autoflush) do not. + options = [arg for arg in verilator if arg.startswith('-G')] + if '--timescale' in verilator: + options += ['--timescale', verilator[verilator.index('--timescale') + 1]] + return { + 'top': compile_config.get('topModule') or compile_root['topModule'], + 'sources': [design / p for p in listed('verilogSourceFiles', compile_root, compile_config)] + + [source / 'rtl/__rtlmeter_utils.sv'], + 'includeFiles': [design / p for p in listed('verilogIncludeFiles', compile_root, compile_config)], + 'files': [design / p for p in listed('files', *executes)], + 'defines': defines, + 'options': options, + 'args': [str(arg) for arg in listed('args', *executes)], + 'diagnostics': case.get('diagnostics', []), + } + + +def codspeed_layout(source, output, manifest, names, window=None): + """Lay out each case for `crates/celox/benches/rtlmeter.rs`: the source + list, RTLMeter's flat include directory, the test's input files and the + `celox` arguments of one fixed simulation window.""" + verify_source(source, manifest) + output.mkdir(parents=True, exist_ok=False) + for name in names: + case = manifest['cases'][name] + spec = codspeed_specification(name, source, manifest) + # Criterion's walltime analysis rejects a benchmark with one sample. + if case['rounds'] < 2: + raise ValueError(f'{name}: a case needs at least 2 rounds') + directory = output / name + includes = directory / 'include' + run_directory = directory / 'run' + includes.mkdir(parents=True) + run_directory.mkdir() + for path in spec['includeFiles']: + link = includes / path.name + if link.exists(): + raise ValueError(f'{name}: include files share the name {path.name}') + link.symlink_to(path) + for path in spec['files']: + shutil.copyfile(path, run_directory / path.name) + files = directory / 'sources.f' + files.write_text(''.join(json.dumps(str(p)) + '\n' for p in spec['sources'])) + cycles = window or case['window'] + includes_in_order = [includes, source / 'rtl', source / 'designs' / case['design'] / 'src'] + command = commands('celox', 'two-state', {**spec, 'includes': includes_in_order}, files, directory, + {'celox': 'celox'}, [*spec['options'], *spec['args'], f'+max_cycles={cycles}'], + 'rtlmeter-steady-state-v1')[0][1:] + (directory / 'case.json').write_text(json.dumps({ + 'name': name, 'design': case['design'], 'rtlmeterRevision': manifest['revision'], + 'window': cycles, 'rounds': case['rounds'], 'args': [str(arg) for arg in command], + }, indent=2) + '\n') + print(f'LAYOUT {name}: {directory}', flush=True) + + def main(): parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest='command', required=True) prepare_parser = sub.add_parser('prepare') prepare_parser.add_argument('destination', type=Path) prepare_parser.add_argument('--manifest', type=Path, default=DEFAULT_MANIFEST_PATH) + layout = sub.add_parser('codspeed-layout', help='lay out cases for the CodSpeed RTLMeter benchmark') + layout.add_argument('source', type=Path) + layout.add_argument('output', type=Path) + layout.add_argument('--manifest', type=Path, default=CODSPEED_MANIFEST_PATH) + layout.add_argument('--case', action='append', dest='cases', + help='case to lay out (repeatable; default: every case not marked optional)') + layout.add_argument('--optional', action='store_true', + help='also lay out the cases marked optional when no --case is given') + layout.add_argument('--window', type=int, default=None, + help='simulated cycles of every case instead of the manifest windows (local checks)') check = sub.add_parser('check') check.add_argument('case', choices=[*MANIFEST['cases'], 'all']) check.add_argument('source', type=Path) @@ -431,6 +524,15 @@ def main(): manifest = json.loads(args.manifest.read_text()) if hasattr(args, 'manifest') else MANIFEST if args.command == 'prepare': prepare(args.destination, manifest) + elif args.command == 'codspeed-layout': + names = args.cases or [name for name, case in manifest['cases'].items() + if args.optional or not case.get('optional')] + unknown = [name for name in names if name not in manifest['cases']] + if unknown: + parser.error(f'unknown cases {unknown}, expected some of {list(manifest["cases"])}') + if args.window is not None and args.window <= 0: + parser.error('window must be positive') + codspeed_layout(args.source.resolve(), args.output.resolve(), manifest, names, args.window) elif args.command == 'check': states = [s.strip() for s in args.states.split(',') if s.strip()] for s in states: diff --git a/scripts/tests/test_rtlmeter_bench.py b/scripts/tests/test_rtlmeter_bench.py index 3c92bca7798..67e13653005 100644 --- a/scripts/tests/test_rtlmeter_bench.py +++ b/scripts/tests/test_rtlmeter_bench.py @@ -185,6 +185,90 @@ def test_steady_manifest_specifies_coremark_cases(self): self.assertEqual(steady_manifest['cases']['e902']['payload'], 'CoreMark 1.0') self.assertEqual(steady_manifest['cases']['e906']['payload'], 'CoreMark 1.0') + def test_codspeed_manifest_pins_the_revision_and_windows(self): + import json + manifest = json.loads(bench.CODSPEED_MANIFEST_PATH.read_text()) + self.assertEqual(manifest['revision'], bench.MANIFEST['revision']) + self.assertEqual(manifest['repository'], bench.MANIFEST['repository']) + self.assertEqual(set(manifest['cases']), + {'veer-el2-cmark', 'veer-eh1-cmark', 'e906-cmark', 'blackparrot-1x1-cmark'}) + for name, case in manifest['cases'].items(): + with self.subTest(case=name): + self.assertEqual(case['test'], 'cmark') + self.assertGreater(case['window'], 0) + self.assertGreaterEqual(case['rounds'], 2) + self.assertEqual([n for n, c in manifest['cases'].items() if c.get('optional')], ['blackparrot-1x1-cmark']) + + def test_codspeed_layout_merges_configuration_and_execute_levels(self): + import json + from unittest.mock import patch + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + design = root / 'designs/Core' + for path in ['src/tb.sv', 'src/default/defines.vh', 'src/other/defines.vh', + 'src/inc/pkg.vh', 'tests/cmark/prog.mem']: + (design / path).parent.mkdir(parents=True, exist_ok=True) + (design / path).write_text('test fixture') + (root / 'rtl').mkdir() + (root / 'rtl/__rtlmeter_utils.sv').write_text('test fixture') + (design / 'descriptor.yaml').write_text(""" +compile: + verilogSourceFiles: [src/tb.sv] + verilogIncludeFiles: [src/inc/pkg.vh] + verilogDefines: {A: 1} + topModule: tb + mainClock: tb.clk + verilatorArgs: [--autoflush, -Gdepth_p=4, -Wno-WIDTH] +execute: + common: + args: [+init_mem=prog.mem] + tests: + hello: {} +configurations: + default: + compile: + verilogIncludeFiles: [src/default/defines.vh] + one: + compile: + verilogIncludeFiles: [src/other/defines.vh] + verilogDefines: {CFG: one} + execute: + tests: + cmark: + args: [+iterations=8] + files: [tests/cmark/prog.mem] +""") + manifest = {'revision': 'pinned', 'cases': { + 'core': {'design': 'Core', 'configuration': 'one', 'test': 'cmark', 'window': 500, 'rounds': 2, + 'diagnostics': ['inferred_latch=warn']}, + 'missing': {'design': 'Core', 'test': 'dhry', 'window': 1, 'rounds': 1}, + }} + output = root / 'layout' + with patch.object(bench, 'verify_source'): + bench.codspeed_layout(root, output, manifest, ['core']) + with self.assertRaisesRegex(ValueError, 'no test dhry'): + bench.codspeed_layout(root, root / 'other', manifest, ['missing']) + manifest['cases']['once'] = {**manifest['cases']['core'], 'rounds': 1} + with self.assertRaisesRegex(ValueError, 'at least 2 rounds'): + bench.codspeed_layout(root, root / 'third', manifest, ['once']) + case = json.loads((output / 'core/case.json').read_text()) + self.assertEqual((case['window'], case['rounds'], case['rtlmeterRevision']), (500, 2, 'pinned')) + args = case['args'] + self.assertEqual(args[:2], ['run', '-f']) + for flag in ['--backend', 'native', '--two-state', '--threads', '1', 'O2', '--report', '-Gdepth_p=4', + '-DA=1', '-DCFG=one', '-D__RTLMETER_MAIN_CLOCK=tb.clk', 'inferred_latch=warn']: + self.assertIn(flag, args) + self.assertNotIn('-Wno-WIDTH', args) + self.assertEqual(args[-3:], ['+init_mem=prog.mem', '+iterations=8', '+max_cycles=500']) + includes = [arg for arg in args if arg.startswith('-I')] + self.assertEqual(includes[0], f'-I{output / "core/include"}') + # The configuration's header, not the default one, under its plain name. + self.assertEqual((output / 'core/include/defines.vh').resolve(), design / 'src/other/defines.vh') + self.assertTrue((output / 'core/include/pkg.vh').is_symlink()) + self.assertEqual((output / 'core/run/prog.mem').read_text(), 'test fixture') + sources = [json.loads(line) for line in (output / 'core/sources.f').read_text().splitlines()] + self.assertEqual(sources, [str(design / 'src/tb.sv'), str(root / 'rtl/__rtlmeter_utils.sv')]) + def test_steady_configuration_includes_verbose_and_max_time_for_xezim(self): self.assertIn('--verbose', bench.STEADY_CONFIGURATION['xezim']) self.assertIn('--max-time 60s', bench.STEADY_CONFIGURATION['xezim']) diff --git a/scripts/with-resource-log.sh b/scripts/with-resource-log.sh new file mode 100644 index 00000000000..da033fe788b --- /dev/null +++ b/scripts/with-resource-log.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Run a command and print the machine's memory, disk and largest process +# every minute to stderr, so a CI job whose runner is starved leaves +# evidence of what grew. Usage: scripts/with-resource-log.sh +set -euo pipefail + +log_resources() { + while sleep 60; do + local memory disk top + memory=$(free -m | awk 'NR == 2 { print $3 "/" $2 " MiB used, " $7 " MiB available" }') + disk=$(df -h . | awk 'NR == 2 { print $4 " disk free" }') + top=$(ps -eo rss=,comm= --sort=-rss | awk 'NR == 1 { printf "%s %d MiB", $2, $1 / 1024 }') + echo "resources: $memory; $disk; largest: $top" >&2 + done +} + +log_resources & +logger=$! +trap 'kill "$logger" 2>/dev/null || true' EXIT +"$@"