Skip to main content

bake_benchmark/
lib.rs

1// Released under the MIT License.
2// Copyright, 2026, by Samuel Williams.
3
4//! Bake tasks for the shared Base benchmark tooling.
5//!
6//! Each task translates its arguments into a [`base_benchmark::Workspace`] operation. Preparation, collection, locking, cleanup, validation, summaries, and every default are implemented once, in `base-benchmark`; the `base-benchmark` command calls the same operations.
7use bake::{Context, Error, Result};
8use base_benchmark::{
9    ArtifactManifest, Campaign, Cancellation, Mode, PrepareRequest, Prepared, RunRequest, Suite,
10    Tree, Workspace, parse_cpus, remote::Remote, summarize_directory,
11};
12use std::path::{Path, PathBuf};
13use std::time::Duration;
14
15fn workspace(context: &Context, manifest_path: Option<PathBuf>) -> Workspace {
16    Workspace::new(resolve(
17        context,
18        manifest_path.unwrap_or_else(|| PathBuf::from("Cargo.toml")),
19    ))
20}
21
22/// Paths are relative to the project root; absolute paths are used as they are.
23fn resolve(context: &Context, path: impl AsRef<Path>) -> PathBuf {
24    context.root().join(path)
25}
26
27fn failed(error: std::io::Error) -> Error {
28    Error::new(error.to_string())
29}
30
31/// The host a task runs on over SSH, when one is given; otherwise the task runs here.
32fn remote(
33    host: Option<String>,
34    directory: Option<String>,
35    program: Option<String>,
36) -> Option<Remote> {
37    host.map(|host| {
38        let mut remote = Remote::new(host);
39        remote.directory = directory.unwrap_or(remote.directory);
40        remote.program = program;
41        remote
42    })
43}
44
45/// Command-line arguments for a remote command: each present option as `--name value`.
46fn options(
47    positional: &[&str],
48    named: &[(&str, Option<String>)],
49    repeated: &[(&str, &[String])],
50) -> Vec<String> {
51    let mut arguments: Vec<String> = positional.iter().map(|value| (*value).to_owned()).collect();
52    for (name, value) in named {
53        if let Some(value) = value {
54            arguments.extend([format!("--{name}"), value.clone()]);
55        }
56    }
57    for (name, values) in repeated {
58        for value in *values {
59            arguments.extend([format!("--{name}"), value.clone()]);
60        }
61    }
62    arguments
63}
64
65fn display(path: Option<PathBuf>) -> Option<String> {
66    path.map(|path| path.display().to_string())
67}
68
69/// List workspace packages that declare `[package.metadata.base-benchmark]` scenarios, including unpublished packages, with resolved scenario defaults. Nothing is built or run.
70#[bake::task]
71pub fn list(
72    context: &mut Context,
73    #[bake(help = "Workspace manifest; defaults to Cargo.toml in the project root.")] manifest_path: Option<PathBuf>,
74) -> Result<Vec<Suite>> {
75    workspace(context, manifest_path).suites().map_err(failed)
76}
77
78/// Build labelled source trees with identical settings and freeze their executables. The first tree is the baseline; without trees, the current workspace is built.
79#[bake::task]
80#[allow(clippy::too_many_arguments, reason = "each argument is a task option")]
81pub fn prepare(
82    context: &mut Context,
83    #[bake(help = "Benchmark package; required when several declare scenarios.")] package: Option<
84        String,
85    >,
86    #[bake(help = "LABEL=PATH source tree; repeat for each tree, baseline first.")] tree: Vec<Tree>,
87    #[bake(
88        help = "Layout replicas of the baseline to rebuild at other paths; defaults to 1 for two or more trees, otherwise 0."
89    )]
90    replicas: Option<usize>,
91    #[bake(help = "New output directory; defaults to target/base-benchmark/prepared-TIME.")] output: Option<PathBuf>,
92    #[bake(help = "Prepare only the feature sets this scenario needs; repeat for each.")] scenario: Vec<String>,
93    #[bake(
94        named,
95        default = false,
96        help = "Build every tree with this workspace's workload package."
97    )]
98    overlay: bool,
99    #[bake(help = "Workspace manifest; defaults to Cargo.toml in the project root.")] manifest_path: Option<PathBuf>,
100    #[bake(help = "Prepare on this SSH host, mirroring local paths there.")] host: Option<String>,
101    #[bake(
102        help = "The host's directory for mirrors and the command; defaults to .cache/base-benchmark."
103    )]
104    remote_directory: Option<String>,
105    #[bake(
106        help = "The host's base-benchmark command; without it, the crates.io release of this version is installed, so unreleased builds need one."
107    )]
108    remote_program: Option<String>,
109) -> Result<Prepared> {
110    let tree: Vec<Tree> = tree
111        .into_iter()
112        .map(|tree| Tree {
113            path: resolve(context, tree.path),
114            ..tree
115        })
116        .collect();
117    let output = output.map(|output| resolve(context, output));
118    let manifest_path = resolve(
119        context,
120        manifest_path.unwrap_or_else(|| PathBuf::from("Cargo.toml")),
121    );
122    if let Some(remote) = remote(host, remote_directory, remote_program) {
123        // A termination signal cancels the host's command, whose output is still copied back.
124        let cancellation = Cancellation::new();
125        let _signals = cancellation.on_termination_signals();
126        let trees: Vec<String> = tree
127            .iter()
128            .map(|tree| format!("{}={}", tree.label, tree.path.display()))
129            .collect();
130        return remote
131            .execute(
132                "prepare",
133                options(
134                    &[],
135                    &[
136                        ("manifest-path", display(Some(manifest_path))),
137                        ("package", package),
138                        ("replicas", replicas.map(|replicas| replicas.to_string())),
139                        ("output", display(output)),
140                        ("overlay", Some(overlay.to_string())),
141                    ],
142                    &[("tree", &trees), ("scenario", &scenario)],
143                ),
144                &cancellation,
145            )
146            .and_then(|outcome| {
147                // The downloaded manifest names the host's executables, for runs on the same host.
148                let manifest_path = outcome.output.join("artifacts.json");
149                ArtifactManifest::read(&manifest_path).map(|manifest| Prepared {
150                    manifest_path,
151                    manifest,
152                })
153            })
154            .map_err(failed);
155    }
156    let cancellation = Cancellation::new();
157    let _signals = cancellation.on_termination_signals();
158    Workspace::new(manifest_path)
159        .prepare(
160            PrepareRequest {
161                package,
162                trees: tree,
163                replicas,
164                output,
165                scenarios: scenario,
166                overlay,
167            },
168            &cancellation,
169        )
170        .map_err(failed)
171}
172
173/// Build the current workspace and run every scenario once with its smoke arguments. Smoke results are not performance evidence.
174#[bake::task]
175#[allow(clippy::too_many_arguments, reason = "each argument is a task option")]
176pub fn smoke(
177    context: &mut Context,
178    #[bake(help = "Benchmark package; required when several declare scenarios.")] package: Option<
179        String,
180    >,
181    #[bake(help = "New output directory; defaults to target/base-benchmark/smoke-TIME.")]
182    output: Option<PathBuf>,
183    #[bake(
184        help = "Host-wide lock file; defaults to /tmp/base-benchmark-host.lock. With --host, a path on the host, relative to the remote user's home."
185    )]
186    lock: Option<PathBuf>,
187    #[bake(help = "Workspace manifest; defaults to Cargo.toml in the project root.")] manifest_path: Option<PathBuf>,
188    #[bake(help = "Smoke on this SSH host, mirroring local paths there.")] host: Option<String>,
189    #[bake(
190        help = "The host's directory for mirrors and the command; defaults to .cache/base-benchmark."
191    )]
192    remote_directory: Option<String>,
193    #[bake(
194        help = "The host's base-benchmark command; without it, the crates.io release of this version is installed, so unreleased builds need one."
195    )]
196    remote_program: Option<String>,
197) -> Result<Vec<Campaign>> {
198    let output = output.map(|output| resolve(context, output));
199    if let Some(remote) = remote(host, remote_directory, remote_program) {
200        // A termination signal cancels the host's command, whose output is still copied back.
201        let cancellation = Cancellation::new();
202        let _signals = cancellation.on_termination_signals();
203        let manifest_path = resolve(
204            context,
205            manifest_path.unwrap_or_else(|| PathBuf::from("Cargo.toml")),
206        );
207        let scenarios: Vec<String> = Workspace::new(manifest_path.clone())
208            .suite(package.as_deref())
209            .map_err(failed)?
210            .scenarios
211            .into_iter()
212            .map(|scenario| scenario.name)
213            .collect();
214        return remote
215            .execute(
216                "smoke",
217                options(
218                    &[],
219                    &[
220                        ("manifest-path", display(Some(manifest_path))),
221                        ("package", package),
222                        ("output", display(output)),
223                        // The lock is the host's, named as it is.
224                        ("lock", display(lock)),
225                    ],
226                    &[],
227                ),
228                &cancellation,
229            )
230            .and_then(|outcome| {
231                // Each scenario's campaign is named after it, in declaration order, as a local smoke run returns them.
232                scenarios
233                    .iter()
234                    .map(|scenario| summarize_directory(&outcome.output.join(scenario)))
235                    .collect::<std::io::Result<Vec<_>>>()
236            })
237            .map(report_all)
238            .map_err(failed);
239    }
240    let cancellation = Cancellation::new();
241    let _signals = cancellation.on_termination_signals();
242    let lock = lock.map(|lock| resolve(context, lock));
243    let campaigns = workspace(context, manifest_path)
244        .smoke(
245            package.as_deref(),
246            output,
247            lock,
248            &cancellation,
249            &mut std::io::stderr(),
250        )
251        .map_err(failed)?;
252    Ok(report_all(campaigns))
253}
254
255/// Write each campaign's directory and report to stderr, as every collecting task does.
256fn report_all(campaigns: Vec<Campaign>) -> Vec<Campaign> {
257    for campaign in &campaigns {
258        eprintln!("{}\n{}", campaign.output.display(), campaign.report);
259    }
260    campaigns
261}
262
263/// Collect a scenario from prepared artifacts in seeded random rounds under the host lock. The report is written to stderr; the result describes the campaign directory, evidence class, and warnings.
264#[bake::task]
265#[allow(clippy::too_many_arguments, reason = "each argument is a task option")]
266pub fn run(
267    context: &mut Context,
268    #[bake(help = "Scenario name.")] scenario: String,
269    #[bake(named, help = "artifacts.json from benchmark:prepare.")] artifacts: PathBuf,
270    #[bake(help = "smoke, screening, or recorded; defaults to screening.")] mode: Option<Mode>,
271    #[bake(help = "Benchmark package; required when several declare scenarios.")] package: Option<
272        String,
273    >,
274    #[bake(help = "Rounds; defaults to 1, 5, or 10 by mode.")] rounds: Option<u32>,
275    #[bake(
276        help = "Seed for the round order and stack padding; defaults to the clock and is recorded."
277    )]
278    seed: Option<u64>,
279    #[bake(
280        help = "CPU list for every workload process, such as 2 or 2,4-5. Required for recorded runs."
281    )]
282    cpus: Option<String>,
283    #[bake(help = "Whole-process perf stat event; repeat for several.")] perf_event: Vec<String>,
284    #[bake(help = "Seconds before a workload process is killed; defaults to 300.")] timeout_seconds: Option<u64>,
285    #[bake(
286        help = "Host-wide lock file; defaults to /tmp/base-benchmark-host.lock. With --host, a path on the host, relative to the remote user's home."
287    )]
288    lock: Option<PathBuf>,
289    #[bake(help = "New output directory; defaults to target/base-benchmark/SCENARIO-MODE-TIME.")]
290    output: Option<PathBuf>,
291    #[bake(help = "The predeclared interpretation rule. Required for recorded runs.")]
292    decision_rule: Option<String>,
293    #[bake(
294        named,
295        default = false,
296        help = "Declare that the host is otherwise idle. Required for recorded runs."
297    )]
298    idle_host: bool,
299    #[bake(help = "Vary initial stack alignment per sample; defaults to true.")]
300    stack_padding: Option<bool>,
301    #[bake(help = "Workspace manifest; defaults to Cargo.toml in the project root.")] manifest_path: Option<PathBuf>,
302    #[bake(help = "Collect on this SSH host, from artifacts prepared there.")] host: Option<String>,
303    #[bake(
304        help = "The host's directory for mirrors and the command; defaults to .cache/base-benchmark."
305    )]
306    remote_directory: Option<String>,
307    #[bake(
308        help = "The host's base-benchmark command; without it, the crates.io release of this version is installed, so unreleased builds need one."
309    )]
310    remote_program: Option<String>,
311) -> Result<Campaign> {
312    // Checked here, so that a remote run fails before contacting the host, as a local one does.
313    let placement = cpus
314        .as_deref()
315        .map(parse_cpus)
316        .transpose()
317        .map_err(failed)?
318        .unwrap_or_default();
319    if let Some(remote) = remote(host, remote_directory, remote_program) {
320        // A termination signal cancels the host's command, whose output is still copied back.
321        let cancellation = Cancellation::new();
322        let _signals = cancellation.on_termination_signals();
323        let manifest_path = resolve(
324            context,
325            manifest_path.unwrap_or_else(|| PathBuf::from("Cargo.toml")),
326        );
327        return remote
328            .execute(
329                "run",
330                options(
331                    &[&scenario],
332                    &[
333                        ("manifest-path", display(Some(manifest_path))),
334                        ("artifacts", display(Some(resolve(context, artifacts)))),
335                        ("mode", mode.map(|mode| mode.to_string())),
336                        ("package", package),
337                        ("rounds", rounds.map(|rounds| rounds.to_string())),
338                        ("seed", seed.map(|seed| seed.to_string())),
339                        ("cpus", cpus),
340                        (
341                            "timeout-seconds",
342                            timeout_seconds.map(|seconds| seconds.to_string()),
343                        ),
344                        // The lock is the host's, named as it is.
345                        ("lock", display(lock)),
346                        (
347                            "output",
348                            display(output.map(|output| resolve(context, output))),
349                        ),
350                        ("decision-rule", decision_rule),
351                        ("idle-host", Some(idle_host.to_string())),
352                        (
353                            "stack-padding",
354                            stack_padding.map(|padding| padding.to_string()),
355                        ),
356                    ],
357                    &[("perf-event", &perf_event)],
358                ),
359                &cancellation,
360            )
361            .and_then(|outcome| summarize_directory(&outcome.output))
362            .map(|campaign| report_all(vec![campaign]).remove(0))
363            .map_err(failed);
364    }
365    let request = RunRequest {
366        package,
367        mode,
368        rounds,
369        seed,
370        cpus: placement,
371        perf_events: perf_event,
372        timeout: timeout_seconds.map(Duration::from_secs),
373        lock: lock.map(|lock| resolve(context, lock)),
374        output: output.map(|output| resolve(context, output)),
375        decision_rule,
376        idle_host,
377        stack_padding,
378        invocation: std::env::args().collect(),
379        ..RunRequest::new(scenario, resolve(context, artifacts))
380    };
381    let cancellation = Cancellation::new();
382    let _signals = cancellation.on_termination_signals();
383    let campaign = workspace(context, manifest_path)
384        .run(request, &cancellation, &mut std::io::stderr())
385        .map_err(failed)?;
386    eprintln!("{}\n{}", campaign.output.display(), campaign.report);
387    Ok(campaign)
388}
389
390/// Regenerate `summary.json` from the raw samples of a complete campaign.
391#[bake::task]
392pub fn summarize(
393    context: &mut Context,
394    #[bake(help = "Campaign directory.")] output: PathBuf,
395) -> Result<Campaign> {
396    let campaign = summarize_directory(&resolve(context, output)).map_err(failed)?;
397    eprintln!("{}", campaign.report);
398    Ok(campaign)
399}