rcp-tools-common 0.41.0

Internal library for RCP file operation tools - shared utilities and core operations (not intended for direct use)
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
//! Elapsed timings with explicit logical scope lifetimes.
//!
//! Finished and interrupted samples both contribute to every duration statistic. Durations include
//! async suspension, are not CPU time, and overlapping scopes must not be added as wall time.
//! Names are static callsite literals, with at most 256 aggregate buckets (including overflow).
//! Histograms retain two significant figures in microseconds; totals and maxima retain full
//! `Duration` precision. Histogram values saturate only above 2^56 microseconds (over 2,000 years).

use anyhow::Context;
use serde::Serialize;
use std::io::Write;

pub(crate) mod metadata;

const TARGET: &str = "rcp::timing";
const FINISHED_FIELD: &str = "timing_finished";
const MAX_SCOPES: usize = 256;
const MAX_HISTOGRAM_MICROS: u64 = 1 << 56;

/// Measure elapsed time until explicit completion or drop, without entering a tracing span.
///
/// `finish()` means the measured work returned, including an ordinary error result. Dropping the
/// guard without finishing records an interrupted sample, including cancellation and early exits.
/// Use the `trace` form for hot per-file scopes enabled by `--timings-detail`.
///
/// ```
/// let scope = common::timing_scope!("operation");
/// // perform work, including async work, without holding an entered span guard
/// scope.finish();
/// ```
#[macro_export]
macro_rules! timing_scope {
    ($name:literal) => {
        $crate::timing::Scope::new(tracing::info_span!(
            target: "rcp::timing", $name, timing_finished = tracing::field::Empty
        ))
    };
    (trace, $name:literal) => {
        $crate::timing::Scope::new(tracing::trace_span!(
            target: "rcp::timing", $name, timing_finished = tracing::field::Empty
        ))
    };
}

/// An explicit scope lifetime, independent of cloned spans and child spans.
#[must_use = "keep the timing scope alive until the measured work finishes"]
pub struct Scope {
    span: Option<tracing::Span>,
}

impl Scope {
    /// Construct a guard for the span generated by [`crate::timing_scope!`].
    #[doc(hidden)]
    pub fn new(span: tracing::Span) -> Self {
        Self { span: Some(span) }
    }

    /// Return the span without entering it.
    fn span(&self) -> &tracing::Span {
        self.span.as_ref().expect("scope has not finished")
    }

    /// Instrument a future and finish when it returns, including an ordinary error result.
    /// Cancellation drops the guard and records interruption.
    pub async fn measure<F: std::future::Future>(self, future: F) -> F::Output {
        use tracing::Instrument;
        let output = future.instrument(self.span().clone()).await;
        self.finish();
        output
    }

    /// Record normal logical completion, regardless of the operation's success or failure.
    pub fn finish(mut self) {
        if let Some(span) = self.span.take() {
            span.record(FINISHED_FIELD, true);
        }
    }
}

impl Drop for Scope {
    fn drop(&mut self) {
        if let Some(span) = self.span.take() {
            span.record(FINISHED_FIELD, false);
        }
    }
}

pub(crate) fn timing_filter(detail: bool) -> tracing_subscriber::filter::Targets {
    tracing_subscriber::filter::Targets::new().with_target(
        TARGET,
        if detail {
            tracing::Level::TRACE
        } else {
            tracing::Level::INFO
        },
    )
}

struct ActiveScope {
    name: &'static str,
    start: std::time::Instant,
    lane: u64,
}

struct Aggregate {
    finished: u64,
    interrupted: u64,
    total: std::time::Duration,
    max: std::time::Duration,
    histogram: hdrhistogram::Histogram<u64>,
}

impl Default for Aggregate {
    fn default() -> Self {
        Self {
            finished: 0,
            interrupted: 0,
            total: std::time::Duration::ZERO,
            max: std::time::Duration::ZERO,
            histogram: hdrhistogram::Histogram::new_with_bounds(1, MAX_HISTOGRAM_MICROS, 2)
                .expect("valid fixed histogram bounds"),
        }
    }
}

impl Aggregate {
    fn record(&mut self, elapsed: std::time::Duration, finished: bool) {
        if finished {
            self.finished += 1;
        } else {
            self.interrupted += 1;
        }
        self.total = self.total.saturating_add(elapsed);
        self.max = self.max.max(elapsed);
        let micros = elapsed.as_micros().min(u128::from(MAX_HISTOGRAM_MICROS)) as u64;
        self.histogram
            .record(micros)
            .expect("sample is within fixed bounds");
    }

    fn summary(&self, name: &'static str) -> ScopeSummary {
        let count = self.finished + self.interrupted;
        ScopeSummary {
            name,
            count,
            finished: self.finished,
            interrupted: self.interrupted,
            total_seconds: self.total.as_secs_f64(),
            mean_seconds: self.total.as_secs_f64() / count as f64,
            p50_seconds: self.histogram.value_at_quantile(0.5) as f64 / 1_000_000.0,
            p95_seconds: self.histogram.value_at_quantile(0.95) as f64 / 1_000_000.0,
            max_seconds: self.max.as_secs_f64(),
        }
    }
}

#[derive(Serialize)]
struct ScopeSummary {
    name: &'static str,
    count: u64,
    finished: u64,
    interrupted: u64,
    total_seconds: f64,
    mean_seconds: f64,
    p50_seconds: f64,
    p95_seconds: f64,
    max_seconds: f64,
}

#[derive(Serialize)]
struct Summary<'a> {
    schema_version: u8,
    identifier: &'a str,
    pid: u32,
    scopes: Vec<ScopeSummary>,
}

struct State {
    identifier: String,
    epoch: std::time::Instant,
    next_lane: u64,
    available_lanes: std::collections::BinaryHeap<std::cmp::Reverse<(std::time::Instant, u64)>>,
    aggregates: std::collections::BTreeMap<&'static str, Aggregate>,
    summary: Option<std::fs::File>,
    timeline: Option<std::io::BufWriter<std::fs::File>>,
    timeline_started: bool,
    error: Option<anyhow::Error>,
    finalized: bool,
}

impl State {
    fn allocate_lane(&mut self, start: std::time::Instant) -> u64 {
        if self.timeline.is_none() {
            return 0;
        }
        // a start timestamp can precede a completion that won the state lock first
        if let Some(std::cmp::Reverse((end, _))) = self.available_lanes.peek()
            && *end <= start
        {
            return self.available_lanes.pop().unwrap().0.1;
        }
        self.next_lane += 1;
        self.next_lane
    }

    fn record(&mut self, scope: ActiveScope, finished: bool, end: std::time::Instant) {
        if self.finalized {
            return;
        }
        let elapsed = end.duration_since(scope.start);
        if self.summary.is_some() {
            let name = if self.aggregates.contains_key(scope.name)
                || self.aggregates.len() < MAX_SCOPES - 1
            {
                scope.name
            } else {
                "__overflow__"
            };
            self.aggregates
                .entry(name)
                .or_default()
                .record(elapsed, finished);
        }
        if let Some(timeline) = &mut self.timeline {
            let event = serde_json::json!({
                "name": scope.name, "cat": TARGET, "ph": "X",
                "pid": std::process::id(), "tid": scope.lane,
                "ts": scope.start.duration_since(self.epoch).as_secs_f64() * 1_000_000.0,
                "dur": elapsed.as_secs_f64() * 1_000_000.0,
                "args": { "identifier": self.identifier, "finished": finished }
            });
            let separator: &[u8] = if self.timeline_started {
                b",\n"
            } else {
                b"[\n"
            };
            let result = timeline
                .write_all(separator)
                .map_err(anyhow::Error::from)
                .and_then(|()| serde_json::to_writer(timeline, &event).map_err(Into::into));
            self.timeline_started = true;
            if self.error.is_none() {
                self.error = result.err();
            }
            self.available_lanes
                .push(std::cmp::Reverse((end, scope.lane)));
        }
    }
}

pub(crate) struct TimingLayer {
    state: std::sync::Arc<std::sync::Mutex<State>>,
    timeline_enabled: bool,
}

impl TimingLayer {
    pub(crate) fn new(
        identifier: String,
        summary: Option<std::fs::File>,
        timeline: Option<std::fs::File>,
    ) -> (Self, TimingGuard) {
        let timeline_enabled = timeline.is_some();
        let state = std::sync::Arc::new(std::sync::Mutex::new(State {
            identifier,
            epoch: std::time::Instant::now(),
            next_lane: 0,
            available_lanes: std::collections::BinaryHeap::new(),
            aggregates: std::collections::BTreeMap::new(),
            summary,
            timeline: timeline.map(std::io::BufWriter::new),
            timeline_started: false,
            error: None,
            finalized: false,
        }));
        (
            Self {
                state: state.clone(),
                timeline_enabled,
            },
            TimingGuard { state },
        )
    }
}

#[derive(Default)]
struct Completion(Option<bool>);

impl tracing::field::Visit for Completion {
    fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
        if field.name() == FINISHED_FIELD {
            self.0 = Some(value);
        }
    }
    fn record_debug(&mut self, _: &tracing::field::Field, _: &dyn std::fmt::Debug) {}
}

impl<S> tracing_subscriber::Layer<S> for TimingLayer
where
    S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
{
    fn on_new_span(
        &self,
        attributes: &tracing::span::Attributes<'_>,
        id: &tracing::span::Id,
        context: tracing_subscriber::layer::Context<'_, S>,
    ) {
        if attributes.metadata().target() != TARGET
            || attributes
                .metadata()
                .fields()
                .field(FINISHED_FIELD)
                .is_none()
        {
            return;
        }
        let start = std::time::Instant::now();
        let lane = if self.timeline_enabled {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state.allocate_lane(start)
        } else {
            0
        };
        if let Some(span) = context.span(id) {
            span.extensions_mut().insert(ActiveScope {
                name: attributes.metadata().name(),
                start,
                lane,
            });
        }
    }

    fn on_record(
        &self,
        id: &tracing::span::Id,
        values: &tracing::span::Record<'_>,
        context: tracing_subscriber::layer::Context<'_, S>,
    ) {
        let mut completion = Completion::default();
        values.record(&mut completion);
        if let Some(finished) = completion.0
            && let Some(span) = context.span(id)
        {
            let scope = span.extensions_mut().remove::<ActiveScope>();
            if let Some(scope) = scope {
                let end = std::time::Instant::now();
                self.state
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .record(scope, finished, end);
            }
        }
    }
}

pub(crate) struct TimingGuard {
    state: std::sync::Arc<std::sync::Mutex<State>>,
}

impl TimingGuard {
    pub(crate) fn finish(&mut self) -> anyhow::Result<()> {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if state.finalized {
            return Ok(());
        }
        state.finalized = true;
        let mut error = state.error.take();
        if let Some(file) = state.summary.take() {
            let summary = Summary {
                schema_version: 1,
                identifier: &state.identifier,
                pid: std::process::id(),
                scopes: state
                    .aggregates
                    .iter()
                    .map(|(&name, aggregate)| aggregate.summary(name))
                    .collect(),
            };
            let mut writer = std::io::BufWriter::new(file);
            let result = serde_json::to_writer_pretty(&mut writer, &summary)
                .context("failed to write timing summary")
                .and_then(|()| writer.flush().context("failed to flush timing summary"));
            if error.is_none() {
                error = result.err();
            }
        }
        if let Some(mut timeline) = state.timeline.take() {
            let closing: &[u8] = if state.timeline_started {
                b"\n]\n"
            } else {
                b"[]\n"
            };
            let result = timeline
                .write_all(closing)
                .and_then(|()| timeline.flush())
                .context("failed to flush elapsed scope timeline");
            if error.is_none() {
                error = result.err();
            }
        }
        match error {
            Some(error) => Err(error),
            None => Ok(()),
        }
    }
}

impl Drop for TimingGuard {
    fn drop(&mut self) {
        if let Err(error) = self.finish() {
            eprintln!("Failed to write scoped timings: {error:#}");
        }
    }
}

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

    fn collector(detail: bool) -> (tracing::Dispatch, TimingGuard, tempfile::NamedTempFile) {
        let file = tempfile::NamedTempFile::new().unwrap();
        let (layer, guard) =
            TimingLayer::new("test-role".into(), Some(file.reopen().unwrap()), None);
        let subscriber =
            tracing_subscriber::registry().with(layer.with_filter(timing_filter(detail)));
        (tracing::Dispatch::new(subscriber), guard, file)
    }

    fn report(guard: &mut TimingGuard, file: &tempfile::NamedTempFile) -> serde_json::Value {
        guard.finish().unwrap();
        serde_json::from_reader(file.reopen().unwrap()).unwrap()
    }

    #[test]
    fn finished_scope_is_recorded_before_clones_and_children_drop() {
        // another ambient registry exposes parent-reference teardown under the wrong subscriber
        tracing::subscriber::with_default(tracing_subscriber::registry(), || {
            let (dispatch, mut guard, file) = collector(false);
            tracing::dispatcher::with_default(&dispatch, || {
                let scope = crate::timing_scope!("parent");
                let clone = scope.span().clone();
                let child =
                    tracing::info_span!(target: "rcp::timing", parent: scope.span(), "child");
                scope.finish();
                let result = report(&mut guard, &file);
                assert_eq!(result["schema_version"], 1);
                assert_eq!(result["identifier"], "test-role");
                assert_eq!(result["pid"], std::process::id());
                assert_eq!(result["scopes"].as_array().unwrap().len(), 1);
                assert_eq!(result["scopes"][0]["count"], 1);
                assert_eq!(result["scopes"][0]["finished"], 1);
                assert_eq!(result["scopes"][0]["interrupted"], 0);
                // tracing-subscriber releases the child's parent through the current dispatcher
                drop((clone, child));
            });
        });
    }

    #[test]
    fn scope_drop_records_interruption_with_original_subscriber() {
        let (dispatch, mut guard, file) = collector(false);
        let scope =
            tracing::dispatcher::with_default(&dispatch, || crate::timing_scope!("dropped"));
        drop(scope);
        let result = report(&mut guard, &file);
        assert_eq!(result["scopes"][0]["count"], 1);
        assert_eq!(result["scopes"][0]["finished"], 0);
        assert_eq!(result["scopes"][0]["interrupted"], 1);
    }

    #[test]
    fn detail_scopes_require_explicit_enablement() {
        for detail in [false, true] {
            let (dispatch, mut guard, file) = collector(detail);
            tracing::dispatcher::with_default(&dispatch, || {
                crate::timing_scope!("coarse").finish();
                crate::timing_scope!(trace, "detail").finish();
            });
            let result = report(&mut guard, &file);
            assert_eq!(
                result["scopes"].as_array().unwrap().len(),
                if detail { 2 } else { 1 }
            );
        }
    }

    #[test]
    fn elapsed_time_includes_async_suspension_and_cancellation() {
        let (dispatch, mut guard, file) = collector(false);
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_time()
            .build()
            .unwrap();
        tracing::dispatcher::with_default(&dispatch, || {
            runtime.block_on(async {
                let scope = crate::timing_scope!("suspension");
                tokio::time::sleep(std::time::Duration::from_millis(20)).await;
                scope.finish();
                let task = tokio::spawn(async {
                    let _scope = crate::timing_scope!("cancellation");
                    std::future::pending::<()>().await;
                });
                tokio::task::yield_now().await;
                task.abort();
                assert!(task.await.unwrap_err().is_cancelled());
            })
        });
        let result = report(&mut guard, &file);
        let scopes = result["scopes"].as_array().unwrap();
        let suspended = scopes.iter().find(|s| s["name"] == "suspension").unwrap();
        assert!(suspended["total_seconds"].as_f64().unwrap() >= 0.015);
        let cancelled = scopes.iter().find(|s| s["name"] == "cancellation").unwrap();
        assert_eq!(cancelled["interrupted"], 1);
    }

    #[test]
    fn measured_error_results_are_finished_and_cancelled_futures_are_interrupted() {
        let (dispatch, mut guard, file) = collector(false);
        let runtime = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        tracing::dispatcher::with_default(&dispatch, || {
            runtime.block_on(async {
                let result = crate::timing_scope!("error-result")
                    .measure(async { Err::<(), _>("failed") })
                    .await;
                assert_eq!(result, Err("failed"));
                let task = tokio::spawn(
                    crate::timing_scope!("cancelled-future").measure(std::future::pending::<()>()),
                );
                tokio::task::yield_now().await;
                task.abort();
                assert!(task.await.unwrap_err().is_cancelled());
            })
        });
        let result = report(&mut guard, &file);
        let scopes = result["scopes"].as_array().unwrap();
        assert_eq!(
            scopes.iter().find(|s| s["name"] == "error-result").unwrap()["finished"],
            1
        );
        assert_eq!(
            scopes
                .iter()
                .find(|s| s["name"] == "cancelled-future")
                .unwrap()["interrupted"],
            1
        );
    }

    #[test]
    fn concurrent_scopes_keep_exact_counts() {
        let (dispatch, mut guard, file) = collector(false);
        std::thread::scope(|threads| {
            for _ in 0..8 {
                threads.spawn(|| {
                    tracing::dispatcher::with_default(&dispatch, || {
                        for _ in 0..100 {
                            crate::timing_scope!("parallel").finish();
                            drop(crate::timing_scope!("parallel"));
                        }
                    })
                });
            }
        });
        let result = report(&mut guard, &file);
        assert_eq!(result["scopes"][0]["count"], 1600);
        assert_eq!(result["scopes"][0]["finished"], 800);
        assert_eq!(result["scopes"][0]["interrupted"], 800);
    }

    #[test]
    fn summary_distribution_includes_interrupted_samples() {
        let mut aggregate = Aggregate::default();
        aggregate.record(std::time::Duration::from_secs(1), true);
        aggregate.record(std::time::Duration::from_secs(3), false);
        let summary = aggregate.summary("distribution");
        assert_eq!(summary.count, 2);
        assert_eq!(summary.total_seconds, 4.0);
        assert_eq!(summary.mean_seconds, 2.0);
        assert!((summary.p50_seconds - 1.0).abs() < 0.01);
        assert!((summary.p95_seconds - 3.0).abs() < 0.03);
        assert_eq!(summary.max_seconds, 3.0);
    }

    #[test]
    fn overlapping_timeline_scopes_have_distinct_lanes() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let (layer, mut guard) =
            TimingLayer::new("timeline".into(), None, Some(file.reopen().unwrap()));
        let subscriber =
            tracing_subscriber::registry().with(layer.with_filter(timing_filter(false)));
        tracing::subscriber::with_default(subscriber, || {
            let first = crate::timing_scope!("overlap");
            let second = crate::timing_scope!("overlap");
            first.finish();
            drop(second);
        });
        guard.finish().unwrap();
        let events: serde_json::Value = serde_json::from_reader(file.reopen().unwrap()).unwrap();
        let events = events.as_array().unwrap();
        assert_eq!(events.len(), 2);
        assert_ne!(events[0]["tid"], events[1]["tid"]);
        assert_eq!(events[0]["ph"], "X");
        assert_eq!(events[0]["args"]["finished"], true);
        assert_eq!(events[1]["args"]["finished"], false);
    }

    #[test]
    fn sequential_timeline_scopes_reuse_lanes_while_another_scope_stays_active() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let (layer, mut guard) =
            TimingLayer::new("timeline".into(), None, Some(file.reopen().unwrap()));
        let subscriber =
            tracing_subscriber::registry().with(layer.with_filter(timing_filter(false)));
        tracing::subscriber::with_default(subscriber, || {
            let outer = crate::timing_scope!("outer");
            for _ in 0..64 {
                crate::timing_scope!("sequential").finish();
            }
            drop(outer);
        });
        guard.finish().unwrap();
        let events: serde_json::Value = serde_json::from_reader(file.reopen().unwrap()).unwrap();
        let events = events.as_array().unwrap();
        assert_eq!(events.len(), 65);
        let sequential_lane = &events[0]["tid"];
        for event in &events[..64] {
            assert_eq!(&event["tid"], sequential_lane);
        }
        assert_ne!(&events[64]["tid"], sequential_lane);
    }

    #[test]
    fn delayed_scope_registration_cannot_reuse_an_overlapping_lane() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let (_, guard) = TimingLayer::new("timeline".into(), None, Some(file.reopen().unwrap()));
        let mut state = guard.state.lock().unwrap();
        let start = state.epoch;
        let first_lane = state.allocate_lane(start);
        state.record(
            ActiveScope {
                name: "first",
                start,
                lane: first_lane,
            },
            true,
            start + std::time::Duration::from_secs(2),
        );
        let overlapping_lane = state.allocate_lane(start + std::time::Duration::from_secs(1));
        assert_ne!(overlapping_lane, first_lane);
        let later_lane = state.allocate_lane(start + std::time::Duration::from_secs(3));
        assert_eq!(later_lane, first_lane);
    }

    #[test]
    fn summary_only_scopes_do_not_allocate_timeline_lanes() {
        let (dispatch, guard, _file) = collector(false);
        tracing::dispatcher::with_default(&dispatch, || {
            for _ in 0..64 {
                crate::timing_scope!("summary").finish();
            }
        });
        let state = guard.state.lock().unwrap();
        assert_eq!(state.next_lane, 0);
        assert_eq!(state.aggregates["summary"].finished, 64);
    }

    #[test]
    fn output_write_failures_are_returned() {
        let file = std::fs::OpenOptions::new()
            .write(true)
            .open("/dev/full")
            .unwrap();
        let (_, mut guard) = TimingLayer::new("unwritable".into(), Some(file), None);
        assert!(guard.finish().is_err());
    }

    #[test]
    fn empty_outputs_are_valid_and_finalization_is_idempotent() {
        let summary = tempfile::NamedTempFile::new().unwrap();
        let timeline = tempfile::NamedTempFile::new().unwrap();
        let (_, mut guard) = TimingLayer::new(
            "empty".into(),
            Some(summary.reopen().unwrap()),
            Some(timeline.reopen().unwrap()),
        );
        guard.finish().unwrap();
        guard.finish().unwrap();
        let result: serde_json::Value = serde_json::from_reader(summary.reopen().unwrap()).unwrap();
        assert_eq!(result["scopes"], serde_json::json!([]));
        let events: serde_json::Value =
            serde_json::from_reader(timeline.reopen().unwrap()).unwrap();
        assert_eq!(events, serde_json::json!([]));
    }

    #[test]
    fn extra_scope_names_fold_into_bounded_overflow_bucket() {
        let (dispatch, mut guard, file) = collector(false);
        drop(dispatch);
        {
            let mut state = guard.state.lock().unwrap();
            for index in 0..300 {
                let name = Box::leak(format!("scope-{index}").into_boxed_str());
                let start = std::time::Instant::now();
                state.record(
                    ActiveScope {
                        name,
                        start,
                        lane: index,
                    },
                    true,
                    start,
                );
            }
        }
        let result = report(&mut guard, &file);
        let scopes = result["scopes"].as_array().unwrap();
        assert_eq!(scopes.len(), 256);
        assert_eq!(
            scopes
                .iter()
                .map(|scope| scope["count"].as_u64().unwrap())
                .sum::<u64>(),
            300
        );
        let overflow = scopes
            .iter()
            .find(|scope| scope["name"] == "__overflow__")
            .unwrap();
        assert_eq!(overflow["count"], 45);
    }

    #[test]
    fn elapsed_timeline_write_failures_are_returned() {
        let file = std::fs::OpenOptions::new()
            .write(true)
            .open("/dev/full")
            .unwrap();
        let (layer, mut guard) = TimingLayer::new("unwritable".into(), None, Some(file));
        let subscriber =
            tracing_subscriber::registry().with(layer.with_filter(timing_filter(false)));
        tracing::subscriber::with_default(subscriber, || crate::timing_scope!("scope").finish());
        assert!(guard.finish().is_err());
    }
}