wasm-slim 0.1.1

WASM bundle size optimizer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Benchmark tracking tool for wasm-slim
//!
//! This tool runs criterion benchmarks and tracks performance over time,
//! detecting regressions and managing baselines.

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use std::path::{Path, PathBuf};
use std::process::Command;
use wasm_slim::bench_tracker::{BenchmarkTracker, PerformanceBudget};

#[derive(Parser)]
#[command(name = "bench-tracker")]
#[command(about = "Performance tracking tool for wasm-slim benchmarks")]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Commands,

    /// Path to project root directory (defaults to current directory)
    ///
    /// This should be the directory containing Cargo.toml, not the file itself.
    /// Symlinks are resolved to their target paths.
    #[arg(short, long, default_value = ".")]
    project_root: PathBuf,
}

#[derive(Subcommand)]
enum Commands {
    /// Run benchmarks and compare with baseline
    Run {
        /// Maximum allowed regression percentage (default: 10%)
        #[arg(long, default_value = "10.0")]
        max_regression: f64,

        /// Fail if regressions are detected
        #[arg(long)]
        fail_on_regression: bool,

        /// Specific benchmark to run (runs all if not specified)
        #[arg(short, long)]
        bench: Option<String>,
    },

    /// Save current benchmark results as baseline
    Baseline {
        /// Version/tag for this baseline
        #[arg(short, long, default_value = "current")]
        version: String,
    },

    /// Show comparison with baseline without running benchmarks
    Compare {
        /// Maximum allowed regression percentage (default: 10%)
        #[arg(long, default_value = "10.0")]
        max_regression: f64,

        /// Fail if regressions are detected
        #[arg(long)]
        fail_on_regression: bool,
    },

    /// Show current baseline information
    Show,

    /// Reset/delete current baseline
    Reset,
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    let project_root = cli
        .project_root
        .canonicalize()
        .context("Failed to resolve project root path")?;

    // Validate that project_root is a directory
    if !project_root.is_dir() {
        anyhow::bail!(
            "Project root must be a directory, got: {}",
            project_root.display()
        );
    }

    match cli.command {
        Commands::Run {
            max_regression,
            fail_on_regression,
            bench,
        } => {
            run_benchmarks(&project_root, max_regression, fail_on_regression, bench)?;
        }
        Commands::Baseline { version } => {
            save_baseline(&project_root, version)?;
        }
        Commands::Compare {
            max_regression,
            fail_on_regression,
        } => {
            compare_with_baseline(&project_root, max_regression, fail_on_regression)?;
        }
        Commands::Show => {
            show_baseline(&project_root)?;
        }
        Commands::Reset => {
            reset_baseline(&project_root)?;
        }
    }

    Ok(())
}

/// Run benchmarks and compare with baseline
fn run_benchmarks(
    project_root: &Path,
    max_regression: f64,
    fail_on_regression: bool,
    bench_name: Option<String>,
) -> Result<()> {
    println!("🔧 Running benchmarks...");

    // Build the cargo bench command
    let mut cmd = Command::new("cargo");
    cmd.arg("bench")
        .arg("--message-format=json")
        .current_dir(project_root);

    if let Some(name) = bench_name {
        cmd.arg("--bench").arg(name);
    }

    // Run benchmarks
    let output = cmd.output().context("Failed to run cargo bench")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eprintln!("Benchmark execution failed:\n{}", stderr);
        anyhow::bail!("Benchmark execution failed");
    }

    println!("✓ Benchmarks completed");

    // Parse results and compare
    let criterion_dir = project_root.join("target").join("criterion");
    if !criterion_dir.exists() {
        println!("⚠️  No criterion results found. Make sure benchmarks use criterion.");
        return Ok(());
    }

    let budget = PerformanceBudget {
        max_regression_percent: max_regression,
        max_time_ns: None,
        fail_on_violation: fail_on_regression,
    };

    let tracker = BenchmarkTracker::with_budget(project_root, budget);
    let current_results = tracker.parse_criterion_results(&criterion_dir)?;

    if current_results.is_empty() {
        println!("⚠️  No benchmark results parsed. Check criterion output.");
        return Ok(());
    }

    println!("✓ Parsed {} benchmark results", current_results.len());

    // Compare with baseline if it exists
    if let Some(baseline) = tracker.load_baseline()? {
        let comparisons = tracker.compare_with_baseline(&current_results, &baseline);
        tracker.print_comparison(&comparisons);

        if tracker.has_regressions(&comparisons) {
            println!("\n⚠️  Performance regressions detected!");
            if fail_on_regression {
                anyhow::bail!("Performance regressions exceed threshold");
            }
        } else {
            println!("\n✓ No significant performance regressions");
        }
    } else {
        println!("\n📝 No baseline found. Run 'bench-tracker baseline' to save current results.");
    }

    Ok(())
}

/// Save current benchmark results as baseline
fn save_baseline(project_root: &Path, version: String) -> Result<()> {
    println!("💾 Saving baseline...");

    let criterion_dir = project_root.join("target").join("criterion");
    if !criterion_dir.exists() {
        anyhow::bail!(
            "No criterion results found. Run benchmarks first with 'cargo bench' or 'bench-tracker run'"
        );
    }

    let tracker = BenchmarkTracker::new(project_root);
    let results = tracker.parse_criterion_results(&criterion_dir)?;

    if results.is_empty() {
        anyhow::bail!("No benchmark results found to save");
    }

    let baseline = tracker.create_baseline(results, version)?;
    tracker.save_baseline(baseline)?;

    println!("✓ Baseline saved successfully");
    Ok(())
}

/// Compare with baseline without running benchmarks
fn compare_with_baseline(
    project_root: &Path,
    max_regression: f64,
    fail_on_regression: bool,
) -> Result<()> {
    let criterion_dir = project_root.join("target").join("criterion");
    if !criterion_dir.exists() {
        anyhow::bail!("No criterion results found. Run benchmarks first.");
    }

    let budget = PerformanceBudget {
        max_regression_percent: max_regression,
        max_time_ns: None,
        fail_on_violation: fail_on_regression,
    };

    let tracker = BenchmarkTracker::with_budget(project_root, budget);
    let current_results = tracker.parse_criterion_results(&criterion_dir)?;

    if let Some(baseline) = tracker.load_baseline()? {
        let comparisons = tracker.compare_with_baseline(&current_results, &baseline);
        tracker.print_comparison(&comparisons);

        if tracker.has_regressions(&comparisons) {
            println!("\n⚠️  Performance regressions detected!");
            if fail_on_regression {
                anyhow::bail!("Performance regressions exceed threshold");
            }
        } else {
            println!("\n✓ No significant performance regressions");
        }
    } else {
        println!("❌ No baseline found. Run 'bench-tracker baseline' first.");
    }

    Ok(())
}

/// Show current baseline information
fn show_baseline(project_root: &Path) -> Result<()> {
    let tracker = BenchmarkTracker::new(project_root);

    if let Some(baseline) = tracker.load_baseline()? {
        println!("📊 Current Baseline");
        println!("Version: {}", baseline.version);
        println!("Timestamp: {}", format_timestamp(baseline.timestamp));
        if let Some(commit) = &baseline.git_commit {
            println!("Git commit: {}", commit);
        }
        println!("\nBenchmarks ({}):", baseline.results.len());

        for (name, result) in &baseline.results {
            println!(
                "{} - {}{})",
                name,
                format_ns(result.mean_ns),
                format_ns(result.stddev_ns)
            );
        }
    } else {
        println!("❌ No baseline found.");
    }

    Ok(())
}

/// Reset/delete current baseline
fn reset_baseline(project_root: &Path) -> Result<()> {
    let baseline_path = project_root
        .join(".wasm-slim")
        .join("benchmarks")
        .join("baseline.json");

    if baseline_path.exists() {
        std::fs::remove_file(&baseline_path).context("Failed to remove baseline file")?;
        println!("✓ Baseline reset successfully");
    } else {
        println!("ℹ️  No baseline to reset");
    }

    Ok(())
}

/// Format timestamp as human-readable date
fn format_timestamp(timestamp: u64) -> String {
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    let time = UNIX_EPOCH + Duration::from_secs(timestamp);
    match time.duration_since(SystemTime::now()) {
        Ok(_) => "future".to_string(),
        Err(elapsed) => {
            let elapsed = elapsed.duration();
            if elapsed.as_secs() < 60 {
                "just now".to_string()
            } else if elapsed.as_secs() < 3600 {
                format!("{} minutes ago", elapsed.as_secs() / 60)
            } else if elapsed.as_secs() < 86400 {
                format!("{} hours ago", elapsed.as_secs() / 3600)
            } else {
                format!("{} days ago", elapsed.as_secs() / 86400)
            }
        }
    }
}

/// Format nanoseconds as human-readable time
fn format_ns(ns: u64) -> String {
    if ns < 1_000 {
        format!("{} ns", ns)
    } else if ns < 1_000_000 {
        format!("{:.2} µs", ns as f64 / 1_000.0)
    } else if ns < 1_000_000_000 {
        format!("{:.2} ms", ns as f64 / 1_000_000.0)
    } else {
        format!("{:.2} s", ns as f64 / 1_000_000_000.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::SystemTime;

    #[test]
    fn test_format_timestamp_future() {
        // Far future timestamp
        let future = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 86400; // 1 day in future
        assert_eq!(format_timestamp(future), "future");
    }

    #[test]
    fn test_format_timestamp_just_now() {
        let now = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let result = format_timestamp(now);
        assert_eq!(result, "just now");
    }

    #[test]
    fn test_format_timestamp_minutes() {
        let two_minutes_ago = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 120;
        let result = format_timestamp(two_minutes_ago);
        assert!(result.contains("minutes ago"));
    }

    #[test]
    fn test_format_timestamp_hours() {
        let two_hours_ago = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 7200;
        let result = format_timestamp(two_hours_ago);
        assert!(result.contains("hours ago"));
    }

    #[test]
    fn test_format_timestamp_days() {
        let two_days_ago = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            - 172800;
        let result = format_timestamp(two_days_ago);
        assert!(result.contains("days ago"));
    }

    #[test]
    fn test_format_ns_nanoseconds() {
        assert_eq!(format_ns(500), "500 ns");
        assert_eq!(format_ns(999), "999 ns");
    }

    #[test]
    fn test_format_ns_microseconds() {
        assert_eq!(format_ns(1_000), "1.00 µs");
        assert_eq!(format_ns(1_500), "1.50 µs");
        assert_eq!(format_ns(999_999), "1000.00 µs");
    }

    #[test]
    fn test_format_ns_milliseconds() {
        assert_eq!(format_ns(1_000_000), "1.00 ms");
        assert_eq!(format_ns(1_500_000), "1.50 ms");
        assert_eq!(format_ns(999_999_999), "1000.00 ms");
    }

    #[test]
    fn test_format_ns_seconds() {
        assert_eq!(format_ns(1_000_000_000), "1.00 s");
        assert_eq!(format_ns(2_500_000_000), "2.50 s");
    }

    #[test]
    fn test_format_ns_boundary_values() {
        assert_eq!(format_ns(0), "0 ns");
        assert_eq!(format_ns(1), "1 ns");
    }
}