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
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//! Memory allocation tracking reports.

use std::collections::HashMap;
use std::fmt;

use crate::OperationMetrics;

/// Thread-safe memory allocation tracking report.
///
/// A `Report` contains the captured memory allocation statistics from a [`Session`](crate::Session)
/// and can be safely sent to other threads for processing. Reports can be merged together
/// and processed independently.
///
/// # Examples
///
/// ```
/// use alloc_tracker::{Allocator, Session};
///
/// #[global_allocator]
/// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
///
/// # fn main() {
/// let session = Session::new();
/// # let session = session.no_stdout().no_file();
/// {
///     let operation = session.operation("test_work");
///     let _span = operation.measure_process().iterations(1);
///     let _data = vec![1, 2, 3, 4, 5]; // This allocates memory
/// }
///
/// let report = session.to_report();
///
/// // A report exposes each operation's statistics for programmatic use.
/// let total_bytes: u64 = report
///     .operations()
///     .map(|(_, op)| op.total_bytes_allocated())
///     .sum();
/// println!("Captured {total_bytes} bytes across all operations");
/// # }
/// ```
///
/// # Merging reports
///
/// ```
/// use alloc_tracker::{Allocator, Report, Session};
///
/// #[global_allocator]
/// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
///
/// # fn main() {
/// // Create two separate sessions
/// let session1 = Session::new();
/// # let session1 = session1.no_stdout().no_file();
/// let session2 = Session::new();
/// # let session2 = session2.no_stdout().no_file();
///
/// // Record some work in each
/// {
///     let op1 = session1.operation("work");
///     let _span1 = op1.measure_process().iterations(1);
///     let _data1 = vec![1, 2, 3]; // This allocates memory
/// }
///
/// {
///     let op2 = session2.operation("work");
///     let _span2 = op2.measure_process().iterations(1);
///     let _data2 = vec![4, 5, 6, 7]; // This allocates more memory
/// }
///
/// // Convert to reports and merge
/// let report1 = session1.to_report();
/// let report2 = session2.to_report();
/// let merged = Report::merge(&report1, &report2);
///
/// // The merged report exposes the combined statistics for programmatic use.
/// let total_bytes: u64 = merged
///     .operations()
///     .map(|(_, op)| op.total_bytes_allocated())
///     .sum();
/// println!("Merged report captured {total_bytes} bytes across all operations");
/// # }
/// ```
#[derive(Clone, Debug, Default)]
pub struct Report {
    operations: HashMap<String, ReportOperation>,
}

/// Memory allocation statistics for a single operation in a report.
#[derive(Clone, Debug)]
pub struct ReportOperation {
    metrics: OperationMetrics,
}

/// Per-iteration statistics for a single allocation metric.
///
/// Every value is expressed in the metric's own per-iteration unit (bytes, or a
/// count of allocations). [`slope`](Self::slope) is the per-iteration value and
/// [`interval`](Self::interval) its 95% confidence bounds, or `None` when there
/// is not enough data to estimate them.
///
/// When the operation's spans covered zero iterations there is no per-iteration
/// rate: [`slope`](Self::slope) is then `NaN` and [`interval`](Self::interval)
/// is `None`.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct MetricStatistics {
    /// The per-iteration value, or `NaN` when the spans covered zero iterations.
    pub slope: f64,

    /// Confidence interval `(low, high)` for [`slope`](Self::slope), or `None`
    /// when it cannot be estimated.
    pub interval: Option<(f64, f64)>,
}

/// Statistics for one operation across both allocation metrics.
///
/// Exposed through [`ReportOperation::statistics`] so callers can consume the
/// same figures that are written to the machine-readable JSON output.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct OperationStatistics {
    /// Number of spans the statistics were derived from (distinct from the total
    /// iteration count).
    pub span_count: u64,

    /// Per-iteration byte-count statistics.
    pub bytes: MetricStatistics,

    /// Per-iteration allocation-count statistics.
    pub allocations: MetricStatistics,
}

impl Report {
    /// Creates an empty report.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn new() -> Self {
        Self {
            operations: HashMap::new(),
        }
    }

    /// Creates a report from shared operation data.
    #[must_use]
    pub(crate) fn from_operation_data(operation_data: &HashMap<String, OperationMetrics>) -> Self {
        let report_operations = operation_data
            .iter()
            .map(|(name, metrics)| {
                (
                    name.clone(),
                    ReportOperation {
                        metrics: metrics.clone(),
                    },
                )
            })
            .collect();

        Self {
            operations: report_operations,
        }
    }

    /// Merges two reports into a new report.
    ///
    /// The resulting report contains the combined statistics from both input reports.
    /// Operations with the same name have their spans concatenated as if all spans
    /// had been recorded through a single session.
    ///
    /// # Examples
    ///
    /// ```
    /// use alloc_tracker::{Allocator, Report, Session};
    ///
    /// #[global_allocator]
    /// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
    ///
    /// # fn main() {
    /// let session1 = Session::new();
    /// # let session1 = session1.no_stdout().no_file();
    /// let session2 = Session::new();
    /// # let session2 = session2.no_stdout().no_file();
    ///
    /// // Both sessions record the same operation name
    /// {
    ///     let op1 = session1.operation("common_work");
    ///     let _span1 = op1.measure_process().iterations(1);
    ///     let _data1 = vec![1, 2, 3]; // 3 elements
    /// }
    ///
    /// {
    ///     let op2 = session2.operation("common_work");
    ///     let _span2 = op2.measure_process().iterations(1);
    ///     let _data2 = vec![4, 5]; // 2 elements
    /// }
    ///
    /// let report1 = session1.to_report();
    /// let report2 = session2.to_report();
    ///
    /// // Merged report shows combined statistics (2 total iterations)
    /// let merged = Report::merge(&report1, &report2);
    /// # }
    /// ```
    #[must_use]
    pub fn merge(a: &Self, b: &Self) -> Self {
        let mut merged_operations = a.operations.clone();

        for (name, b_op) in &b.operations {
            merged_operations
                .entry(name.clone())
                .and_modify(|a_op| a_op.metrics.merge(&b_op.metrics))
                .or_insert_with(|| b_op.clone());
        }

        Self {
            operations: merged_operations,
        }
    }

    /// Returns the operations sorted by name.
    ///
    /// The report holds operations in an unordered map, so every output sorts
    /// them by name to present a stable, reproducible order.
    pub(crate) fn sorted_operations(&self) -> Vec<(&str, &ReportOperation)> {
        let mut operations: Vec<(&str, &ReportOperation)> = self
            .operations
            .iter()
            .map(|(name, op)| (name.as_str(), op))
            .collect();
        operations.sort_unstable_by_key(|(name, _)| *name);
        operations
    }

    /// Prints the memory allocation statistics to stdout.
    ///
    /// Prints 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, in which case printing anything might violate the
    /// output protocol the tool is speaking.
    // Excluded from coverage as an un-assertable stdout side effect, matching the
    // sibling `Display` impl. The figures it prints are covered independently via
    // `Display` and the JSON output, so nothing computational is hidden here.
    #[cfg_attr(coverage_nightly, coverage(off))]
    #[cfg_attr(test, mutants::skip)] // Too difficult to test stdout output reliably - manually tested.
    pub fn print_to_stdout(&self) {
        if self.is_empty() {
            return;
        }
        println!("{self}");
    }

    /// Whether there is any recorded activity in this report.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.operations.is_empty() || self.operations.values().all(|op| op.metrics.is_empty())
    }

    /// Returns an iterator over the operation names and their statistics.
    ///
    /// This allows programmatic access to the same data that would be printed by
    /// [`print_to_stdout()`](Self::print_to_stdout).
    ///
    /// # Examples
    ///
    /// ```
    /// use alloc_tracker::{Allocator, Session};
    ///
    /// #[global_allocator]
    /// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
    ///
    /// # fn main() {
    /// let session = Session::new();
    /// # let session = session.no_stdout().no_file();
    /// {
    ///     let operation = session.operation("test_work");
    ///     let _span = operation.measure_process().iterations(1);
    ///     let _data = vec![1, 2, 3, 4, 5]; // This allocates memory
    /// }
    ///
    /// let report = session.to_report();
    /// for (name, op) in report.operations() {
    ///     println!(
    ///         "Operation '{}' had {} iterations",
    ///         name,
    ///         op.total_iterations()
    ///     );
    ///     println!("Bytes per iteration: {:?}", op.bytes());
    ///     println!("Total bytes: {}", op.total_bytes_allocated());
    /// }
    /// # }
    /// ```
    pub fn operations(&self) -> impl Iterator<Item = (&str, &ReportOperation)> {
        self.operations.iter().map(|(name, op)| (name.as_str(), op))
    }
}

impl ReportOperation {
    /// Returns the total bytes allocated across all iterations for this operation.
    #[must_use]
    pub fn total_bytes_allocated(&self) -> u64 {
        self.metrics.total_bytes_allocated()
    }

    /// Returns the total number of allocations across all iterations for this operation.
    #[must_use]
    pub fn total_allocations_count(&self) -> u64 {
        self.metrics.total_allocations_count()
    }

    /// Returns the total number of iterations recorded for this operation.
    #[must_use]
    pub fn total_iterations(&self) -> u64 {
        self.metrics.total_iterations()
    }

    /// Returns the per-iteration bytes allocated — the primary allocation metric
    /// for this operation.
    ///
    /// Returns `None` when no finite per-iteration rate is available — for example
    /// when no spans were recorded, or the recorded spans covered zero iterations
    /// (leaving the rate undefined).
    #[must_use]
    pub fn bytes(&self) -> Option<f64> {
        self.metrics.bytes_slope().filter(|slope| slope.is_finite())
    }

    /// Returns the per-iteration allocation count for this operation.
    ///
    /// Returns `None` when no finite per-iteration rate is available — for example
    /// when no spans were recorded, or the recorded spans covered zero iterations
    /// (leaving the rate undefined).
    #[must_use]
    pub fn allocations(&self) -> Option<f64> {
        self.metrics
            .allocations_slope()
            .filter(|slope| slope.is_finite())
    }

    /// Computes per-iteration statistics over the recorded spans.
    ///
    /// Returns `None` when no spans were recorded. The returned
    /// [`OperationStatistics`] carries the per-iteration value and its confidence
    /// interval for both the byte and allocation-count metrics — the same figures
    /// written to the machine-readable JSON output.
    ///
    /// # Examples
    ///
    /// ```
    /// use alloc_tracker::{Allocator, Session};
    ///
    /// #[global_allocator]
    /// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
    ///
    /// # fn main() {
    /// let session = Session::new();
    /// # let session = session.no_stdout().no_file();
    /// {
    ///     let operation = session.operation("test_work");
    ///     let _span = operation.measure_process().iterations(1);
    ///     let _data = vec![1, 2, 3, 4, 5]; // This allocates memory
    /// }
    ///
    /// let report = session.to_report();
    /// for (_name, op) in report.operations() {
    ///     if let Some(stats) = op.statistics() {
    ///         println!(
    ///             "slope: {} bytes/iter over {} spans",
    ///             stats.bytes.slope, stats.span_count
    ///         );
    ///     }
    /// }
    /// # }
    /// ```
    #[must_use]
    pub fn statistics(&self) -> Option<OperationStatistics> {
        if self.metrics.span_count() == 0 {
            return None;
        }
        Some(OperationStatistics {
            span_count: self.metrics.span_count(),
            bytes: MetricStatistics {
                slope: self.metrics.bytes_slope()?,
                interval: self.metrics.bytes_interval(),
            },
            allocations: MetricStatistics {
                slope: self.metrics.allocations_slope()?,
                interval: self.metrics.allocations_interval(),
            },
        })
    }
}

/// Formats a per-iteration count for human-readable output.
///
/// Counts are conceptually integers but the warmup-robust slope is a real number
/// (a fitted per-iteration rate), so this rounds to two decimals and trims any
/// trailing zeros: `200.0` renders as `200` and `199.5` as `199.5`. A slope of
/// `NaN` — produced when the operation's spans covered zero iterations — renders
/// as `"NaN"` to mark the measurement as unusable.
pub(crate) fn format_count(value: f64) -> String {
    if value.is_nan() {
        return "NaN".to_owned();
    }
    let rounded = (value.max(0.0) * 100.0).round() / 100.0;
    let mut rendered = format!("{rounded:.2}");
    if rendered.contains('.') {
        rendered = rendered
            .trim_end_matches('0')
            .trim_end_matches('.')
            .to_string();
    }
    rendered
}

impl fmt::Display for ReportOperation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The summary shows only the per-iteration slopes, not their intervals.
        match (self.metrics.bytes_slope(), self.metrics.allocations_slope()) {
            (Some(bytes), Some(allocations)) => write!(
                f,
                "{} bytes/iter, {} allocations/iter",
                format_count(bytes),
                format_count(allocations),
            ),
            _ => write!(f, "no measurements"),
        }
    }
}

// No API contract to test - output format is not guaranteed.
#[cfg_attr(coverage_nightly, coverage(off))] // Too annoying to test every question mark operator.
impl fmt::Display for Report {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_empty() {
            writeln!(f, "No allocation statistics captured.")?;
            return Ok(());
        }

        writeln!(f, "Allocation statistics:")?;
        writeln!(f)?;

        // Pre-render the per-iteration slope cells so the column widths and the
        // printed rows are computed from the exact same strings. The confidence
        // interval is kept out of this summary for readability; it remains in the
        // JSON output and the `statistics()` API.
        let rows: Vec<(&str, String, String)> = self
            .sorted_operations()
            .into_iter()
            .map(|(name, operation)| match operation.statistics() {
                Some(statistics) => (
                    name,
                    format_count(statistics.bytes.slope),
                    format_count(statistics.allocations.slope),
                ),
                None => (name, "n/a".to_owned(), "n/a".to_owned()),
            })
            .collect();

        let name_header = "Operation";
        let bytes_header = "Bytes/iter";
        let count_header = "Allocations/iter";

        let max_name_width = rows
            .iter()
            .map(|(name, _, _)| name.len())
            .max()
            .unwrap_or(0)
            .max(name_header.len());
        let max_bytes_width = rows
            .iter()
            .map(|(_, bytes, _)| bytes.len())
            .max()
            .unwrap_or(0)
            .max(bytes_header.len());
        let max_count_width = rows
            .iter()
            .map(|(_, _, count)| count.len())
            .max()
            .unwrap_or(0)
            .max(count_header.len());

        // Print table header.
        writeln!(
            f,
            "| {name_header:<max_name_width$} | {bytes_header:>max_bytes_width$} | {count_header:>max_count_width$} |",
        )?;

        // Print separator.
        let separator_name_width = max_name_width
            .checked_add(2)
            .expect("operation name width fits in memory, adding 2 cannot overflow");
        let separator_bytes_width = max_bytes_width
            .checked_add(2)
            .expect("bytes width fits in memory, adding 2 cannot overflow");
        let separator_count_width = max_count_width
            .checked_add(2)
            .expect("count width fits in memory, adding 2 cannot overflow");
        writeln!(
            f,
            "|{:-<separator_name_width$}|{:-<separator_bytes_width$}|{:-<separator_count_width$}|",
            "", "", "",
        )?;

        // Print table rows.
        for (name, bytes, count) in rows {
            writeln!(
                f,
                "| {name:<max_name_width$} | {bytes:>max_bytes_width$} | {count:>max_count_width$} |",
            )?;
        }

        Ok(())
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    #![allow(
        clippy::float_cmp,
        reason = "allocation statistics are exact integer-derived values in these fixtures"
    )]

    use std::panic::{RefUnwindSafe, UnwindSafe};

    use super::*;
    use crate::Session;
    use crate::allocator::register_fake_allocation;

    /// Builds a detached [`ReportOperation`] from per-iteration deltas for tests
    /// that assert directly on the report surface without a live session.
    fn report_operation(bytes_delta: u64, count_delta: u64, iterations: u64) -> ReportOperation {
        let mut metrics = OperationMetrics::default();
        metrics.add_iterations(bytes_delta, count_delta, iterations);
        ReportOperation { metrics }
    }

    #[test]
    fn new_report_is_empty() {
        let report = Report::new();
        assert!(report.is_empty());
    }

    #[test]
    fn report_from_empty_session_is_empty() {
        let session = Session::new().no_stdout().no_file();
        let report = session.to_report();
        assert!(report.is_empty());
    }

    #[test]
    fn report_from_session_with_operations_is_not_empty() {
        let session = Session::new().no_stdout().no_file();
        {
            let operation = session.operation("test");
            let _span = operation.measure_thread().iterations(1);
            register_fake_allocation(100, 1);
        } // Span drops here, releasing the mutable borrow

        let report = session.to_report();
        assert!(!report.is_empty());
    }

    #[test]
    fn report_with_registered_but_unmeasured_operation_is_empty() {
        let session = Session::new().no_stdout().no_file();
        let _operation = session.operation("unmeasured");

        let report = session.to_report();
        assert!(report.is_empty());
    }

    #[test]
    fn report_with_only_zero_iteration_spans_is_empty() {
        // A span that covered zero iterations records a span (so statistics can be
        // fit) but no measurable work, so the report is still empty. Guards against
        // `is_empty` regressing to key off whether statistics exist.
        let session = Session::new().no_stdout().no_file();
        {
            let operation = session.operation("failed");
            let _span = operation.measure_thread().iterations(0);
            register_fake_allocation(800, 8);
        }

        let report = session.to_report();
        assert!(report.is_empty());
        // The operation still recorded a span, so it exposes statistics.
        let operations = report.sorted_operations();
        let (_name, operation) = operations.first().expect("the report has one operation");
        assert!(operation.statistics().is_some());
    }

    #[test]
    fn operations_are_sorted_by_name() {
        let mut operations = HashMap::new();
        operations.insert("zebra".to_owned(), report_operation(10, 1, 1));
        operations.insert("alpha".to_owned(), report_operation(20, 2, 1));
        let report = Report { operations };

        let names: Vec<&str> = report
            .sorted_operations()
            .into_iter()
            .map(|(name, _)| name)
            .collect();
        assert_eq!(names, ["alpha", "zebra"]);
    }

    #[test]
    fn merge_empty_reports() {
        let report1 = Report::new();
        let report2 = Report::new();
        let merged = Report::merge(&report1, &report2);
        assert!(merged.is_empty());
    }

    #[test]
    fn merge_empty_with_non_empty() {
        let session = Session::new().no_stdout().no_file();
        {
            let operation = session.operation("test");
            let _span = operation.measure_thread().iterations(1);
            register_fake_allocation(100, 1);
        } // Span drops here

        let report1 = Report::new();
        let report2 = session.to_report();

        let merged1 = Report::merge(&report1, &report2);
        let merged2 = Report::merge(&report2, &report1);

        assert!(!merged1.is_empty());
        assert!(!merged2.is_empty());
    }

    #[test]
    fn merge_different_operations() {
        let session1 = Session::new().no_stdout().no_file();
        let session2 = Session::new().no_stdout().no_file();

        {
            let op1 = session1.operation("test1");
            let _span1 = op1.measure_thread().iterations(1);
            register_fake_allocation(100, 1);
        } // Span drops here

        {
            let op2 = session2.operation("test2");
            let _span2 = op2.measure_thread().iterations(1);
            register_fake_allocation(200, 2);
        } // Span drops here

        let report1 = session1.to_report();
        let report2 = session2.to_report();
        let merged = Report::merge(&report1, &report2);

        assert_eq!(merged.operations.len(), 2);
        assert!(merged.operations.contains_key("test1"));
        assert!(merged.operations.contains_key("test2"));
    }

    #[test]
    fn merge_same_operations() {
        let session1 = Session::new().no_stdout().no_file();
        let session2 = Session::new().no_stdout().no_file();

        {
            let op1 = session1.operation("test");
            let _span1 = op1.measure_thread().iterations(1);
            register_fake_allocation(100, 1);
        } // Span drops here

        {
            let op2 = session2.operation("test");
            let _span2 = op2.measure_thread().iterations(1);
            register_fake_allocation(200, 2);
        } // Span drops here

        let report1 = session1.to_report();
        let report2 = session2.to_report();
        let merged = Report::merge(&report1, &report2);

        assert_eq!(merged.operations.len(), 1);
        let merged_op = merged.operations.get("test").unwrap();
        assert_eq!(merged_op.total_iterations(), 2); // 1 + 1
        assert_eq!(merged_op.total_bytes_allocated(), 300); // 100 + 200
        assert_eq!(merged_op.total_allocations_count(), 3); // 1 + 2
    }

    #[test]
    fn report_clone() {
        let session = Session::new().no_stdout().no_file();
        {
            let operation = session.operation("test");
            let _span = operation.measure_thread().iterations(1);
            register_fake_allocation(100, 1);
        } // Span drops here

        let report1 = session.to_report();
        let report2 = report1.clone();

        assert_eq!(report1.operations.len(), report2.operations.len());
    }

    #[test]
    fn report_operation_total_allocations_count_zero() {
        let operation = report_operation(0, 0, 1);
        assert_eq!(operation.total_allocations_count(), 0);
    }

    #[test]
    fn report_operation_total_allocations_count_multiple() {
        // 100 bytes and 5 allocations per iteration over 5 iterations.
        let operation = report_operation(100, 5, 5);
        assert_eq!(operation.total_allocations_count(), 25);
    }

    #[test]
    fn report_operation_total_allocations_count_consistency_with_session() {
        let session = Session::new().no_stdout().no_file();
        {
            let operation = session.operation("test_consistency");
            let _span = operation.measure_thread().iterations(1);
            // Simulate 3 allocations
            register_fake_allocation(300, 3);
        } // Span drops here

        let report = session.to_report();
        let operations: Vec<_> = report.operations().collect();
        assert_eq!(operations.len(), 1);

        let (_name, report_op) = operations.first().unwrap();
        assert_eq!(report_op.total_allocations_count(), 3);
        assert_eq!(report_op.total_bytes_allocated(), 300);
        assert_eq!(report_op.total_iterations(), 1);
    }

    #[test]
    fn statistics_are_none_without_spans() {
        let session = Session::new().no_stdout().no_file();
        let report = session.to_report();
        assert!(report.operations().next().is_none());
    }

    #[test]
    fn statistics_expose_both_metric_estimates() {
        // A single recorded span yields a span count of one and a slope equal to
        // the per-iteration mean, but carries no dispersion information, so the
        // interval is withheld.
        let operation = report_operation(200, 2, 4);
        let stats = operation.statistics().unwrap();
        assert_eq!(stats.span_count, 1);
        assert_eq!(stats.bytes.slope, 200.0);
        assert_eq!(stats.bytes.interval, None);
        assert_eq!(stats.allocations.slope, 2.0);
        assert_eq!(stats.allocations.interval, None);
    }

    #[test]
    fn repeated_identical_spans_collapse_the_interval_onto_the_slope() {
        // Two identical spans clear the two-span threshold with zero residual
        // dispersion, so the interval collapses onto the slope.
        let mut metrics = OperationMetrics::default();
        metrics.add_iterations(200, 2, 4);
        metrics.add_iterations(200, 2, 4);
        let operation = ReportOperation { metrics };

        let stats = operation.statistics().unwrap();
        assert_eq!(stats.span_count, 2);
        assert_eq!(stats.bytes.slope, 200.0);
        assert_eq!(stats.bytes.interval, Some((200.0, 200.0)));
    }

    // Static assertions for thread safety.
    static_assertions::assert_impl_all!(Report: Send, Sync);
    static_assertions::assert_impl_all!(ReportOperation: Send, Sync);
    static_assertions::assert_impl_all!(OperationStatistics: Send, Sync);
    static_assertions::assert_impl_all!(MetricStatistics: Send, Sync);

    // Static assertions for unwind safety.
    static_assertions::assert_impl_all!(Report: UnwindSafe, RefUnwindSafe);
    static_assertions::assert_impl_all!(
        ReportOperation: UnwindSafe, RefUnwindSafe
    );

    #[test]
    fn report_operation_display_shows_robust_per_iteration_estimate() {
        // 250 bytes/iter over 4 iterations → a single-span slope of 250 with the
        // interval collapsed onto it.
        let operation = report_operation(250, 3, 4);
        let display_output = operation.to_string();
        assert!(
            display_output.contains("bytes/iter"),
            "got {display_output}"
        );
        assert!(display_output.contains("250"), "got {display_output}");
    }

    #[test]
    fn report_operation_display_shows_nan_for_zero_iterations() {
        // A span that covered zero iterations has no per-iteration rate, so the
        // slopes are NaN and render as "NaN" rather than a misleading "0".
        let operation = report_operation(250, 3, 0);
        let display_output = operation.to_string();
        assert!(
            display_output.contains("NaN bytes/iter"),
            "got {display_output}"
        );
        assert!(
            display_output.contains("NaN allocations/iter"),
            "got {display_output}"
        );
    }

    #[test]
    fn report_operation_display_reports_no_measurements_when_empty() {
        // A report operation whose metrics recorded no spans has no statistics, so
        // its Display takes the `None` leg.
        let operation = ReportOperation {
            metrics: OperationMetrics::default(),
        };
        assert_eq!(operation.to_string(), "no measurements");
    }

    #[test]
    fn empty_report_display_shows_no_statistics_message() {
        let report = Report::new();
        let display_output = report.to_string();
        assert!(display_output.contains("No allocation statistics captured."));
    }
}