use anyhow::{Context, Result, bail};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use usage_rs::{Args, Cli, Subcommands};
use tak_cli::accept::{self, Acceptances};
use tak_cli::backfill;
use tak_cli::baseline::{self, Baseline, Store};
use tak_cli::compare;
use tak_cli::config::{
self, AutoRuns, Config, DEFAULT_BUDGET, DEFAULT_MAX_RUNS, DEFAULT_MIN_RUNS, DEFAULT_RUNS,
DEFAULT_WARMUP, Runs, SELF_TOOL, Subject,
};
use tak_cli::detect;
use tak_cli::export::{self, ExportResult};
use tak_cli::measure::{self, Plan};
use tak_cli::notes;
use tak_cli::record::{self, Record, SCHEMA_VERSION};
use tak_cli::settings::{CliLayer, EnvLayer, Settings, TakConfigLayer, config_source};
#[derive(Cli)]
#[usage(completion = true)]
#[usage(
name = "tak",
bin = "tak",
version,
about = "CLI performance, tracked",
unknown_flags = "error",
config = tak_cli::settings::Settings
)]
struct Cli {
#[usage(subcommand)]
cmd: Cmd,
#[usage(long, global, value_name = "VAR", setting = "env_deny")]
env_deny: Vec<String>,
#[usage(long, global, value_name = "VAR", setting = "env_allow")]
env_allow: Vec<String>,
#[usage(long, global, value_name = "PCT", setting = "gate_pct")]
gate_pct: Option<f64>,
#[usage(long, global, value_name = "N", setting = "gate_min_delta")]
gate_min_delta: Option<u64>,
#[usage(long, global, setting = "allow_empty")]
allow_empty: bool,
#[usage(long = "no-credit", action = usage_rs::ArgAction::SetFalse, global = true)]
#[usage(default = "true", setting = "credit")]
credit: bool,
#[usage(long, global, value_name = "CLASS", setting = "runner_class")]
runner: Option<String>,
}
#[derive(Subcommands)]
enum Cmd {
Completion {
#[usage(
arg,
choices("bash", "elvish", "zsh", "fish", "nu", "nushell", "powershell", "pwsh")
)]
shell: String,
},
Run {
#[usage(long)]
bench: Option<String>,
#[usage(long, value_name = "N|auto")]
runs: Option<String>,
#[usage(long)]
warmup: Option<u32>,
#[usage(long)]
no_counters: bool,
#[usage(long)]
allocations: bool,
#[usage(long)]
record: bool,
#[usage(long)]
no_progress: bool,
#[usage(long, value_name = "NAME")]
group: Vec<String>,
#[usage(long, value_name = "NAME")]
subject: Vec<String>,
#[usage(long, value_name = "N")]
seed: Option<u64>,
#[usage(long, value_name = "PATH")]
config: Option<std::path::PathBuf>,
#[usage(long)]
dry_run: bool,
#[usage(long, value_name = "PATH")]
export_json: Option<std::path::PathBuf>,
#[usage(long, value_name = "DIR")]
profile_dir: Option<std::path::PathBuf>,
#[usage(long, value_name = "NAME")]
save_baseline: Option<String>,
#[usage(long, value_name = "NAME")]
baseline: Option<String>,
#[usage(long)]
gate: bool,
#[usage(arg, double_dash = "required")]
cmd: Vec<String>,
},
History {
#[usage(arg, default = "HEAD")]
rev: String,
#[usage(long, default = "origin")]
remote: String,
},
Log {
#[usage(arg, default = "HEAD")]
rev: String,
#[usage(short = 'n', long, default = "30")]
limit: usize,
#[usage(long, value_name = "NAME")]
bench: Vec<String>,
#[usage(long, value_name = "PATH")]
html: Option<std::path::PathBuf>,
#[usage(long, default = "origin")]
remote: String,
},
Push(RemoteArgs),
Artifact(Box<ArtifactArgs>),
Init(RemoteArgs),
Backfill {
#[usage(long, value_name = "RANGE")]
commits: Option<String>,
#[usage(long)]
force: bool,
#[usage(long)]
repo: Option<String>,
#[usage(long)]
bin: Option<String>,
#[usage(arg, double_dash = "required")]
args: Vec<String>,
#[usage(long)]
bench: Option<String>,
#[usage(long, default = "20")]
limit: usize,
#[usage(long)]
runs: Option<u32>,
#[usage(long)]
dry_run: bool,
},
Compare {
#[usage(arg, default = "origin/main")]
base: String,
#[usage(long, default = "HEAD")]
rev: String,
#[usage(long, default = "origin")]
remote: String,
#[usage(long)]
no_gate: bool,
#[usage(long, value_name = "BENCH")]
accept: Vec<String>,
},
Explain {
#[usage(arg)]
base: std::path::PathBuf,
#[usage(arg)]
head: std::path::PathBuf,
#[usage(long, default = "10", value_name = "N")]
top: usize,
},
Detect {
#[usage(arg, default = "HEAD")]
rev: String,
#[usage(long, default = "20", value_name = "N")]
window: usize,
#[usage(long, default = "origin")]
remote: String,
#[usage(long)]
no_gate: bool,
#[usage(long, value_name = "BENCH")]
accept: Vec<String>,
},
Doctor,
Settings {
#[usage(long)]
docs: bool,
},
#[usage(hide)]
Usage,
}
#[derive(Args)]
struct ArtifactArgs {
#[usage(subcommand)]
cmd: ArtifactCmd,
}
#[derive(Subcommands)]
enum ArtifactCmd {
Export {
#[usage(long, value_name = "PATH")]
output: std::path::PathBuf,
#[usage(long, default = "HEAD")]
rev: String,
},
Publish {
#[usage(arg)]
path: std::path::PathBuf,
#[usage(long, value_name = "REV")]
expect: String,
#[usage(long, default = "origin")]
remote: String,
},
}
#[derive(Args)]
struct RemoteArgs {
#[usage(long, default = "origin")]
remote: String,
}
fn runner_class(settings: &Settings) -> String {
if !settings.runner_class.trim().is_empty() {
return settings.runner_class.clone();
}
if std::env::var("GITHUB_ACTIONS").is_ok() {
let os = std::env::var("RUNNER_OS").unwrap_or_else(|_| "unknown".into());
let arch = std::env::var("RUNNER_ARCH").unwrap_or_else(|_| "unknown".into());
return format!("gha-{}-{}", os.to_lowercase(), arch.to_lowercase());
}
format!("local-{}-{}", std::env::consts::OS, std::env::consts::ARCH)
}
fn now_rfc3339() -> String {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
rfc3339(i64::try_from(secs).unwrap_or(i64::MAX))
}
fn rfc3339(secs: i64) -> String {
let days = secs.div_euclid(86_400);
let rem = secs.rem_euclid(86_400);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!(
"{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
rem / 3600,
(rem % 3600) / 60,
rem % 60
)
}
struct RunOpts {
bench: Option<String>,
runs: Option<Runs>,
warmup: Option<u32>,
no_counters: bool,
allocations: bool,
record: bool,
no_progress: bool,
groups: Vec<String>,
subjects: Vec<String>,
seed: Option<u64>,
export_json: Option<std::path::PathBuf>,
profile_dir: Option<std::path::PathBuf>,
config: Option<std::path::PathBuf>,
dry_run: bool,
save_baseline: Option<String>,
baseline: Option<String>,
gate: bool,
}
#[derive(Default)]
struct Local {
store: Option<Store>,
against: Option<Baseline>,
gates: Option<compare::Gates>,
}
fn baseline_gates(opts: &RunOpts, settings: &Settings, adhoc: bool) -> Result<compare::Gates> {
if adhoc && !opts.gate {
return Ok(compare::Gates::uniform(global_gate(settings)?));
}
compare_gates(settings, opts.config.as_deref()).with_context(|| {
if adhoc {
"--gate needs a valid tak.toml to find per-benchmark gates; run without --gate \
to report only"
} else {
"could not read the gates in tak.toml"
}
})
}
fn open_local(opts: &RunOpts, settings: &Settings, adhoc: bool) -> Result<Local> {
if opts.gate && opts.baseline.is_none() {
bail!(
"--gate applies to --baseline; to gate against another commit's recorded \
measurements, use `tak compare`"
);
}
for name in [&opts.baseline, &opts.save_baseline].into_iter().flatten() {
baseline::validate_name(name)?;
}
if opts.baseline.is_none() && opts.save_baseline.is_none() {
return Ok(Local::default());
}
let store = Store::locate()?;
if let Some(name) = &opts.save_baseline {
store.check_saveable(name)?;
}
let against = opts
.baseline
.as_deref()
.map(|name| store.load(name))
.transpose()?;
let gates = against
.is_some()
.then(|| baseline_gates(opts, settings, adhoc))
.transpose()?;
Ok(Local {
store: Some(store),
against,
gates,
})
}
struct Measured {
bench: String,
subject: Subject,
version: Option<Option<String>>,
samples: measure::Samples,
custom: BTreeMap<String, Option<f64>>,
record: Record,
count_failed: bool,
profile: Option<Vec<u8>>,
}
fn check_profile_paths<'a>(
opts: &RunOpts,
plans: impl IntoIterator<Item = (&'a str, bool, &'a [Subject])>,
) -> Result<()> {
let Some(dir) = &opts.profile_dir else {
return Ok(());
};
if opts.no_counters {
bail!(
"--profile-dir keeps the profiles of instruction counts, and --no-counters turns them off"
);
}
for (bench, multi, subjects) in plans {
for s in subjects {
tak_cli::profile::path_for(dir, bench, &record_tool(multi, s))?;
}
}
Ok(())
}
fn check_recorded_names(settings: &Settings, bench: Option<&str>) -> Result<()> {
record::check_name("runner class", &runner_class(settings))?;
if let Some(bench) = bench {
record::check_name("benchmark", bench)?;
}
Ok(())
}
fn check_tak_tool() -> Result<()> {
if let Ok(tool) = std::env::var("TAK_TOOL") {
record::check_name("TAK_TOOL", &tool)?;
}
Ok(())
}
fn cmd_run(opts: RunOpts, cmd: Vec<String>, settings: &Settings) -> Result<()> {
global_gate(settings)?;
check_recorded_names(settings, opts.bench.as_deref())?;
let local = open_local(&opts, settings, !cmd.is_empty())?;
if cmd.is_empty() {
return run_declared(opts, settings, &local);
}
check_tak_tool()?;
if !opts.subjects.is_empty() {
bail!(
"--subject selects subjects declared in tak.toml; it cannot be used with a command after `--`"
);
}
if !opts.groups.is_empty() {
bail!(
"--group selects benchmarks declared in tak.toml; it cannot be used with a command after `--`"
);
}
let bench = opts.bench.clone().unwrap_or_else(|| "default".to_string());
let subject = Subject {
name: SELF_TOOL.to_string(),
cmd,
prepare: None,
setup: None,
setup_dir: None,
check: None,
dir: None,
version_cmd: None,
env: BTreeMap::new(),
vars: BTreeMap::new(),
when: None,
runs: opts.runs.unwrap_or(Runs::Fixed(DEFAULT_RUNS)),
auto: AutoRuns {
budget: DEFAULT_BUDGET,
min: DEFAULT_MIN_RUNS,
max: DEFAULT_MAX_RUNS,
},
warmup: opts.warmup.unwrap_or(DEFAULT_WARMUP),
counters: true,
allocations: opts.allocations,
ok_exit_codes: config::DEFAULT_OK_EXIT_CODES.to_vec(),
metrics: BTreeMap::new(),
};
check_profile_paths(
&opts,
[(bench.as_str(), false, std::slice::from_ref(&subject))],
)?;
let seed = opts.seed.unwrap_or_else(random_seed);
if opts.dry_run {
print_plan(
&bench,
false,
std::slice::from_ref(&subject),
opts.no_counters,
);
return Ok(());
}
let (measured, _) = measure_bench(&bench, &[subject], false, seed, &opts, settings)?;
finish(measured, Vec::new(), &opts, seed, settings, &local)
}
fn run_declared(opts: RunOpts, settings: &Settings, local: &Local) -> Result<()> {
let cwd = std::env::current_dir()?;
let found = match &opts.config {
Some(path) => {
let path = std::path::absolute(path)
.with_context(|| format!("could not resolve {}", path.display()))?;
let cfg = Config::load(&path)?;
Some((path, cfg))
}
None => Config::find(&cwd)?,
};
let Some((path, cfg)) = found else {
bail!(
"no command given and no {} found in {} or any parent.\n\
Pass a command after `--`, or declare one:\n\n\
\x20 [bench.startup]\n\
\x20 cmd = [\"./mycli\", \"--version\"]",
config::FILE_NAME,
cwd.display()
);
};
let Planned { mut plans, skipped } = plan_declared(&cfg, &path, &opts)?;
print_skipped(&skipped);
let root = path.parent().map(Path::to_path_buf).unwrap_or_default();
for (_, _, subjects) in &mut plans {
for s in subjects {
s.anchor(&root);
}
}
if plans.is_empty() {
if opts.gate && !opts.dry_run {
bail!(
"nothing to gate against baseline `{}`: {}",
opts.baseline.as_deref().unwrap_or_default(),
if skipped.is_empty() {
format!("{} declares no benchmarks", path.display())
} else {
"every selected benchmark or subject has a false `when`".to_string()
}
);
}
if skipped.is_empty() {
println!("{} declares no benchmarks", path.display());
return Ok(());
}
if !opts.dry_run
&& (opts.record || opts.export_json.is_some() || opts.save_baseline.is_some())
{
bail!(
"nothing to {}: every selected benchmark or subject has a false `when`",
if opts.record {
"record"
} else if opts.save_baseline.is_some() {
"save"
} else {
"export"
}
);
}
println!("nothing to run: every selected benchmark or subject has a false `when`");
return Ok(());
}
check_profile_paths(
&opts,
plans
.iter()
.map(|(name, multi, subjects)| (name.as_str(), *multi, subjects.as_slice())),
)?;
if opts.dry_run {
println!("{}", path.display());
for (name, multi, subjects) in &plans {
print_plan(name, *multi, subjects, opts.no_counters);
}
return Ok(());
}
let seed = opts.seed.unwrap_or_else(random_seed);
let mut measured = Vec::new();
let mut failed = Vec::new();
for (name, multi, subjects) in &plans {
let (m, f) = measure_bench(name, subjects, *multi, seed, &opts, settings)?;
measured.extend(m);
failed.extend(f);
}
finish(measured, failed, &opts, seed, settings, local)
}
type BenchPlan = (String, bool, Vec<Subject>);
struct Planned {
plans: Vec<BenchPlan>,
skipped: Vec<(String, Option<String>, String)>,
}
fn select_groups<'a>(
cfg: &Config,
path: &Path,
opts: &RunOpts,
selected: Vec<(String, &'a tak_cli::config::Bench)>,
) -> Result<Vec<(String, &'a tak_cli::config::Bench)>> {
if opts.groups.is_empty() {
return Ok(selected);
}
if opts.bench.is_some() {
bail!("--bench and --group cannot be combined; --bench already names one benchmark");
}
for g in &opts.groups {
if !cfg.has_group(g) {
let found: Vec<_> = cfg.group_names().collect();
bail!(
"no group `{g}` in {} (found: {})",
path.display(),
if found.is_empty() {
"none".to_string()
} else {
found.join(", ")
}
);
}
}
for g in &opts.groups {
if !selected.iter().any(|(_, b)| b.group() == Some(g.as_str())) {
bail!("no benchmark in {} names group `{g}`", path.display());
}
}
Ok(selected
.into_iter()
.filter(|(_, b)| {
b.group()
.is_some_and(|g| opts.groups.iter().any(|o| o == g))
})
.collect())
}
fn plan_declared(cfg: &Config, path: &Path, opts: &RunOpts) -> Result<Planned> {
let selected: Vec<_> = match &opts.bench {
Some(name) => {
let b = cfg.bench.get(name).with_context(|| {
format!(
"no benchmark `{name}` in {} (found: {})",
path.display(),
if cfg.bench.is_empty() {
"none".to_string()
} else {
cfg.bench.keys().cloned().collect::<Vec<_>>().join(", ")
}
)
})?;
vec![(name.clone(), b)]
}
None => cfg.bench.iter().map(|(k, v)| (k.clone(), v)).collect(),
};
let selected = select_groups(cfg, path, opts, selected)?;
let mut plans = Vec::new();
let mut seen = std::collections::BTreeSet::new();
let env = tak_cli::template::env();
let mut skipped = Vec::new();
let mut hidden: std::collections::BTreeMap<String, (String, String)> = Default::default();
for (name, b) in selected {
let subjects = cfg.subjects(&name)?;
seen.extend(subjects.iter().map(|s| s.name.clone()));
if !opts.subjects.is_empty() && !subjects.iter().any(|s| opts.subjects.contains(&s.name)) {
continue;
}
if let Some(when) = b.when()
&& !tak_cli::condition::eval(when, &env, &name, None)
.with_context(|| format!("benchmark `{name}`"))?
{
for s in subjects {
hidden
.entry(s.name)
.or_insert_with(|| (name.clone(), when.to_string()));
}
skipped.push((name.clone(), None, when.to_string()));
continue;
}
let mut kept = Vec::with_capacity(subjects.len());
for s in subjects {
if !opts.subjects.is_empty() && !opts.subjects.contains(&s.name) {
continue;
}
match &s.when {
Some(when)
if !tak_cli::condition::eval(when, &env, &name, Some(&s.name))
.with_context(|| format!("benchmark `{name}`, subject `{}`", s.name))? =>
{
hidden
.entry(s.name.clone())
.or_insert_with(|| (name.clone(), when.clone()));
skipped.push((name.clone(), Some(s.name.clone()), when.clone()));
}
_ => kept.push(s),
}
}
let mut subjects = kept;
if subjects.is_empty() {
continue;
}
if !opts.subjects.is_empty() {
subjects.retain(|s| opts.subjects.contains(&s.name));
if subjects.is_empty() {
continue;
}
}
let mut subjects = subjects
.into_iter()
.map(|s| {
let subject = s.name.clone();
tak_cli::template::render(s, &name, &env)
.with_context(|| format!("benchmark `{name}`, subject `{subject}`"))
})
.collect::<Result<Vec<_>>>()?;
for s in &mut subjects {
let impossible = config::check_platform_exit_codes(&s.ok_exit_codes, cfg!(unix))
.with_context(|| format!("benchmark `{name}`, subject `{}`", s.name))?;
if !impossible.is_empty() {
let range = config::exit_code_range(cfg!(unix)).expect("narrowed");
eprintln!(
" warning: {name} ({}): ok_exit_codes {} can never match here: exit codes on this platform are {} to {}",
s.name,
config::join_codes(&impossible),
range.start(),
range.end()
);
}
s.runs = opts.runs.unwrap_or(s.runs);
s.warmup = opts.warmup.unwrap_or(s.warmup);
s.allocations |= opts.allocations;
}
plans.push((name, b.is_multi(), subjects));
}
let planned: std::collections::BTreeSet<&str> = plans
.iter()
.flat_map(|(_, _, subjects)| subjects.iter().map(|s| s.name.as_str()))
.collect();
if let Some(off) = opts
.subjects
.iter()
.find(|s| !planned.contains(s.as_str()) && hidden.contains_key(*s))
{
let (bench, when) = &hidden[off];
bail!(
"subject `{off}` was asked for, but `when` is false for it in benchmark `{bench}`: {when}"
);
}
if let Some(missing) = opts.subjects.iter().find(|s| !seen.contains(*s)) {
bail!(
"no subject `{missing}` in the selected benchmarks (found: {})",
seen.into_iter().collect::<Vec<_>>().join(", ")
);
}
if plans.iter().any(|(_, multi, _)| !multi) {
check_tak_tool()?;
}
Ok(Planned { plans, skipped })
}
fn print_skipped(skipped: &[(String, Option<String>, String)]) {
for (bench, subject, when) in skipped {
let what = subject
.as_ref()
.map_or(bench.to_string(), |s| format!("{bench} ({s})"));
eprintln!(" skipping {what}: `when` is false: {when}");
}
}
fn random_seed() -> u64 {
fastrand::u64(..1 << 53)
}
fn print_plan(bench: &str, multi: bool, subjects: &[Subject], no_counters: bool) {
println!(
"\n {bench}{}",
if multi { "" } else { " (single command)" }
);
for s in subjects {
if multi {
println!(" {}", s.name);
}
let pad = if multi { " " } else { " " };
println!("{pad}cmd {}", shell_words(&s.cmd));
if let Some(p) = &s.setup {
match &s.setup_dir {
Some(d) => println!("{pad}setup {} (in {})", shell_words(p), d.display()),
None => println!("{pad}setup {}", shell_words(p)),
}
}
if let Some(v) = &s.version_cmd {
println!("{pad}version {}", shell_words(v));
}
if let Some(p) = &s.prepare {
println!("{pad}prepare {}", shell_words(p));
}
if let Some(c) = &s.check {
println!("{pad}check {}", shell_words(c));
}
if let Some(d) = &s.dir {
println!("{pad}dir {}", d.display());
}
for (k, v) in &s.env {
println!("{pad}env {k}={}", shell_words(std::slice::from_ref(v)));
}
let runs = match s.runs {
Runs::Fixed(n) => n.to_string(),
Runs::Auto => format!(
"auto ({} budget, {}..={})",
tak_cli::progress::fmt(s.auto.budget),
s.auto.min,
s.auto.max
),
};
println!("{pad}runs {runs}, warmup {}", s.warmup);
if s.ok_exit_codes != config::DEFAULT_OK_EXIT_CODES {
let codes: Vec<String> = s.ok_exit_codes.iter().map(i32::to_string).collect();
println!("{pad}ok exit {}", codes.join(", "));
}
if s.counters && !no_counters {
println!("{pad}counters on");
}
if s.allocations {
println!("{pad}allocations on");
}
for (name, source) in &s.metrics {
match source {
config::MetricSource::File(p) => {
println!("{pad}metric {name} file {}", p.display())
}
config::MetricSource::Cmd(c) => {
println!("{pad}metric {name} cmd {}", shell_words(c))
}
}
}
}
}
fn shell_words(argv: &[String]) -> String {
argv.iter()
.map(|a| {
if !a.is_empty()
&& a.chars()
.all(|c| c.is_ascii_alphanumeric() || "-_./=:,@%+".contains(c))
{
a.clone()
} else {
format!("'{}'", a.replace('\'', r"'\''"))
}
})
.collect::<Vec<_>>()
.join(" ")
}
fn finish(
measured: Vec<Measured>,
failed: Vec<String>,
opts: &RunOpts,
seed: u64,
settings: &Settings,
local: &Local,
) -> Result<()> {
if let Some(path) = &opts.export_json {
let results = measured
.iter()
.map(|m| {
let command = if m.subject.name == SELF_TOOL {
&m.bench
} else {
&m.subject.name
};
let mut r = ExportResult::new(&m.bench, &m.subject.name, command, &m.samples.times)
.with_exit_codes(&m.samples.exit_codes);
r.version = m.version.clone();
r.allocations = export::Allocations::from_metrics(&m.record.metrics);
r.metrics = m.custom.clone();
if m.subject.check.is_some() {
r.with_checks(&m.samples.checks)
} else {
r
}
})
.collect();
let meta = export::Meta {
tak_version: env!("CARGO_PKG_VERSION").to_string(),
seed,
runner: runner_class(settings),
time: now_rfc3339(),
machine: tak_cli::machine::detect(),
};
export::write(path, meta, results)?;
println!(
"\n exported {} result(s) to {}",
measured.len(),
path.display()
);
}
if let Some(dir) = &opts.profile_dir {
let runner = runner_class(settings);
let commit = notes::rev_parse("HEAD").ok();
let mut written = 0usize;
for m in &measured {
if let Some(raw) = &m.profile {
let dest = tak_cli::profile::path_for(dir, &m.bench, &m.record.tool)?;
let origin = tak_cli::profile::Origin {
runner: runner.clone(),
commit: commit.clone(),
bench: m.bench.clone(),
subject: m.record.tool.clone(),
};
tak_cli::profile::write(&dest, raw, &origin)?;
written += 1;
}
}
println!("\n wrote {written} profile(s) to {}", dir.display());
}
let failing = failing_checks(&measured);
let compared = match (&local.against, &local.gates) {
(Some(b), Some(gates)) => Some(report_against(
b,
&measured,
&failing,
gates,
opts.gate && settings.allow_empty,
)),
_ => None,
};
let storing = match (opts.record, &opts.save_baseline) {
(true, Some(name)) => Some(format!("recording or saving baseline `{name}`")),
(true, None) => Some("recording".to_string()),
(false, Some(name)) => Some(format!("saving baseline `{name}`")),
(false, None) => None,
};
if !failed.is_empty() {
if let Some(storing) = &storing {
eprintln!("\n not {storing}: a run with a failed subject would be stored incomplete");
}
bail!("{} subject(s) failed: {}", failed.len(), failed.join(", "));
}
let broken = failed_metrics(&measured);
if !broken.is_empty() {
if let Some(storing) = &storing {
eprintln!(
"\n not {storing}: a run missing a declared metric would be stored incomplete"
);
}
bail!("{} metric(s) failed: {}", broken.len(), broken.join(", "));
}
let verdict = match (&local.against, &compared, &local.gates) {
(Some(against), Some(compared), Some(gates)) if opts.gate => {
gate_against(against, compared, &failing, gates)
}
_ => Ok(()),
};
let kept = match &opts.save_baseline {
Some(name) if verdict.is_err() && opts.baseline.as_ref() == Some(name) => Some(name),
_ => None,
};
if let Some(storing) = &storing {
if !failing.is_empty() {
eprintln!(
"
not {storing}: stored measurements keep timings without check verdicts, so a \
run with a failed check would be stored as if it had passed"
);
bail!("check failed: {}", labels(&failing));
}
let records: Vec<Record> = measured.into_iter().map(|m| m.record).collect();
if let (Some(name), Some(store)) = (&opts.save_baseline, &local.store)
&& kept.is_none()
{
save_baseline(store, name, &records)?;
}
if opts.record {
record_all(&records).with_context(|| match &opts.save_baseline {
Some(name) if kept.is_none() => format!(
"baseline `{name}` was saved, but nothing was recorded to {}; \
re-running the same command saves the baseline again and records",
notes::NOTES_REF
),
_ => format!("nothing was recorded to {}", notes::NOTES_REF),
})?;
}
}
match kept {
Some(name) => verdict
.with_context(|| format!("baseline `{name}` was not replaced because the gate failed")),
None => verdict,
}
}
struct FailedCheck {
bench: String,
tool: String,
label: String,
}
fn failing_checks(measured: &[Measured]) -> Vec<FailedCheck> {
measured
.iter()
.filter(|m| m.samples.passed() < m.samples.checks.len())
.map(|m| {
let label = if m.subject.name == SELF_TOOL {
m.bench.clone()
} else {
format!("{} ({})", m.bench, m.subject.name)
};
FailedCheck {
bench: m.bench.clone(),
tool: m.record.tool.clone(),
label: format!(
"{label} failed {} of {}",
m.samples.checks.len() - m.samples.passed(),
m.samples.checks.len()
),
}
})
.collect()
}
fn labels<'a>(failing: impl IntoIterator<Item = &'a FailedCheck>) -> String {
failing
.into_iter()
.map(|f| f.label.as_str())
.collect::<Vec<_>>()
.join(", ")
}
struct Against {
comparison: compare::Comparison,
gaps: Vec<(compare::Key, baseline::Gap)>,
measured: BTreeSet<compare::Key>,
}
fn report_against(
against: &Baseline,
measured: &[Measured],
failing: &[FailedCheck],
gates: &compare::Gates,
allow_empty: bool,
) -> Against {
let current: Vec<Record> = measured.iter().map(|m| m.record.clone()).collect();
let base = baseline::relevant(&against.records, ¤t);
let mut comparison = compare::compare(&base, ¤t);
let count_failed: BTreeSet<compare::Key> = measured
.iter()
.filter(|m| m.count_failed)
.map(|m| {
(
m.record.bench.clone(),
m.record.tool.clone(),
m.record.runner.clone(),
)
})
.collect();
let gaps: Vec<_> = baseline::gaps(&against.records, ¤t, &count_failed)
.into_iter()
.filter(|(k, _)| gates.get(&k.0, &k.1).enabled)
.collect();
let keys: BTreeSet<compare::Key> = current
.iter()
.map(|r| (r.bench.clone(), r.tool.clone(), r.runner.clone()))
.collect();
let enabled = |bench: &str, tool: &str| gates.get(bench, tool).enabled;
comparison.allowed_empty = allow_empty
&& comparison.is_empty()
&& keys.iter().any(|k| enabled(&k.0, &k.1))
&& !failing.iter().any(|f| enabled(&f.bench, &f.tool))
&& !gaps
.iter()
.any(|(_, gap)| matches!(gap, baseline::Gap::CountFailed));
let mut stranded: BTreeMap<Vec<String>, Vec<String>> = BTreeMap::new();
for k in &keys {
if base.iter().any(|r| r.bench == k.0 && r.tool == k.1) {
continue;
}
let elsewhere = baseline::other_runners(&against.records, k);
if !elsewhere.is_empty() {
stranded
.entry(elsewhere)
.or_default()
.push(describe_series(k));
}
}
for (runners, series) in &stranded {
let runners: BTreeSet<&str> = runners.iter().map(String::as_str).collect();
eprintln!(
" warning: baseline `{}` holds {} only for runner class {}. Runner classes are \
never compared with each other.",
against.name,
series.join(", "),
quoted(&runners)
);
}
println!(
"\n compared against baseline `{}` ({})\n",
against.name,
against.path.display()
);
print!(
"{}",
compare::markdown(&comparison, &compare::Trend::new(), gates, false)
);
if !failing.is_empty() {
println!(
"\n**Check failed, so this comparison is not evidence of an improvement:** {}. \
Those numbers come from samples that did the wrong work.",
labels(failing)
);
}
if !gaps.is_empty() {
println!("\nNot gated: {}", describe_gaps(&gaps));
}
Against {
comparison,
gaps,
measured: keys,
}
}
fn describe_gaps(gaps: &[(compare::Key, baseline::Gap)]) -> String {
gaps.iter()
.map(|(k, why)| format!("{} ({why})", describe_series(k)))
.collect::<Vec<_>>()
.join(", ")
}
fn quoted(names: &BTreeSet<&str>) -> String {
names
.iter()
.map(|n| format!("`{}`", compare::escape_control(n)))
.collect::<Vec<_>>()
.join(", ")
}
fn describe_series(key: &compare::Key) -> String {
compare::describe(key)
}
fn gate_against(
against: &Baseline,
compared: &Against,
failing: &[FailedCheck],
gates: &compare::Gates,
) -> Result<()> {
let failing: Vec<&FailedCheck> = failing
.iter()
.filter(|f| gates.get(&f.bench, &f.tool).enabled)
.collect();
if !failing.is_empty() {
bail!(
"check failed, so nothing is gated against baseline `{}`: {}",
against.name,
labels(failing)
);
}
let comparison = &compared.comparison;
let enabled = |bench: &str, tool: &str| gates.get(bench, tool).enabled;
let nothing_gated = |why: &str| {
eprintln!(
" note: nothing was gated against baseline `{}`: {why}",
against.name
);
Ok(())
};
if !compared.measured.iter().any(|k| enabled(&k.0, &k.1)) {
return nothing_gated("every benchmark measured is report-only");
}
if comparison.allowed_empty {
warn_allowed_empty(&format!(
"nothing was compared against baseline `{}`",
against.name
));
return Ok(());
}
if !compared.gaps.is_empty() {
bail!(
"cannot gate against baseline `{}`: {}",
against.name,
describe_gaps(&compared.gaps)
);
}
if !comparison
.changes
.iter()
.any(|c| c.metric == compare::GATED_METRIC)
{
bail!(
"nothing to gate: no instruction count was measured both in this run and in \
baseline `{}`",
against.name
);
}
if !comparison
.changes
.iter()
.any(|c| c.metric == compare::GATED_METRIC && enabled(&c.bench, &c.tool))
{
return nothing_gated("every benchmark compared by instruction count is report-only");
}
let regressions = comparison.regressions(gates);
if regressions.is_empty() {
return Ok(());
}
if comparison.gated_uniformly(gates) {
let floor = match gates.global.min_delta {
0 => String::new(),
n => format!(" and {n} instructions"),
};
bail!(
"{} benchmark(s) regressed by more than {}%{floor} against baseline `{}`",
regressions.len(),
gates.global.pct,
against.name
);
}
bail!(
"{} benchmark(s) regressed beyond their gate against baseline `{}`",
regressions.len(),
against.name
)
}
fn save_baseline(store: &Store, name: &str, records: &[Record]) -> Result<()> {
if records.is_empty() {
return Ok(());
}
let path = store.save(name, records)?;
println!(
"\n saved {} measurement(s) to baseline `{name}` ({})",
records.len(),
path.display()
);
println!(" compare against it with: tak run --baseline {name}");
Ok(())
}
fn failed_metrics(measured: &[Measured]) -> Vec<String> {
measured
.iter()
.flat_map(|m| {
m.custom
.iter()
.filter(|(_, v)| v.is_none())
.map(|(name, _)| format!("{} `{name}`", label(m)))
})
.collect()
}
fn label(m: &Measured) -> String {
if m.subject.name == SELF_TOOL {
m.bench.clone()
} else {
format!("{} ({})", m.bench, m.subject.name)
}
}
fn metric_value(v: f64) -> String {
if v.fract() == 0.0 && v < 1e15 {
format!("{v:.0}")
} else {
v.to_string()
}
}
fn record_all(records: &[Record]) -> Result<()> {
if records.is_empty() {
return Ok(());
}
let sha = notes::rev_parse("HEAD").context("not in a git repository")?;
notes::append(&sha, records)?;
println!(
"\n recorded {} measurement(s) to {} for {}",
records.len(),
notes::NOTES_REF,
&sha[..12]
);
println!(" push with: tak push");
Ok(())
}
fn measure_bench(
bench: &str,
subjects: &[Subject],
multi: bool,
seed: u64,
opts: &RunOpts,
settings: &Settings,
) -> Result<(Vec<Measured>, Vec<String>)> {
measure_bench_vetted(bench, subjects, multi, seed, opts, settings, &|_| Ok(()))
}
fn measure_bench_vetted(
bench: &str,
subjects: &[Subject],
multi: bool,
seed: u64,
opts: &RunOpts,
settings: &Settings,
vet: &dyn Fn(&Subject) -> Result<()>,
) -> Result<(Vec<Measured>, Vec<String>)> {
if multi {
println!(
" {bench}: {} subjects, interleaved (--seed {seed})",
subjects.len()
);
}
let bench_seed = measure::seed_for(seed, bench);
let (results, versions) = if opts.no_progress {
let mut quiet = measure::Quiet;
let mut obs = Vetted {
inner: &mut quiet,
subjects,
vet,
};
measure::interleaved_with_versions(subjects, bench_seed, settings, &mut obs)
} else {
let names = subjects.iter().map(|s| s.name.clone()).collect();
let mut bar = tak_cli::progress::Bar::new(bench, names);
let mut obs = Vetted {
inner: &mut bar,
subjects,
vet,
};
let r = measure::interleaved_with_versions(subjects, bench_seed, settings, &mut obs);
bar.finish();
r
};
let versions: Vec<Option<Option<String>>> = subjects
.iter()
.zip(versions)
.map(|(s, v)| {
v.map(|r| match r {
Ok(v) => Some(v),
Err(e) => {
let label = if multi {
format!("{bench} ({})", s.name)
} else {
bench.to_string()
};
eprintln!(" warning: {label}: version_cmd failed, version unknown: {e:#}");
None
}
})
})
.collect();
let mut measured = Vec::new();
let mut failed = Vec::new();
for ((s, result), version) in subjects.iter().zip(results).zip(versions) {
let samples = match result {
Ok(samples) => samples,
Err(e) if !multi => return Err(e),
Err(e) => {
eprintln!(" error: {bench} ({}) dropped: {e:#}", s.name);
failed.push(format!("{bench} ({})", s.name));
continue;
}
};
let mut metrics = measure::stats(&samples.times);
let label = if multi {
format!("{bench} ({})", s.name)
} else {
bench.to_string()
};
for w in measure::warnings(&samples.times) {
eprintln!(" warning: {label}: {w}");
}
let checks = s
.check
.as_ref()
.map(|_| (samples.passed(), samples.checks.len()));
if let Some((passed, total)) = checks
&& passed < total
{
const LISTED: usize = 8;
let failed: Vec<usize> = samples
.checks
.iter()
.enumerate()
.filter(|(_, ok)| !**ok)
.map(|(i, _)| i + 1)
.collect();
let mut which = failed
.iter()
.take(LISTED)
.map(usize::to_string)
.collect::<Vec<_>>()
.join(", ");
if failed.len() > LISTED {
which.push_str(", …");
}
eprintln!(
" warning: {label}: check failed after {} of {total} samples (sample {which}); first: {}",
failed.len(),
samples.first_failure.as_deref().unwrap_or("(no detail)")
);
}
let (count_failed, profile) = if s.counters && !opts.no_counters {
let (counted, profile) = count_into(
&mut metrics,
s,
settings,
opts.profile_dir.is_some(),
&|| vet(s),
);
(!counted, profile)
} else {
(false, None)
};
if s.allocations
&& let Err(e) = allocations_into(&mut metrics, &label, s, settings, &|| vet(s))
{
if !multi {
return Err(e);
}
eprintln!(" error: {label} dropped: {e:#}");
failed.push(label.clone());
continue;
}
let mut custom = BTreeMap::new();
for (name, source) in &s.metrics {
let value = match vet(s).and_then(|()| measure::custom_metric(source, s, settings)) {
Ok(v) => {
metrics.insert(name.clone(), v);
Some(v)
}
Err(e) => {
eprintln!(" error: {label}: metric `{name}` failed: {e:#}");
None
}
};
custom.insert(name.clone(), value);
}
if multi {
let mut count = metrics
.get("instructions")
.map_or(String::new(), |i| format!(" instructions {i:.0}"));
if let (Some(blocks), Some(bytes)) =
(metrics.get("alloc_blocks"), metrics.get("alloc_bytes"))
{
count.push_str(&format!(" allocs {blocks:.0} ({bytes:.0} bytes)"));
}
let checked = checks.map_or(String::new(), |(p, t)| format!(" checks {p}/{t}"));
let extra: String = custom
.iter()
.filter_map(|(k, v)| v.map(|v| format!(" {k} {}", metric_value(v))))
.collect();
println!(
" {:<width$} min {:>9.2} p50 {:>9.2} mean {:>9.2} ± {:<8.2} max {:>9.2} ms n={}{checked}{count}{extra}",
s.name,
metrics["wall_min_ms"],
metrics["wall_p50_ms"],
metrics["wall_mean_ms"],
metrics["wall_stddev_ms"],
metrics["wall_max_ms"],
samples.times.len(),
width = subjects.iter().map(|s| s.name.len()).max().unwrap_or(0),
);
} else {
println!(" {bench} {}", s.cmd.join(" "));
}
for (k, v) in metrics.iter().filter(|_| !multi) {
if k == "wall_n" {
continue;
}
if k == "instructions" || k.starts_with("alloc_") {
println!(" {k:<16} {v:>14.0}");
} else if s.metrics.contains_key(k) {
println!(" {k:<16} {:>14}", metric_value(*v));
} else {
println!(" {k:<16} {v:>14.2}");
}
}
if let Some((passed, total)) = checks.filter(|_| !multi) {
println!(" {:<16} {:>14}", "checks", format!("{passed}/{total}"));
}
let tool = record_tool(multi, s);
measured.push(Measured {
bench: bench.to_string(),
subject: s.clone(),
version: version.clone(),
samples,
custom,
count_failed,
profile,
record: Record {
v: SCHEMA_VERSION,
bench: bench.to_string(),
tool,
version: version.flatten(),
runner: runner_class(settings),
ts: now_rfc3339(),
metrics,
},
});
}
Ok((measured, failed))
}
struct Vetted<'a> {
inner: &'a mut dyn measure::Observer,
subjects: &'a [Subject],
vet: &'a dyn Fn(&Subject) -> Result<()>,
}
impl measure::Observer for Vetted<'_> {
fn planned(&mut self, remaining: &[u64]) {
self.inner.planned(remaining);
}
fn setting_up(&mut self, subject: usize) {
self.inner.setting_up(subject);
}
fn set_up(&mut self, subject: usize) -> Result<()> {
self.inner.set_up(subject)?;
(self.vet)(&self.subjects[subject])
}
fn before_run(&mut self, subject: usize) -> Result<()> {
self.inner.before_run(subject)?;
(self.vet)(&self.subjects[subject])
}
fn started(&mut self, subject: usize) {
self.inner.started(subject);
}
fn finished(&mut self, subject: usize, elapsed: std::time::Duration) {
self.inner.finished(subject, elapsed);
}
fn dropped(&mut self, subject: usize) {
self.inner.dropped(subject);
}
}
fn record_tool(multi: bool, s: &Subject) -> String {
if multi {
s.name.clone()
} else {
std::env::var("TAK_TOOL").unwrap_or_else(|_| SELF_TOOL.into())
}
}
fn count_into(
metrics: &mut BTreeMap<String, f64>,
s: &Subject,
settings: &Settings,
profile: bool,
vet: &dyn Fn() -> Result<()>,
) -> (bool, Option<Vec<u8>>) {
let counted = if profile {
measure::subject_profile_vetted(s, settings, vet).map(|c| c.map(|(c, p)| (c, Some(p))))
} else {
measure::subject_instructions_vetted(s, settings, vet).map(|c| c.map(|c| (c, None)))
};
match counted {
Ok(Some((c, profile))) => {
let profile = match profile {
Some(Ok(raw)) => Some(raw),
Some(Err(e)) => {
eprintln!(
"warning: {}: instruction count kept, but its profile was not: {e:#}",
s.name
);
None
}
None => None,
};
metrics.insert("instructions".into(), c.min as f64);
if c.is_suspect() {
eprintln!(
"warning: instruction count varied {:.2}% across {} runs. \
The metric is deterministic, so this means the command \
itself does environment-dependent work (an update check, \
a cache it populates on first run, DNS). Its counts are \
not a usable gate until that is removed.",
c.spread_pct(),
c.runs
);
}
(true, profile)
}
Ok(None) => {
eprintln!(
"note: valgrind not found — recording timing only. \
Instruction counts are the only gate-able metric; on macOS/Windows \
run tak in a Linux container to get them."
);
(true, None)
}
Err(e) => {
eprintln!("warning: instruction counting failed: {e}");
(false, None)
}
}
}
fn allocations_into(
metrics: &mut BTreeMap<String, f64>,
label: &str,
s: &Subject,
settings: &Settings,
vet: &dyn Fn() -> Result<()>,
) -> Result<()> {
let refused = std::cell::RefCell::new(None);
let checked = || {
vet().inspect_err(|e| {
refused.replace(Some(format!("{e:#}")));
})
};
let result = measure::subject_allocations_vetted(s, settings, &checked);
if let Some(why) = refused.take() {
bail!("{why}");
}
match result {
Ok(Some(a)) => {
for (k, v) in a.min.metrics() {
metrics.insert(k.into(), v as f64);
}
if a.saw_nothing() {
eprintln!(
" warning: {label}: DHAT saw no heap allocations. It counts only \
calls it can intercept, so a statically linked binary or one with \
its own allocator (jemalloc, mimalloc) reports zero however much \
it allocates."
);
} else if a.is_suspect() {
eprintln!(
" warning: {label}: heap allocation totals varied {:.2}% across {} runs. \
A hermetic command repeats them exactly, so this one does \
environment-dependent work (a cache it fills on first run, an \
update check, DNS).",
a.totals_spread_pct(),
a.runs
);
} else if a.peak_is_unsteady() {
eprintln!(
" note: {label}: peak heap varied {:.2}% across {} runs while the \
totals did not. Threads that allocate at once reach a different peak \
depending on how valgrind interleaves them; the minimum is recorded.",
a.peak_spread_pct(),
a.runs
);
}
}
Ok(None) => {
eprintln!(" note: {label}: valgrind not found, so heap allocations were not measured.")
}
Err(e) => eprintln!(" warning: {label}: allocation counting failed: {e:#}"),
}
Ok(())
}
fn cmd_history(rev: String, remote: String) -> Result<()> {
let sha = notes::rev_parse(&rev).context("not in a git repository")?;
let recs = notes::read(Some(&remote), &sha)?;
if recs.is_empty() {
println!("no measurements recorded for {}", &sha[..12]);
return Ok(());
}
println!("{} measurement(s) for {}\n", recs.len(), &sha[..12]);
for r in recs {
let ins = r
.metrics
.get("instructions")
.map(|v| format!("{v:.0}"))
.unwrap_or_else(|| "-".into());
let wall = r
.metrics
.get("wall_min_ms")
.map(|v| format!("{v:.2}ms"))
.unwrap_or_else(|| "-".into());
println!(
" {:<16} {:<10} {:<22} instructions={:<14} wall_min={}",
compare::escape_control(&r.bench),
compare::escape_control(&r.tool),
compare::escape_control(&r.runner),
ins,
wall
);
}
Ok(())
}
struct LogOpts {
rev: String,
limit: usize,
bench: Vec<String>,
html: Option<std::path::PathBuf>,
remote: String,
}
fn cmd_log(opts: LogOpts, settings: &Settings) -> Result<()> {
if opts.limit == 0 {
bail!("-n must be at least 1");
}
notes::rev_parse(&opts.rev).with_context(|| format!("cannot resolve {}", opts.rev))?;
let _ = notes::fetch(&opts.remote);
let mut enough = tak_cli::report::Enough::new(opts.limit, &opts.bench);
let walked = notes::log_until(&opts.rev, |c| enough.after(c))?;
let shallow = walked
.last()
.is_some_and(|oldest| notes::is_shallow_boundary(&oldest.sha));
let history = tak_cli::report::build(walked, opts.limit, &opts.bench, shallow)?;
let Some(path) = opts.html else {
print!(
"{}",
tak_cli::report::markdown(&history, &opts.rev, settings.credit)
);
return Ok(());
};
let page = tak_cli::report::html(
&history,
&opts.rev,
repo_from_origin().as_deref(),
settings.credit,
);
std::fs::write(&path, page).with_context(|| format!("could not write {}", path.display()))?;
println!(
"wrote {}: {} series over {} recorded commit(s)",
path.display(),
history.series.len(),
history.commits.len()
);
Ok(())
}
const TREND_COMMITS: usize = 20;
fn gather_trend(base: &str, head_sha: &str, head_records: &[Record]) -> Result<compare::Trend> {
let commits = notes::rev_list(base, TREND_COMMITS)?;
let mut walked = Vec::with_capacity(commits.len());
for sha in commits.iter().rev() {
walked.push((sha.clone(), notes::read(None, sha)?));
}
Ok(compare::build_trend(&walked, head_sha, head_records))
}
fn floor_suffix(gate: &compare::Gate) -> String {
match gate.min_delta {
0 => String::new(),
n => format!(" and {n} instructions"),
}
}
fn warn_allowed_empty(what: &str) {
let message = format!("{what}; passing because `allow_empty` is on");
if std::env::var_os("GITHUB_ACTIONS").is_some() {
eprintln!("::warning::tak: {}", workflow_escape(&message));
} else {
eprintln!("warning: {message}");
}
}
fn workflow_escape(text: &str) -> String {
text.replace('%', "%25")
.replace('\r', "%0D")
.replace('\n', "%0A")
}
#[allow(clippy::too_many_arguments)]
fn cmd_compare(
base: String,
rev: String,
remote: String,
no_gate: bool,
accept_flags: Vec<String>,
cli: &CliLayer,
settings: &Settings,
) -> Result<()> {
let proposed = Policy {
gates: compare_gates(settings, None)?,
accept_trailers: settings.accept_trailers,
allow_empty: settings.allow_empty,
};
let base_sha = notes::rev_parse(&base).with_context(|| {
format!("cannot resolve {base}; tak compare needs the base commit locally, so fetch it")
})?;
let head_sha = notes::rev_parse(&rev).with_context(|| format!("cannot resolve {rev}"))?;
let (policy, from) = base_policy(&base_sha, cli)?;
let gates = &policy.gates;
let mut accepted = Acceptances::default();
for name in &accept_flags {
accepted.add_name(name, accept::Source::Flag)?;
}
let log = notes::trailers(&base_sha, &head_sha, accept::TRAILER, false);
let mut ignored = Acceptances::default();
if policy.accept_trailers {
let log = log.with_context(|| {
format!(
"cannot read {} trailers from {base}..{rev}",
accept::TRAILER
)
})?;
accepted.add_trailer_log(&log);
} else if let Ok(log) = log {
ignored.add_trailer_log(&log);
}
let base_records = notes::read(Some(&remote), &base_sha)?;
let head_records = notes::read(None, &head_sha)?;
let mut comparison = compare::compare(&base_records, &head_records)
.with_accepted(accepted)
.with_ignored_trailers(ignored);
let trend = gather_trend(&base_sha, &head_sha, &head_records).unwrap_or_default();
let at = detect::short(&base_sha);
let measured = base_records
.iter()
.chain(&head_records)
.map(|r| (r.bench.clone(), r.tool.clone()))
.collect();
let changed = proposed.changes_from(&policy, &measured);
comparison.gate_source = compare::gate_source(from.as_deref(), at, &changed);
comparison.allowed_empty = comparison.is_empty() && policy.allow_empty && !no_gate;
print!(
"{}",
compare::markdown(&comparison, &trend, gates, settings.credit)
);
if no_gate {
return Ok(());
}
if comparison.is_empty() {
if !policy.allow_empty {
bail!(
"nothing was compared: no series was measured on both {base} and {rev}. \
Either one side has no measurements recorded (the base predates \
adopting tak, or its notes were never pushed or fetched), or the two \
were measured on different runner classes, which are deliberately \
not comparable. Pass --allow-empty, or set `[gate] allow_empty = true` \
in the base's tak.toml, to accept this, as on the first pull request \
after adopting tak or across a runner-class migration"
)
}
warn_allowed_empty(&format!(
"nothing was compared: no series was measured on both {base} and {rev}"
));
return Ok(());
}
let regressions = comparison.failures(gates);
if regressions.is_empty() {
return Ok(());
}
if comparison.gated_uniformly(gates) {
let floor = floor_suffix(&gates.global);
bail!(
"{} benchmark(s) regressed by more than {}%{floor}",
regressions.len(),
gates.global.pct
)
}
bail!(
"{} benchmark(s) regressed beyond their gate",
regressions.len()
)
}
fn cmd_explain(base: &Path, head: &Path, top: usize) -> Result<()> {
if top == 0 {
bail!("--top must be at least 1");
}
let (pairs, unpaired) = tak_cli::profile::load(base, head)?;
let recorded = |o: &tak_cli::profile::Origin| {
let records = notes::read(None, o.commit.as_deref()?).ok()?;
records
.iter()
.filter(|r| r.bench == o.bench && r.tool == o.subject && r.runner == o.runner)
.filter_map(|r| r.metrics.get(compare::GATED_METRIC))
.map(|v| *v as u64)
.min()
};
print!(
"{}",
tak_cli::profile::markdown(&pairs, &unpaired, top, &recorded)
);
Ok(())
}
fn cmd_detect(
rev: String,
window: usize,
remote: String,
no_gate: bool,
accept_flags: Vec<String>,
settings: &Settings,
) -> Result<()> {
if window < 2 {
bail!("--window must be at least 2: a step needs two recorded commits");
}
let gates = compare_gates(settings, None)?;
let mut flags = Acceptances::default();
for name in &accept_flags {
flags.add_name(name, accept::Source::Flag)?;
}
let head = notes::rev_parse(&rev).with_context(|| format!("cannot resolve {rev}"))?;
let _ = notes::fetch(&remote);
let (walked, cutoff) = detect::gather(&head, window)?;
let mut found = detect::analyze(&walked, &gates);
found.cutoff = cutoff;
found.allow_empty = settings.allow_empty;
found.no_gate = no_gate;
let froms: BTreeSet<&str> = found.latest.iter().map(|s| s.from.as_str()).collect();
let mut logs = BTreeMap::new();
let mut ignored = Acceptances::default();
for from in froms {
let log = notes::trailers(from, &head, accept::TRAILER, true);
if settings.accept_trailers {
let log = log.with_context(|| {
format!(
"cannot read {} trailers from {}..{}",
accept::TRAILER,
detect::short(from),
detect::short(&head)
)
})?;
logs.insert(from.to_string(), log);
} else if let Ok(log) = log {
ignored.add_trailer_log(&log);
}
}
found.accept(&flags, &logs);
found.ignored_trailers = ignored;
print!("{}", detect::markdown(&found, settings.credit));
if found.empty_fails() {
bail!(
"nothing was compared at {}; pass --allow-empty, or set `[gate] allow_empty = \
true` in tak.toml, if that is expected",
detect::short(&head)
);
}
if found.nothing_compared() && found.allow_empty && !no_gate {
warn_allowed_empty(&format!("nothing was compared at {}", detect::short(&head)));
}
let failures = found.failures();
if failures.is_empty() || no_gate {
return Ok(());
}
if found.uniform() {
let floor = floor_suffix(&gates.global);
bail!(
"{} benchmark(s) stepped up by more than {}%{floor} at {}",
failures.len(),
gates.global.pct,
detect::short(&head)
)
}
bail!(
"{} benchmark(s) stepped beyond their gate at {}",
failures.len(),
detect::short(&head)
)
}
fn compare_gates(settings: &Settings, config: Option<&Path>) -> Result<compare::Gates> {
let global = global_gate(settings)?;
let found = match config {
Some(path) => Some((path.to_path_buf(), Config::load(path)?)),
None => Config::find(&std::env::current_dir()?)?,
};
Ok(match found {
Some((_, cfg)) => cfg.gates(global),
None => compare::Gates::uniform(global),
})
}
struct Policy {
gates: compare::Gates,
accept_trailers: bool,
allow_empty: bool,
}
impl Policy {
fn changes_from(&self, base: &Policy, measured: &BTreeSet<(String, String)>) -> Vec<String> {
let mut out = self.gates.changes_from(&base.gates, measured);
if self.accept_trailers != base.accept_trailers {
out.push("`accept_trailers`".to_string());
}
if self.allow_empty != base.allow_empty {
out.push("`allow_empty`".to_string());
}
out
}
}
fn base_policy(base_sha: &str, cli: &CliLayer) -> Result<(Policy, Option<String>)> {
let at = detect::short(base_sha);
let found = find_at(base_sha).with_context(|| {
format!(
"cannot read the gate policy from the base, {at}: tak compare reads {} out \
of the base commit's tree, so its objects must be in this clone",
config::FILE_NAME
)
})?;
let (layer, config, path) = match found {
None => (TakConfigLayer::empty(), None, None),
Some((path, text)) => {
let origin = format!("{at}:{path}");
let context = || {
format!(
"in {path} at the base, {at}, which sets the gate for this comparison; \
fix it there"
)
};
let layer = TakConfigLayer::parse(&origin, &text).with_context(context)?;
let config = Config::parse(&text).with_context(context)?;
(layer, Some(config), Some(path))
}
};
let settings = Settings::resolve(cli, &EnvLayer::from_process(), &layer)
.with_context(|| format!("could not read settings from the base, {at}"))?;
let global = global_gate(&settings)?;
let gates = match config {
Some(cfg) => cfg.gates(global),
None => compare::Gates::uniform(global),
};
let policy = Policy {
gates,
accept_trailers: settings.accept_trailers,
allow_empty: settings.allow_empty,
};
Ok((policy, path))
}
fn find_at(commit: &str) -> Result<Option<(String, String)>> {
let prefix = notes::prefix()?;
let mut dir = prefix.trim_end_matches('/');
loop {
let path = match dir {
"" => config::FILE_NAME.to_string(),
_ => format!("{dir}/{}", config::FILE_NAME),
};
if let Some(text) = notes::file_at(commit, &path)? {
return Ok(Some((path, text)));
}
if dir.is_empty() {
return Ok(None);
}
dir = dir.rsplit_once('/').map_or("", |(parent, _)| parent);
}
}
fn global_gate(settings: &Settings) -> Result<compare::Gate> {
compare::Gate::new(settings.gate_pct, settings.gate_min_delta).context("gate_pct")
}
fn cmd_doctor(settings: &Settings) -> Result<()> {
println!("tak doctor\n");
match notes::rev_parse("HEAD") {
Ok(sha) => println!(" ✓ git repository HEAD {}", &sha[..12]),
Err(_) => {
println!(" ✗ git repository not in one — nothing can be recorded");
return Ok(());
}
}
match std::process::Command::new("valgrind")
.arg("--version")
.output()
{
Ok(o) if o.status.success() => println!(
" ✓ valgrind {}",
String::from_utf8_lossy(&o.stdout).trim()
),
_ => println!(
" ! valgrind not found — timing only, no gate-able metric\n\
\x20 (expected on macOS/Windows; use a Linux container)"
),
}
match notes::fetch("origin") {
Ok(true) => println!(
" ✓ notes fetch refreshed {} from origin",
notes::NOTES_REF
),
Ok(false) => println!(
" ! notes fetch could not fetch {} (no remote, offline, or no data yet)",
notes::NOTES_REF
),
Err(e) => println!(" ! notes fetch {e}"),
}
println!(" · runner class {}", runner_class(settings));
Ok(())
}
fn repo_from_origin() -> Option<String> {
let out = std::process::Command::new("git")
.args(["remote", "get-url", "origin"])
.output()
.ok()?;
if !out.status.success() {
return None;
}
let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
let rest = [
"https://github.com/",
"http://github.com/",
"git@github.com:",
"ssh://git@github.com/",
]
.iter()
.find_map(|p| url.strip_prefix(p))?;
let slug = rest.trim_end_matches('/').trim_end_matches(".git");
(slug.matches('/').count() == 1 && !slug.is_empty()).then(|| slug.to_string())
}
fn backfill_workdir() -> Result<tempfile::TempDir> {
let mut builder = tempfile::Builder::new();
builder.prefix("tak-backfill-");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
builder.permissions(std::fs::Permissions::from_mode(0o700));
}
builder
.tempdir()
.context("could not create a backfill directory")
}
#[allow(clippy::too_many_arguments)]
fn cmd_backfill(
repo: Option<String>,
bin: Option<String>,
args: Vec<String>,
bench: String,
limit: usize,
runs: u32,
dry_run: bool,
settings: &Settings,
) -> Result<()> {
check_recorded_names(settings, Some(&bench))?;
let repo = repo
.or_else(repo_from_origin)
.context("could not infer the repository — pass --repo owner/name")?;
let bin = bin.unwrap_or_else(|| repo.rsplit('/').next().unwrap_or(&repo).to_string());
let args = if args.is_empty() {
vec!["--version".to_string()]
} else {
args
};
if !dry_run && !backfill::in_git_repo() {
bail!(
"not inside a git repository — measurements are recorded against tagged \
commits. Run from a clone of {repo}, or pass --dry-run."
);
}
let releases = backfill::list_releases(&repo, limit)?;
if releases.is_empty() {
println!("no releases with downloadable assets found for {repo}");
return Ok(());
}
println!("{} release(s) from {repo}\n", releases.len());
let workdir = backfill_workdir()?;
let mut recorded = 0usize;
let mut skipped = 0usize;
for (i, rel) in releases.iter().enumerate() {
let Some(asset) = backfill::pick_asset(&rel.assets) else {
println!(" {:<14} skipped — no asset for this platform", rel.tag);
skipped += 1;
continue;
};
let dir = workdir.path().join(backfill::release_dir_name(i, &rel.tag));
let path = match backfill::fetch_binary(asset, &bin, &dir) {
Ok(p) => p,
Err(e) => {
println!(" {:<14} skipped — {e}", rel.tag);
skipped += 1;
continue;
}
};
let mut cmd = vec![path.to_string_lossy().to_string()];
cmd.extend(args.iter().cloned());
let plan = Plan {
cmd: cmd.clone(),
warmup: 2,
runs,
dir: None,
settings: settings.clone(),
};
let mut metrics = match measure::wall(&plan) {
Ok(m) => m,
Err(e) => {
println!(" {:<14} skipped — {e}", rel.tag);
skipped += 1;
continue;
}
};
let mut suspect = None;
if let Ok(Some(c)) = measure::instructions(&cmd, None, settings) {
metrics.insert("instructions".into(), c.min as f64);
if c.is_suspect() {
suspect = Some(c.spread_pct());
}
}
let ins = metrics
.get("instructions")
.map(|v| format!("{v:>14.0}"))
.unwrap_or_else(|| format!("{:>14}", "-"));
println!(
" {:<14} wall_min {:>8.2}ms instructions {ins}{}",
rel.tag,
metrics["wall_min_ms"],
suspect
.map(|p| format!(" ⚠ varied {p:.1}%"))
.unwrap_or_default()
);
if dry_run {
continue;
}
let Some(sha) = backfill::tag_commit(&rel.tag) else {
println!(
" not recorded — tag {} not present locally (try `git fetch --tags`)",
rel.tag
);
skipped += 1;
continue;
};
let rec = Record {
v: SCHEMA_VERSION,
bench: bench.clone(),
tool: bin.clone(),
version: Some(backfill::version_of(&rel.tag).to_string()),
runner: runner_class(settings),
ts: rel.published_at.clone().unwrap_or_else(now_rfc3339),
metrics,
};
notes::append(&sha, &[rec])?;
recorded += 1;
}
if dry_run {
println!("\n dry run — nothing written");
} else {
println!(
"\n recorded {recorded}, skipped {skipped} → {}",
notes::NOTES_REF
);
println!(" push with: tak push");
}
Ok(())
}
struct CommitBackfill {
range: String,
bench: Option<String>,
limit: usize,
runs: Option<u32>,
force: bool,
dry_run: bool,
}
struct Pending {
sha: String,
subject: String,
needs: BTreeMap<String, Vec<String>>,
build_failed_before: bool,
measure_failed_before: Vec<String>,
}
impl Pending {
fn wanted(&self) -> bool {
!self.needs.is_empty() && !self.build_failed_before
}
fn passed_over(&self) -> bool {
(self.build_failed_before && !self.needs.is_empty())
|| (self.needs.is_empty() && !self.measure_failed_before.is_empty())
}
}
fn needs_for(
plans: &[BenchPlan],
have: &std::collections::BTreeSet<(String, String)>,
force: bool,
) -> BTreeMap<String, Vec<String>> {
let mut needs = BTreeMap::new();
for (bench, multi, subjects) in plans {
let missing: Vec<String> = subjects
.iter()
.filter(|s| force || !have.contains(&(bench.clone(), record_tool(*multi, s))))
.map(|s| s.name.clone())
.collect();
if !missing.is_empty() {
needs.insert(bench.clone(), missing);
}
}
needs
}
fn describe_needs(needs: &BTreeMap<String, Vec<String>>, plans: &[BenchPlan]) -> String {
needs
.iter()
.map(|(bench, subjects)| {
let all = plans
.iter()
.find(|(b, _, _)| b == bench)
.is_some_and(|(_, _, s)| s.len() == subjects.len());
if all {
bench.clone()
} else {
format!("{bench} ({})", subjects.join(", "))
}
})
.collect::<Vec<_>>()
.join(", ")
}
enum Outcome {
Recorded(usize),
BuildFailed,
MeasureFailed(String),
NotRecorded,
}
fn cmd_backfill_commits(o: CommitBackfill, settings: &Settings) -> Result<()> {
let cwd = std::env::current_dir()?;
let Some((path, cfg)) = Config::find(&cwd)? else {
bail!(
"no {} found in {} or any parent — --commits measures the benchmarks it declares",
config::FILE_NAME,
cwd.display()
);
};
let Some(build) = cfg.build()? else {
bail!(
"{} has no [build]. --commits checks each commit out fresh, so it has \
to be built before it can be measured:\n\n\
\x20 [build]\n\
\x20 cmd = [\"cargo\", \"build\", \"--release\"]\n\n\
A project with nothing to build can declare cmd = [\"true\"].",
path.display()
);
};
let opts = RunOpts {
bench: o.bench.clone(),
runs: o.runs.map(Runs::Fixed),
warmup: None,
no_counters: false,
allocations: false,
record: true,
no_progress: false,
groups: Vec::new(),
subjects: Vec::new(),
seed: None,
export_json: None,
profile_dir: None,
config: None,
dry_run: o.dry_run,
save_baseline: None,
baseline: None,
gate: false,
};
let Planned { plans, skipped } = plan_declared(&cfg, &path, &opts)?;
print_skipped(&skipped);
if plans.is_empty() {
bail!(
"nothing to backfill: {}",
if skipped.is_empty() {
"tak.toml declares no benchmarks"
} else {
"every selected benchmark or subject has a false `when`"
}
);
}
let config_dir = path.parent().context("tak.toml has no parent directory")?;
let top = tak_cli::worktree::toplevel(config_dir)?;
let rel = config_dir
.canonicalize()?
.strip_prefix(top.canonicalize()?)
.map(Path::to_path_buf)
.with_context(|| {
format!(
"{} is outside the repository at {}",
path.display(),
top.display()
)
})?;
if o.range.starts_with('-') || o.range.trim().is_empty() {
bail!("not a commit range: {:?} (try `main~20..main`)", o.range);
}
let _ = notes::fetch("origin");
let commits = notes::log(&o.range, None)
.with_context(|| format!("could not list the commits in {}", o.range))?;
if commits.is_empty() {
println!("no commits in {}", o.range);
return Ok(());
}
let runner = runner_class(settings);
let build_key = serde_json::to_string(&(
&runner,
&build.cmd,
build.dir.as_ref().map(|d| d.to_string_lossy()),
&build.env,
))?;
let text =
std::fs::read(&path).with_context(|| format!("could not read {}", path.display()))?;
let measure_key = format!("{build_key} {}", tak_cli::worktree::fingerprint(&text));
let mut failures = tak_cli::worktree::FailedCommits::load(build_key, measure_key)?;
let mut pending = Vec::with_capacity(commits.len());
for c in commits {
let have: std::collections::BTreeSet<(String, String)> = c
.records
.into_iter()
.filter(|r| r.runner == runner)
.map(|r| (r.bench, r.tool))
.collect();
let mut needs = needs_for(&plans, &have, o.force);
let mut measure_failed_before = Vec::new();
if !o.force {
needs.retain(|bench, _| {
let failed = failures.measure_failed(&c.sha, bench);
if failed {
measure_failed_before.push(bench.clone());
}
!failed
});
}
pending.push(Pending {
build_failed_before: !o.force && failures.build_failed(&c.sha),
measure_failed_before,
needs,
sha: c.sha,
subject: c.subject,
});
}
let recorded_before = pending
.iter()
.filter(|p| p.needs.is_empty() && p.measure_failed_before.is_empty())
.count();
let build_failed_before = pending
.iter()
.filter(|p| p.passed_over() && p.build_failed_before)
.count();
let measure_failed_before = pending
.iter()
.filter(|p| p.passed_over() && !p.build_failed_before)
.count();
let (todo, beyond): (Vec<&Pending>, Vec<&Pending>) = {
let needed: Vec<&Pending> = pending.iter().filter(|p| p.wanted()).collect();
let split = needed.len().min(o.limit);
(needed[..split].to_vec(), needed[split..].to_vec())
};
println!(
"{} commit(s) in {}, first parent only, runner {runner}",
pending.len(),
o.range
);
println!("build: {}", shell_words(&build.cmd));
if o.dry_run {
println!();
let everything = needs_for(&plans, &Default::default(), true);
for p in &pending {
let status = if p.build_failed_before && p.passed_over() {
"build failed before".to_string()
} else if p.passed_over() {
"measure failed before".to_string()
} else if p.needs.is_empty() {
"recorded".to_string()
} else if beyond.iter().any(|b| b.sha == p.sha) {
"beyond --limit".to_string()
} else if p.needs == everything {
"would build".to_string()
} else if p.measure_failed_before.is_empty() {
format!("would build ({})", describe_needs(&p.needs, &plans))
} else {
format!(
"would build ({}; {} failed before)",
describe_needs(&p.needs, &plans),
p.measure_failed_before.join(", ")
)
};
println!(" {} {status:<21} {}", &p.sha[..12], p.subject);
}
println!("\n dry run — nothing built or written");
return Ok(());
}
let scratch = backfill_workdir()?;
let hooks = scratch.path().join("hooks");
std::fs::create_dir(&hooks).context("could not create an empty hooks directory")?;
tak_cli::worktree::prune();
tak_cli::worktree::clean_up_on_interrupt(scratch.path())?;
let seed = random_seed();
let mut recorded = 0usize;
let (mut build_failed, mut measure_failed, mut not_recorded) =
(Vec::new(), Vec::new(), Vec::new());
for p in &todo {
let short = &p.sha[..12];
println!("\n{short} {}", p.subject);
let outcome = backfill_commit(
p,
&build,
&plans,
&rel,
scratch.path(),
&hooks,
seed,
&opts,
settings,
);
tak_cli::worktree::wait_if_interrupted();
match outcome? {
Outcome::Recorded(n) => {
println!(" recorded {n} measurement(s)");
recorded += 1;
let benches: Vec<String> = p.needs.keys().cloned().collect();
failures.recorded(&p.sha, &benches)?;
}
Outcome::BuildFailed => {
build_failed.push(short);
failures.add(&p.sha, tak_cli::worktree::Failure::Build)?;
}
Outcome::MeasureFailed(bench) => {
measure_failed.push(short);
failures.recorded(&p.sha, &[])?;
failures.add(&p.sha, tak_cli::worktree::Failure::Measure(bench))?;
}
Outcome::NotRecorded => not_recorded.push(short),
}
}
tak_cli::worktree::wait_if_interrupted();
println!(
"\n recorded {recorded} commit(s) → {}; {recorded_before} already recorded",
notes::NOTES_REF
);
if !build_failed.is_empty() {
println!(" build failed: {}", build_failed.join(", "));
}
if !measure_failed.is_empty() {
println!(" measurement failed: {}", measure_failed.join(", "));
}
if !not_recorded.is_empty() {
println!(" not checked out: {}", not_recorded.join(", "));
}
let failed_before = build_failed_before + measure_failed_before;
if failed_before > 0 {
println!(
" {failed_before} commit(s) passed over: they failed in an earlier run \
({build_failed_before} build, {measure_failed_before} measurement; \
--force retries them)"
);
}
if !beyond.is_empty() {
println!(
" {} more commit(s) beyond --limit {}; run again to continue",
beyond.len(),
o.limit
);
}
if recorded > 0 {
println!(" push with: tak push");
}
let failed = !(build_failed.is_empty() && measure_failed.is_empty() && not_recorded.is_empty())
|| failed_before > 0;
if recorded == 0 && recorded_before == 0 && failed {
bail!("no commit in {} was recorded", o.range);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn backfill_commit(
p: &Pending,
build: &config::Build,
plans: &[BenchPlan],
rel: &Path,
scratch: &Path,
hooks: &Path,
seed: u64,
opts: &RunOpts,
settings: &Settings,
) -> Result<Outcome> {
let wt = match tak_cli::worktree::Worktree::add(&scratch.join(&p.sha[..12]), &p.sha, hooks) {
Ok(wt) => wt,
Err(e) => {
println!(" not recorded — {e:#}");
return Ok(Outcome::NotRecorded);
}
};
let root = wt.path().join(rel);
let ts = match tak_cli::worktree::commit_time(&p.sha) {
Ok(t) => rfc3339(t),
Err(e) => {
eprintln!(" warning: {e:#}; recording the measurement time instead");
now_rfc3339()
}
};
let mut build = build.clone();
build.anchor(&root);
let contained = [Some(&root), build.dir.as_ref()]
.into_iter()
.flatten()
.try_for_each(|dir| wt.check_contains(dir))
.and_then(|()| check_program(&build.cmd, &wt));
if let Err(e) = contained {
println!(" build failed — skipped: {e:#}");
return Ok(Outcome::BuildFailed);
}
match backfill::run_build(&build, &scratch.join("build.log")) {
Ok(took) => println!(" built in {:.1}s", took.as_secs_f64()),
Err(e) => {
println!(" build failed — skipped");
for line in format!("{e:#}").lines() {
println!(" {line}");
}
return Ok(Outcome::BuildFailed);
}
}
let mut records = Vec::new();
for (name, multi, subjects) in plans {
let Some(wanted) = p.needs.get(name) else {
continue;
};
let mut subjects: Vec<Subject> = subjects
.iter()
.filter(|s| wanted.contains(&s.name))
.cloned()
.collect();
for s in &mut subjects {
s.anchor(&root);
}
let vet = |s: &Subject| check_contained(s, &wt);
let problem = match check_inputs(&subjects, &wt) {
Some(missing) => Some(missing),
None => match measure_bench_vetted(name, &subjects, *multi, seed, opts, settings, &vet)
{
Err(e) => Some(format!("{e:#}")),
Ok((_, failed)) if !failed.is_empty() => {
Some(format!("subject(s) failed: {}", failed.join(", ")))
}
Ok((measured, _)) => {
let failing = failing_checks(&measured);
let uncounted: Vec<String> = measured
.iter()
.filter(|m| m.count_failed)
.map(|m| {
if *multi {
format!("{name} ({})", m.subject.name)
} else {
name.clone()
}
})
.collect();
let broken = failed_metrics(&measured);
if !failing.is_empty() {
Some(format!("check failed: {}", labels(&failing)))
} else if !broken.is_empty() {
Some(format!(
"{} metric(s) failed: {}",
broken.len(),
broken.join(", ")
))
} else if !uncounted.is_empty() {
Some(format!(
"instruction counting failed: {}",
uncounted.join(", ")
))
} else {
records.extend(measured.into_iter().map(|m| m.record));
None
}
}
},
};
if let Some(problem) = problem {
println!(" not recorded — {name}: {problem}");
return Ok(Outcome::MeasureFailed(name.clone()));
}
}
for r in &mut records {
r.ts = ts.clone();
}
notes::append(&p.sha, &records)?;
Ok(Outcome::Recorded(records.len()))
}
fn check_inputs(subjects: &[Subject], wt: &tak_cli::worktree::Worktree) -> Option<String> {
let shown = |p: &Path| p.strip_prefix(wt.path()).unwrap_or(p).display().to_string();
for s in subjects {
if let Err(e) = check_contained(s, wt) {
return Some(format!("{e:#}"));
}
let program = Path::new(&s.cmd[0]);
if s.setup.is_some() {
continue;
}
if let Some(d) = &s.dir
&& !d.is_dir()
{
return Some(format!(
"`dir` {} does not exist at this commit (tak.toml is read from the current checkout)",
shown(d)
));
}
if program.is_absolute()
&& program.starts_with(wt.path())
&& spawned_path(program).is_none()
{
return Some(format!(
"{} does not exist at this commit after the build",
shown(program)
));
}
}
None
}
fn check_contained(s: &Subject, wt: &tak_cli::worktree::Worktree) -> Result<()> {
if let Some(d) = &s.dir
&& d.starts_with(wt.path())
&& d.exists()
{
wt.check_contains(d)?;
}
let programs = [
Some(&s.cmd),
s.setup.as_ref(),
s.prepare.as_ref(),
s.check.as_ref(),
s.version_cmd.as_ref(),
];
for argv in programs.into_iter().flatten() {
check_program(argv, wt)?;
}
for source in s.metrics.values() {
match source {
config::MetricSource::Cmd(argv) => check_program(argv, wt)?,
config::MetricSource::File(p) => {
if p.starts_with(wt.path()) && p.exists() {
wt.check_contains(p)?;
}
}
}
}
Ok(())
}
fn check_program(argv: &[String], wt: &tak_cli::worktree::Worktree) -> Result<()> {
let program = Path::new(&argv[0]);
if program.is_absolute()
&& program.starts_with(wt.path())
&& let Some(found) = spawned_path(program)
{
wt.check_contains(&found)?;
}
Ok(())
}
fn spawned_path(program: &Path) -> Option<std::path::PathBuf> {
if program.exists() {
return Some(program.to_path_buf());
}
let suffix = std::env::consts::EXE_SUFFIX;
if suffix.is_empty() || program.extension().is_some() {
return None;
}
let mut with = program.as_os_str().to_owned();
with.push(suffix);
let with = std::path::PathBuf::from(with);
with.exists().then_some(with)
}
fn tolerant_settings(cli: &CliLayer, doing: &str) -> Settings {
resolve_settings(cli).unwrap_or_else(|_| {
eprintln!("warning: could not read tak.toml; {doing} without it");
Settings::resolve(cli, &EnvLayer::from_process(), &TakConfigLayer::empty())
.unwrap_or_default()
})
}
fn resolve_settings(cli: &CliLayer) -> Result<Settings> {
Settings::from_process(cli)
}
fn render_default(value: &usage_rs::config::Const) -> String {
use usage_rs::config::{Const, Value};
match value {
Const::Str(s) => format!("{s:?}"),
Const::Bool(b) => b.to_string(),
Const::Int(i) => i.to_string(),
Const::Float(f) => Value::Float(*f).display(),
Const::List(items) => format!(
"[{}]",
items
.iter()
.map(render_default)
.collect::<Vec<_>>()
.join(", ")
),
other => other.to_value().display(),
}
}
fn cmd_settings(resolved: &Settings, docs: bool) -> Result<()> {
let scrubbed: Vec<&str> = resolved.scrubbed_env().collect();
for meta in Settings::SETTINGS_PROPS {
let Some(value) = resolved.display_value(meta.key) else {
println!(
"{} (no accessor — wire it into Settings::display_value)",
meta.key
);
continue;
};
println!("{} {}", meta.key, meta.ty.name());
println!(" value {value}");
if let Some(default) = &meta.default {
println!(" default {}", render_default(default));
}
if !meta.cli.is_empty() {
println!(" cli {}", meta.cli.join(", "));
}
if !meta.envs.is_empty() {
println!(" env {}", meta.envs.join(", "));
}
let config_keys: Vec<&str> = meta
.bindings
.iter()
.filter(|(kind, _)| *kind == config_source().name())
.map(|(_, key)| *key)
.collect();
if !config_keys.is_empty() {
println!(" tak.toml {}", config_keys.join(", "));
}
if let Some(since) = meta.since {
println!(" since {since}");
}
if docs {
println!();
if let Some(text) = meta.long_help.or(meta.help) {
for line in text.trim().lines() {
println!(" {line}");
}
}
for example in meta.examples {
println!(" $ {example}");
}
}
println!();
}
println!("removed from measured commands: {scrubbed:?}");
Ok(())
}
fn main() -> Result<()> {
let (cli, overrides) = Cli::parse_with_settings();
match cli.cmd {
Cmd::Completion { shell } => {
let shell = usage_rs::complete::Shell::from_name(&shell)
.ok_or_else(|| anyhow::anyhow!("unsupported shell: {shell}"))?;
print!("{}", Cli::completion_script(shell));
Ok(())
}
Cmd::Run {
bench,
runs,
warmup,
no_counters,
allocations,
record,
no_progress,
group,
subject,
seed,
export_json,
profile_dir,
config,
dry_run,
save_baseline,
baseline,
gate,
cmd,
} => {
let settings = Settings::from_process_at(&overrides, config.as_deref())?;
let profile_dir = profile_dir
.map(|d| {
std::path::absolute(&d)
.with_context(|| format!("could not resolve {}", d.display()))
})
.transpose()?;
cmd_run(
RunOpts {
bench,
runs: runs.as_deref().map(str::parse).transpose()?,
warmup,
no_counters,
allocations,
record,
no_progress,
groups: group,
subjects: subject,
seed,
export_json,
profile_dir,
config,
dry_run,
save_baseline,
baseline,
gate,
},
cmd,
&settings,
)
}
Cmd::History { rev, remote } => cmd_history(rev, remote),
Cmd::Log {
rev,
limit,
bench,
html,
remote,
} => cmd_log(
LogOpts {
rev,
limit,
bench,
html,
remote,
},
&tolerant_settings(&overrides, "reading history"),
),
Cmd::Push(RemoteArgs { remote }) => {
notes::push(&remote)?;
println!("pushed {} to {}", notes::NOTES_REF, remote);
Ok(())
}
Cmd::Artifact(args) => match args.cmd {
ArtifactCmd::Export { output, rev } => {
let (sha, records) = tak_cli::artifact::export(&output, &rev)?;
println!(
"exported {records} measurement(s) for {} to {}",
&sha[..12],
output.display()
);
Ok(())
}
ArtifactCmd::Publish {
path,
expect,
remote,
} => {
let (sha, records) = tak_cli::artifact::publish(&path, &expect, &remote)?;
println!(
"published {records} measurement(s) for {} to {remote}",
&sha[..12]
);
Ok(())
}
},
Cmd::Init(RemoteArgs { remote }) => {
notes::install_refspec(&remote)?;
println!(
"added {} to remote.{}.fetch — plain `git fetch` now picks up measurements",
notes::NOTES_REF,
remote
);
Ok(())
}
Cmd::Backfill {
commits,
force,
repo,
bin,
args,
bench,
limit,
runs,
dry_run,
} => {
let settings = resolve_settings(&overrides)?;
match commits {
Some(range) => {
if repo.is_some() || bin.is_some() || !args.is_empty() {
bail!(
"--repo, --bin and arguments after `--` select release binaries; \
--commits measures the benchmarks tak.toml declares"
);
}
cmd_backfill_commits(
CommitBackfill {
range,
bench,
limit,
runs,
force,
dry_run,
},
&settings,
)
}
None => {
if force {
bail!("--force only applies with --commits");
}
cmd_backfill(
repo,
bin,
args,
bench.unwrap_or_else(|| "release".to_string()),
limit,
runs.unwrap_or(10),
dry_run,
&settings,
)
}
}
}
Cmd::Compare {
base,
rev,
remote,
no_gate,
accept,
} => cmd_compare(
base,
rev,
remote,
no_gate,
accept,
&overrides,
&resolve_settings(&overrides)?,
),
Cmd::Explain { base, head, top } => cmd_explain(&base, &head, top),
Cmd::Detect {
rev,
window,
remote,
no_gate,
accept,
} => cmd_detect(
rev,
window,
remote,
no_gate,
accept,
&resolve_settings(&overrides)?,
),
Cmd::Doctor => cmd_doctor(&tolerant_settings(&overrides, "showing settings")),
Cmd::Settings { docs } => cmd_settings(&resolve_settings(&overrides)?, docs),
Cmd::Usage => {
print!("{}", Cli::spec().view().omit_version().to_kdl());
print!("{}", Settings::spec_kdl());
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_flags_this_cli_reads_are_the_flags_its_settings_declare() {
assert_eq!(
Settings::SETTINGS_REGISTRY.drift(Cli::SETTINGS_BINDINGS),
Vec::<String>::new()
);
}
#[test]
fn timestamp_is_rfc3339_shaped() {
let ts = now_rfc3339();
assert_eq!(ts.len(), 20, "{ts}");
assert!(ts.ends_with('Z'));
assert_eq!(&ts[4..5], "-");
assert_eq!(&ts[10..11], "T");
}
#[test]
fn timestamps_before_the_epoch_are_formatted() {
assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z");
assert_eq!(rfc3339(-1), "1969-12-31T23:59:59Z");
assert_eq!(rfc3339(-86_400 * 365), "1969-01-01T00:00:00Z");
assert_eq!(rfc3339(1_700_000_000), "2023-11-14T22:13:20Z");
}
#[cfg(unix)]
#[test]
fn the_backfill_workdir_is_owner_only() {
use std::os::unix::fs::PermissionsExt;
let workdir = backfill_workdir().unwrap();
let mode = workdir.path().metadata().unwrap().permissions().mode();
assert_eq!(mode & 0o077, 0, "workdir mode was {:o}", mode & 0o777);
}
#[test]
fn a_built_program_is_found_with_the_platform_suffix() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("mycli");
assert_eq!(spawned_path(&bin), None);
let file = format!("{}{}", bin.display(), std::env::consts::EXE_SUFFIX);
std::fs::write(&file, b"").unwrap();
assert_eq!(spawned_path(&bin), Some(std::path::PathBuf::from(file)));
}
#[test]
fn an_explicit_runner_class_wins() {
let s = Settings {
runner_class: "gha-linux-x64-rust1.85".into(),
..Settings::default()
};
assert_eq!(runner_class(&s), "gha-linux-x64-rust1.85");
}
#[test]
fn a_blank_class_falls_back_to_the_derived_name() {
for blank in ["", " "] {
let s = Settings {
runner_class: blank.into(),
..Settings::default()
};
let got = runner_class(&s);
assert!(!got.trim().is_empty(), "{blank:?} produced {got:?}");
assert!(got.contains('-'), "expected a derived name, got {got:?}");
}
}
}