alloc_tracker 0.7.0

Memory allocation tracking utilities for benchmarks and performance analysis
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
//! Machine-readable JSON output of memory allocation statistics.

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use serde::Serialize;

use crate::Report;

/// Subdirectory of the Cargo target directory that receives the JSON files.
const OUTPUT_SUBDIRECTORY: &str = "alloc_tracker";

/// Machine-readable allocation statistics for a single operation.
///
/// Carries the per-iteration slope with its confidence interval for each metric,
/// mirroring the shape `all_the_time` writes for processor time. Interval fields
/// are omitted when the interval cannot be estimated.
#[derive(Serialize)]
struct OperationOutput<'a> {
    operation: &'a str,
    total_iterations: u64,
    total_bytes_allocated: u64,
    total_allocations_count: u64,
    span_count: u64,
    slope_bytes_per_iteration: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    interval_low_bytes_per_iteration: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    interval_high_bytes_per_iteration: Option<f64>,
    slope_allocations_per_iteration: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    interval_low_allocations_per_iteration: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    interval_high_allocations_per_iteration: Option<f64>,
}

impl Report {
    /// Writes machine-readable JSON statistics into the Cargo target directory.
    ///
    /// One file is written per operation, named after the operation, at
    /// `<target>/alloc_tracker/<operation>.json`. Operation names are sanitized
    /// to be filesystem-safe and existing files are overwritten.
    ///
    /// The target directory is resolved the same way as Criterion (honoring
    /// `CARGO_TARGET_DIR`), falling back to a relative `target` directory.
    ///
    /// Writes nothing if no operations were captured. This may indicate that the
    /// session was part of a "list available benchmarks" probe run instead of
    /// some real activity.
    ///
    /// # Panics
    ///
    /// Panics if the output directory cannot be created or a file cannot be
    /// written. Benchmark results are not useful without the output files they
    /// produce, so a write failure is treated as fatal rather than recoverable.
    ///
    /// Also panics if two operation names sanitize to the same file name, since
    /// writing both would silently discard one operation's results.
    pub(crate) fn write_to_target(&self) {
        let target =
            folo_utils::cargo_target_directory().unwrap_or_else(|| PathBuf::from("target"));
        self.write_to_directory(target.join(OUTPUT_SUBDIRECTORY));
    }

    /// Writes machine-readable JSON statistics into the given directory.
    ///
    /// One file is written per operation, named after the operation, as
    /// `<directory>/<operation>.json`. Operation names are sanitized to be
    /// filesystem-safe and existing files are overwritten. The directory is
    /// created if it does not exist.
    ///
    /// Writes nothing if no operations were captured.
    ///
    /// # Panics
    ///
    /// Panics if the output directory cannot be created or a file cannot be
    /// written. Benchmark results are not useful without the output files they
    /// produce, so a write failure is treated as fatal rather than recoverable.
    ///
    /// Also panics if two operation names sanitize to the same file name, since
    /// writing both would silently discard one operation's results.
    pub fn write_to_directory(&self, directory: impl AsRef<Path>) {
        let directory = directory.as_ref();

        // Build every output up front, detecting sanitized-name collisions before
        // touching the filesystem. Two operation names that sanitize to the same
        // file name would otherwise silently overwrite each other's results.
        let mut file_names: HashMap<String, &str> = HashMap::new();
        let mut outputs: Vec<(PathBuf, String)> = Vec::new();
        for (name, operation) in self.sorted_operations() {
            let Some(statistics) = operation.statistics() else {
                // Registered but never measured operations have no spans and thus
                // no statistics, so they leave no output file behind.
                continue;
            };

            let file_name = format!("{}.json", folo_utils::sanitize_file_name(name));
            if let Some(previous) = file_names.insert(file_name.clone(), name) {
                panic!(
                    "operations {previous:?} and {name:?} both map to the output file name \
                     {file_name:?} after sanitization; rename one of them to avoid silently \
                     overwriting benchmark results"
                );
            }

            let output = OperationOutput {
                operation: name,
                total_iterations: operation.total_iterations(),
                total_bytes_allocated: operation.total_bytes_allocated(),
                total_allocations_count: operation.total_allocations_count(),
                span_count: statistics.span_count,
                slope_bytes_per_iteration: statistics.bytes.slope,
                interval_low_bytes_per_iteration: statistics.bytes.interval.map(|(low, _)| low),
                interval_high_bytes_per_iteration: statistics.bytes.interval.map(|(_, high)| high),
                slope_allocations_per_iteration: statistics.allocations.slope,
                interval_low_allocations_per_iteration: statistics
                    .allocations
                    .interval
                    .map(|(low, _)| low),
                interval_high_allocations_per_iteration: statistics
                    .allocations
                    .interval
                    .map(|(_, high)| high),
            };

            let json = serde_json::to_string_pretty(&output)
                .expect("serializing fixed primitive fields to JSON cannot fail");

            outputs.push((directory.join(file_name), json));
        }

        // Without any output, no directory is created, so a probe run that captured
        // no measurable work leaves nothing behind.
        if outputs.is_empty() {
            return;
        }

        fs::create_dir_all(directory).unwrap_or_else(|error| {
            panic!(
                "failed to create benchmark output directory {}: {error}",
                directory.display()
            )
        });

        for (path, json) in outputs {
            fs::write(&path, json).unwrap_or_else(|error| {
                panic!(
                    "failed to write benchmark output file {}: {error}",
                    path.display()
                )
            });
        }
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use std::fs;
    use std::path::Path;

    use serde_json::Value;

    use crate::Session;
    use crate::allocator::register_fake_allocation;

    fn read_json(path: &Path) -> Value {
        serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap()
    }

    fn session_with_recorded_work(name: &str) -> Session {
        let session = Session::new().no_stdout().no_file();
        {
            let operation = session.operation(name);
            let _span = operation.measure_thread().iterations(4);
            register_fake_allocation(800, 8);
        }
        session
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Writes files, which is not supported under Miri isolation.
    fn writes_operation_statistics_as_json() {
        let session = session_with_recorded_work("allocate_vec");
        let directory = tempfile::tempdir().unwrap();

        session.to_report().write_to_directory(directory.path());

        let file = directory.path().join("allocate_vec.json");
        let value = read_json(&file);

        assert_eq!(
            value.get("operation").and_then(Value::as_str),
            Some("allocate_vec")
        );
        assert_eq!(
            value.get("total_iterations").and_then(Value::as_u64),
            Some(4)
        );
        assert_eq!(
            value.get("total_bytes_allocated").and_then(Value::as_u64),
            Some(800)
        );
        assert_eq!(
            value.get("total_allocations_count").and_then(Value::as_u64),
            Some(8)
        );
        // A single recorded span yields a span count of one and per-metric slopes
        // equal to the per-iteration means, but no interval (a single span carries
        // no dispersion information), so the interval fields are omitted.
        assert_eq!(value.get("span_count").and_then(Value::as_u64), Some(1));
        assert_eq!(
            value
                .get("slope_bytes_per_iteration")
                .and_then(Value::as_f64),
            Some(200.0)
        );
        assert!(value.get("interval_low_bytes_per_iteration").is_none());
        assert!(value.get("interval_high_bytes_per_iteration").is_none());
        // The raw means, standard deviation, minimum and maximum are not emitted.
        assert!(value.get("mean_bytes_per_iteration").is_none());
        assert!(value.get("mean_allocations_per_iteration").is_none());
        assert!(value.get("std_dev_bytes_per_iteration").is_none());
        assert!(value.get("min_bytes_per_iteration").is_none());
        assert!(value.get("max_bytes_per_iteration").is_none());
        assert_eq!(
            value
                .get("slope_allocations_per_iteration")
                .and_then(Value::as_f64),
            Some(2.0)
        );
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Writes files, which is not supported under Miri isolation.
    fn writes_interval_when_multiple_spans_recorded() {
        // Two identical spans clear the two-span threshold with zero residual
        // dispersion, so the interval collapses onto the slope and is written out.
        let session = Session::new().no_stdout().no_file();
        for _ in 0..2 {
            let operation = session.operation("allocate_vec");
            let _span = operation.measure_thread().iterations(4);
            register_fake_allocation(800, 8);
        }
        let directory = tempfile::tempdir().unwrap();

        session.to_report().write_to_directory(directory.path());

        let value = read_json(&directory.path().join("allocate_vec.json"));
        assert_eq!(value.get("span_count").and_then(Value::as_u64), Some(2));
        assert_eq!(
            value
                .get("interval_low_bytes_per_iteration")
                .and_then(Value::as_f64),
            Some(200.0)
        );
        assert_eq!(
            value
                .get("interval_high_bytes_per_iteration")
                .and_then(Value::as_f64),
            Some(200.0)
        );
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Writes files, which is not supported under Miri isolation.
    fn writes_null_slopes_for_zero_iteration_operation() {
        let session = Session::new().no_stdout().no_file();
        {
            let operation = session.operation("failed");
            // The workload could not run, so it records zero iterations.
            let _span = operation.measure_thread().iterations(0);
            register_fake_allocation(800, 8);
        }
        let directory = tempfile::tempdir().unwrap();

        session.to_report().write_to_directory(directory.path());

        let value = read_json(&directory.path().join("failed.json"));
        // A zero-iteration measurement has no per-iteration rate; both slopes are
        // NaN, which serde_json renders as JSON null.
        assert!(
            value
                .get("slope_bytes_per_iteration")
                .expect("the bytes slope field is always present")
                .is_null(),
            "a zero-iteration bytes slope must serialize as null"
        );
        assert!(
            value
                .get("slope_allocations_per_iteration")
                .expect("the allocations slope field is always present")
                .is_null(),
            "a zero-iteration allocations slope must serialize as null"
        );
        assert_eq!(
            value.get("total_iterations").and_then(Value::as_u64),
            Some(0)
        );
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Writes files, which is not supported under Miri isolation.
    fn sanitizes_operation_name_in_file_name() {
        let session = session_with_recorded_work("group/case name");
        let directory = tempfile::tempdir().unwrap();

        session.to_report().write_to_directory(directory.path());

        let file = directory.path().join("group_case_name.json");
        assert!(file.exists());

        // The original, unsanitized name is preserved inside the file.
        assert_eq!(
            read_json(&file).get("operation").and_then(Value::as_str),
            Some("group/case name")
        );
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Writes files, which is not supported under Miri isolation.
    fn empty_session_writes_no_files() {
        let session = Session::new().no_stdout().no_file();
        let directory = tempfile::tempdir().unwrap();
        let target = directory.path().join("nested");

        session.to_report().write_to_directory(&target);

        // Nothing is written, so the directory is not even created.
        assert!(!target.exists());
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Writes files, which is not supported under Miri isolation.
    fn skips_operations_without_iterations() {
        let session = Session::new().no_stdout().no_file();
        {
            let operation = session.operation("measured");
            let _span = operation.measure_thread().iterations(4);
            register_fake_allocation(800, 8);
        }
        // Registered but never measured, so it stays at zero iterations and must
        // be skipped rather than written.
        let _unmeasured = session.operation("unmeasured");

        let directory = tempfile::tempdir().unwrap();
        session.to_report().write_to_directory(directory.path());

        assert!(directory.path().join("measured.json").exists());
        assert!(!directory.path().join("unmeasured.json").exists());
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Writes files, which is not supported under Miri isolation.
    fn overwrites_existing_files() {
        let directory = tempfile::tempdir().unwrap();
        let file = directory.path().join("allocate_vec.json");
        fs::write(&file, "stale contents").unwrap();

        let session = session_with_recorded_work("allocate_vec");
        session.to_report().write_to_directory(directory.path());

        // Parsing succeeds only if the stale, non-JSON contents were replaced.
        let value = read_json(&file);
        assert_eq!(
            value.get("operation").and_then(Value::as_str),
            Some("allocate_vec")
        );
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Writes files, which is not supported under Miri isolation.
    #[should_panic(expected = "failed to create benchmark output directory")]
    fn panics_when_output_directory_cannot_be_created() {
        let session = session_with_recorded_work("allocate_vec");
        let directory = tempfile::tempdir().unwrap();

        // A regular file where a directory component is expected makes the
        // recursive directory creation fail.
        let blocker = directory.path().join("blocker");
        fs::write(&blocker, "not a directory").unwrap();

        session
            .to_report()
            .write_to_directory(blocker.join("nested"));
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Writes files, which is not supported under Miri isolation.
    #[should_panic(expected = "failed to write benchmark output file")]
    fn panics_when_output_file_cannot_be_written() {
        let session = session_with_recorded_work("allocate_vec");
        let directory = tempfile::tempdir().unwrap();

        // A directory occupying the output file's path makes the file write fail.
        fs::create_dir_all(directory.path().join("allocate_vec.json")).unwrap();

        session.to_report().write_to_directory(directory.path());
    }

    #[test]
    #[should_panic(expected = "after sanitization")]
    fn panics_when_operation_names_collide_after_sanitization() {
        let session = Session::new().no_stdout().no_file();

        // Both names sanitize to `group_case.json`, so writing both would silently
        // discard one operation's results.
        for name in ["group/case", "group_case"] {
            let operation = session.operation(name);
            let _span = operation.measure_thread().iterations(4);
            register_fake_allocation(800, 8);
        }

        // The collision is detected before anything is written, so this path is
        // never created.
        session
            .to_report()
            .write_to_directory("collision_is_detected_before_writing");
    }
}