perfgate 0.17.0

Core library for perfgate performance budgets and baseline diffs
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! Profiler trait and concrete implementations for flamegraph capture.

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Instant;

/// Errors that can occur during profiling.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ProfileError {
    #[error("profiler command failed: {command}: {reason}")]
    CommandFailed { command: String, reason: String },

    #[error("failed to create output directory {path}: {reason}")]
    CreateDir { path: String, reason: String },

    #[error("failed to write flamegraph SVG to {path}: {reason}")]
    WriteSvg { path: String, reason: String },

    #[error("profiler produced no output")]
    NoOutput,
}

/// Request to capture a flamegraph.
#[derive(Debug, Clone)]
pub struct ProfileRequest {
    /// The command to profile (argv).
    pub command: Vec<String>,

    /// Directory where the flamegraph SVG should be written.
    pub output_dir: PathBuf,

    /// Label for the flamegraph file (used in the filename).
    pub label: String,

    /// Optional working directory for the profiled command.
    pub cwd: Option<PathBuf>,

    /// Environment variables for the profiled command.
    pub env: Vec<(String, String)>,
}

/// Result of a successful flamegraph capture.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileResult {
    /// Path to the generated flamegraph SVG file.
    pub svg_path: PathBuf,

    /// Which profiler was used.
    pub profiler_used: String,

    /// How long the profiling took in milliseconds.
    pub duration_ms: u64,
}

/// Trait for profiler implementations.
pub trait Profiler {
    /// Capture a flamegraph for the given command.
    fn capture(&self, request: &ProfileRequest) -> Result<ProfileResult, ProfileError>;
}

/// Ensure the output directory exists.
fn ensure_output_dir(dir: &Path) -> Result<(), ProfileError> {
    std::fs::create_dir_all(dir).map_err(|e| ProfileError::CreateDir {
        path: dir.display().to_string(),
        reason: e.to_string(),
    })
}

/// Build the SVG output path from the request.
fn svg_output_path(request: &ProfileRequest) -> PathBuf {
    let sanitized_label = request
        .label
        .replace(|c: char| !c.is_alphanumeric() && c != '-' && c != '_', "_");
    request
        .output_dir
        .join(format!("flamegraph-{sanitized_label}.svg"))
}

/// Linux `perf record` + `inferno-flamegraph` profiler.
pub struct PerfProfiler;

impl Profiler for PerfProfiler {
    fn capture(&self, request: &ProfileRequest) -> Result<ProfileResult, ProfileError> {
        ensure_output_dir(&request.output_dir)?;
        let svg_path = svg_output_path(request);
        let start = Instant::now();

        // Step 1: perf record
        let perf_data = request.output_dir.join("perf.data");
        let mut perf_cmd = Command::new("perf");
        perf_cmd.args([
            "record",
            "-g",
            "--call-graph",
            "dwarf",
            "-o",
            &perf_data.display().to_string(),
            "--",
        ]);
        perf_cmd.args(&request.command);

        if let Some(cwd) = &request.cwd {
            perf_cmd.current_dir(cwd);
        }
        for (k, v) in &request.env {
            perf_cmd.env(k, v);
        }

        let perf_output = perf_cmd.output().map_err(|e| ProfileError::CommandFailed {
            command: "perf record".to_string(),
            reason: e.to_string(),
        })?;

        if !perf_output.status.success() {
            return Err(ProfileError::CommandFailed {
                command: "perf record".to_string(),
                reason: String::from_utf8_lossy(&perf_output.stderr).to_string(),
            });
        }

        // Step 2: perf script | inferno-collapse-perf | inferno-flamegraph > svg
        let perf_script = Command::new("perf")
            .args(["script", "-i", &perf_data.display().to_string()])
            .output()
            .map_err(|e| ProfileError::CommandFailed {
                command: "perf script".to_string(),
                reason: e.to_string(),
            })?;

        if !perf_script.status.success() {
            return Err(ProfileError::CommandFailed {
                command: "perf script".to_string(),
                reason: String::from_utf8_lossy(&perf_script.stderr).to_string(),
            });
        }

        let mut collapse = Command::new("inferno-collapse-perf")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| ProfileError::CommandFailed {
                command: "inferno-collapse-perf".to_string(),
                reason: e.to_string(),
            })?;

        // Write perf script output to collapse stdin, then drop to close pipe
        use std::io::Write;
        if let Some(ref mut stdin) = collapse.stdin {
            stdin
                .write_all(&perf_script.stdout)
                .map_err(|e| ProfileError::CommandFailed {
                    command: "inferno-collapse-perf (write stdin)".to_string(),
                    reason: e.to_string(),
                })?;
        }
        collapse.stdin.take(); // close stdin so child sees EOF

        let collapse_output =
            collapse
                .wait_with_output()
                .map_err(|e| ProfileError::CommandFailed {
                    command: "inferno-collapse-perf".to_string(),
                    reason: e.to_string(),
                })?;

        if !collapse_output.status.success() {
            return Err(ProfileError::CommandFailed {
                command: "inferno-collapse-perf".to_string(),
                reason: String::from_utf8_lossy(&collapse_output.stderr).to_string(),
            });
        }

        let mut flamegraph = Command::new("inferno-flamegraph")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| ProfileError::CommandFailed {
                command: "inferno-flamegraph".to_string(),
                reason: e.to_string(),
            })?;

        if let Some(ref mut stdin) = flamegraph.stdin {
            stdin
                .write_all(&collapse_output.stdout)
                .map_err(|e| ProfileError::CommandFailed {
                    command: "inferno-flamegraph (write stdin)".to_string(),
                    reason: e.to_string(),
                })?;
        }
        flamegraph.stdin.take(); // close stdin so child sees EOF

        let flamegraph_output =
            flamegraph
                .wait_with_output()
                .map_err(|e| ProfileError::CommandFailed {
                    command: "inferno-flamegraph".to_string(),
                    reason: e.to_string(),
                })?;

        if !flamegraph_output.status.success() {
            return Err(ProfileError::CommandFailed {
                command: "inferno-flamegraph".to_string(),
                reason: String::from_utf8_lossy(&flamegraph_output.stderr).to_string(),
            });
        }

        if flamegraph_output.stdout.is_empty() {
            return Err(ProfileError::NoOutput);
        }

        std::fs::write(&svg_path, &flamegraph_output.stdout).map_err(|e| {
            ProfileError::WriteSvg {
                path: svg_path.display().to_string(),
                reason: e.to_string(),
            }
        })?;

        // Clean up perf.data
        let _ = std::fs::remove_file(&perf_data);

        let duration_ms = start.elapsed().as_millis() as u64;

        Ok(ProfileResult {
            svg_path,
            profiler_used: "perf + inferno".to_string(),
            duration_ms,
        })
    }
}

/// macOS `dtrace` + `inferno-flamegraph` profiler.
pub struct DtraceProfiler;

impl Profiler for DtraceProfiler {
    fn capture(&self, request: &ProfileRequest) -> Result<ProfileResult, ProfileError> {
        ensure_output_dir(&request.output_dir)?;
        let svg_path = svg_output_path(request);
        let start = Instant::now();

        let stacks_path = request.output_dir.join("dtrace-stacks.txt");

        // Build the dtrace probe script: profile user-space stacks at 997 Hz
        let command_str = request.command.join(" ");
        let dtrace_script = format!(
            "profile-997 /execname == \"{}\"/ {{ @[ustack(100)] = count(); }}",
            request
                .command
                .first()
                .map(|s| s.as_str())
                .unwrap_or("unknown")
        );

        // Run the command in background, capture its PID, then dtrace
        // Alternative: use dtrace -c to run the command directly
        let mut dtrace_cmd = Command::new("dtrace");
        dtrace_cmd.args([
            "-x",
            "ustackframes=100",
            "-n",
            &dtrace_script,
            "-c",
            &command_str,
            "-o",
            &stacks_path.display().to_string(),
        ]);

        if let Some(cwd) = &request.cwd {
            dtrace_cmd.current_dir(cwd);
        }
        for (k, v) in &request.env {
            dtrace_cmd.env(k, v);
        }

        let dtrace_output = dtrace_cmd
            .output()
            .map_err(|e| ProfileError::CommandFailed {
                command: "dtrace".to_string(),
                reason: e.to_string(),
            })?;

        if !dtrace_output.status.success() {
            return Err(ProfileError::CommandFailed {
                command: "dtrace".to_string(),
                reason: String::from_utf8_lossy(&dtrace_output.stderr).to_string(),
            });
        }

        // Collapse dtrace stacks using inferno-collapse-dtrace
        let stacks_data = std::fs::read(&stacks_path).map_err(|e| ProfileError::CommandFailed {
            command: "read dtrace stacks".to_string(),
            reason: e.to_string(),
        })?;

        let mut collapse = Command::new("inferno-collapse-dtrace")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| ProfileError::CommandFailed {
                command: "inferno-collapse-dtrace".to_string(),
                reason: e.to_string(),
            })?;

        use std::io::Write;
        if let Some(ref mut stdin) = collapse.stdin {
            stdin
                .write_all(&stacks_data)
                .map_err(|e| ProfileError::CommandFailed {
                    command: "inferno-collapse-dtrace (write stdin)".to_string(),
                    reason: e.to_string(),
                })?;
        }
        collapse.stdin.take(); // close stdin so child sees EOF

        let collapse_output =
            collapse
                .wait_with_output()
                .map_err(|e| ProfileError::CommandFailed {
                    command: "inferno-collapse-dtrace".to_string(),
                    reason: e.to_string(),
                })?;

        if !collapse_output.status.success() {
            return Err(ProfileError::CommandFailed {
                command: "inferno-collapse-dtrace".to_string(),
                reason: String::from_utf8_lossy(&collapse_output.stderr).to_string(),
            });
        }

        let mut flamegraph = Command::new("inferno-flamegraph")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| ProfileError::CommandFailed {
                command: "inferno-flamegraph".to_string(),
                reason: e.to_string(),
            })?;

        if let Some(ref mut stdin) = flamegraph.stdin {
            stdin
                .write_all(&collapse_output.stdout)
                .map_err(|e| ProfileError::CommandFailed {
                    command: "inferno-flamegraph (write stdin)".to_string(),
                    reason: e.to_string(),
                })?;
        }
        flamegraph.stdin.take(); // close stdin so child sees EOF

        let flamegraph_output =
            flamegraph
                .wait_with_output()
                .map_err(|e| ProfileError::CommandFailed {
                    command: "inferno-flamegraph".to_string(),
                    reason: e.to_string(),
                })?;

        if !flamegraph_output.status.success() {
            return Err(ProfileError::CommandFailed {
                command: "inferno-flamegraph".to_string(),
                reason: String::from_utf8_lossy(&flamegraph_output.stderr).to_string(),
            });
        }

        if flamegraph_output.stdout.is_empty() {
            return Err(ProfileError::NoOutput);
        }

        std::fs::write(&svg_path, &flamegraph_output.stdout).map_err(|e| {
            ProfileError::WriteSvg {
                path: svg_path.display().to_string(),
                reason: e.to_string(),
            }
        })?;

        // Clean up intermediate files
        let _ = std::fs::remove_file(&stacks_path);

        let duration_ms = start.elapsed().as_millis() as u64;

        Ok(ProfileResult {
            svg_path,
            profiler_used: "dtrace + inferno".to_string(),
            duration_ms,
        })
    }
}

/// Cross-platform `cargo flamegraph` profiler.
pub struct CargoFlamegraphProfiler;

impl Profiler for CargoFlamegraphProfiler {
    fn capture(&self, request: &ProfileRequest) -> Result<ProfileResult, ProfileError> {
        ensure_output_dir(&request.output_dir)?;
        let svg_path = svg_output_path(request);
        let start = Instant::now();

        let mut cmd = Command::new("cargo");
        cmd.args([
            "flamegraph",
            "--output",
            &svg_path.display().to_string(),
            "--",
        ]);
        cmd.args(&request.command);

        if let Some(cwd) = &request.cwd {
            cmd.current_dir(cwd);
        }
        for (k, v) in &request.env {
            cmd.env(k, v);
        }

        let output = cmd.output().map_err(|e| ProfileError::CommandFailed {
            command: "cargo flamegraph".to_string(),
            reason: e.to_string(),
        })?;

        if !output.status.success() {
            return Err(ProfileError::CommandFailed {
                command: "cargo flamegraph".to_string(),
                reason: String::from_utf8_lossy(&output.stderr).to_string(),
            });
        }

        if !svg_path.exists() {
            return Err(ProfileError::NoOutput);
        }

        let duration_ms = start.elapsed().as_millis() as u64;

        Ok(ProfileResult {
            svg_path,
            profiler_used: "cargo-flamegraph".to_string(),
            duration_ms,
        })
    }
}

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

    #[test]
    fn svg_output_path_sanitizes_label() {
        let request = ProfileRequest {
            command: vec!["echo".to_string()],
            output_dir: PathBuf::from("/tmp/profiles"),
            label: "my bench/test:1".to_string(),
            cwd: None,
            env: Vec::new(),
        };
        let path = svg_output_path(&request);
        let filename = path.file_name().unwrap().to_str().unwrap();
        assert_eq!(filename, "flamegraph-my_bench_test_1.svg");
    }

    #[test]
    fn svg_output_path_preserves_valid_chars() {
        let request = ProfileRequest {
            command: vec!["echo".to_string()],
            output_dir: PathBuf::from("/tmp/profiles"),
            label: "bench-name_v2".to_string(),
            cwd: None,
            env: Vec::new(),
        };
        let path = svg_output_path(&request);
        let filename = path.file_name().unwrap().to_str().unwrap();
        assert_eq!(filename, "flamegraph-bench-name_v2.svg");
    }

    #[test]
    fn profile_error_display() {
        let err = ProfileError::CommandFailed {
            command: "perf record".to_string(),
            reason: "not found".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "profiler command failed: perf record: not found"
        );

        let err = ProfileError::NoOutput;
        assert_eq!(err.to_string(), "profiler produced no output");
    }

    #[test]
    fn profile_result_serialization_roundtrip() {
        let result = ProfileResult {
            svg_path: PathBuf::from("/tmp/profiles/flamegraph-bench.svg"),
            profiler_used: "perf + inferno".to_string(),
            duration_ms: 1234,
        };

        let json = serde_json::to_string(&result).unwrap();
        let deserialized: ProfileResult = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.profiler_used, "perf + inferno");
        assert_eq!(deserialized.duration_ms, 1234);
    }

    #[test]
    fn ensure_output_dir_creates_nested_dirs() {
        let tmp = tempfile::tempdir().unwrap();
        let nested = tmp.path().join("a").join("b").join("c");
        assert!(!nested.exists());
        ensure_output_dir(&nested).unwrap();
        assert!(nested.exists());
    }

    #[test]
    fn ensure_output_dir_succeeds_if_exists() {
        let tmp = tempfile::tempdir().unwrap();
        ensure_output_dir(tmp.path()).unwrap();
    }
}