1use anyhow::Context;
10use serde::Serialize;
11use std::io::Write;
12
13pub(crate) mod metadata;
14
15const TARGET: &str = "rcp::timing";
16const FINISHED_FIELD: &str = "timing_finished";
17const MAX_SCOPES: usize = 256;
18const MAX_HISTOGRAM_MICROS: u64 = 1 << 56;
19
20#[macro_export]
32macro_rules! timing_scope {
33 ($name:literal) => {
34 $crate::timing::Scope::new(tracing::info_span!(
35 target: "rcp::timing", $name, timing_finished = tracing::field::Empty
36 ))
37 };
38 (trace, $name:literal) => {
39 $crate::timing::Scope::new(tracing::trace_span!(
40 target: "rcp::timing", $name, timing_finished = tracing::field::Empty
41 ))
42 };
43}
44
45#[must_use = "keep the timing scope alive until the measured work finishes"]
47pub struct Scope {
48 span: Option<tracing::Span>,
49}
50
51impl Scope {
52 #[doc(hidden)]
54 pub fn new(span: tracing::Span) -> Self {
55 Self { span: Some(span) }
56 }
57
58 fn span(&self) -> &tracing::Span {
60 self.span.as_ref().expect("scope has not finished")
61 }
62
63 pub async fn measure<F: std::future::Future>(self, future: F) -> F::Output {
66 use tracing::Instrument;
67 let output = future.instrument(self.span().clone()).await;
68 self.finish();
69 output
70 }
71
72 pub fn finish(mut self) {
74 if let Some(span) = self.span.take() {
75 span.record(FINISHED_FIELD, true);
76 }
77 }
78}
79
80impl Drop for Scope {
81 fn drop(&mut self) {
82 if let Some(span) = self.span.take() {
83 span.record(FINISHED_FIELD, false);
84 }
85 }
86}
87
88pub(crate) fn timing_filter(detail: bool) -> tracing_subscriber::filter::Targets {
89 tracing_subscriber::filter::Targets::new().with_target(
90 TARGET,
91 if detail {
92 tracing::Level::TRACE
93 } else {
94 tracing::Level::INFO
95 },
96 )
97}
98
99struct ActiveScope {
100 name: &'static str,
101 start: std::time::Instant,
102 lane: u64,
103}
104
105struct Aggregate {
106 finished: u64,
107 interrupted: u64,
108 total: std::time::Duration,
109 max: std::time::Duration,
110 histogram: hdrhistogram::Histogram<u64>,
111}
112
113impl Default for Aggregate {
114 fn default() -> Self {
115 Self {
116 finished: 0,
117 interrupted: 0,
118 total: std::time::Duration::ZERO,
119 max: std::time::Duration::ZERO,
120 histogram: hdrhistogram::Histogram::new_with_bounds(1, MAX_HISTOGRAM_MICROS, 2)
121 .expect("valid fixed histogram bounds"),
122 }
123 }
124}
125
126impl Aggregate {
127 fn record(&mut self, elapsed: std::time::Duration, finished: bool) {
128 if finished {
129 self.finished += 1;
130 } else {
131 self.interrupted += 1;
132 }
133 self.total = self.total.saturating_add(elapsed);
134 self.max = self.max.max(elapsed);
135 let micros = elapsed.as_micros().min(u128::from(MAX_HISTOGRAM_MICROS)) as u64;
136 self.histogram
137 .record(micros)
138 .expect("sample is within fixed bounds");
139 }
140
141 fn summary(&self, name: &'static str) -> ScopeSummary {
142 let count = self.finished + self.interrupted;
143 ScopeSummary {
144 name,
145 count,
146 finished: self.finished,
147 interrupted: self.interrupted,
148 total_seconds: self.total.as_secs_f64(),
149 mean_seconds: self.total.as_secs_f64() / count as f64,
150 p50_seconds: self.histogram.value_at_quantile(0.5) as f64 / 1_000_000.0,
151 p95_seconds: self.histogram.value_at_quantile(0.95) as f64 / 1_000_000.0,
152 max_seconds: self.max.as_secs_f64(),
153 }
154 }
155}
156
157#[derive(Serialize)]
158struct ScopeSummary {
159 name: &'static str,
160 count: u64,
161 finished: u64,
162 interrupted: u64,
163 total_seconds: f64,
164 mean_seconds: f64,
165 p50_seconds: f64,
166 p95_seconds: f64,
167 max_seconds: f64,
168}
169
170#[derive(Serialize)]
171struct Summary<'a> {
172 schema_version: u8,
173 identifier: &'a str,
174 pid: u32,
175 scopes: Vec<ScopeSummary>,
176}
177
178struct State {
179 identifier: String,
180 epoch: std::time::Instant,
181 next_lane: u64,
182 available_lanes: std::collections::BinaryHeap<std::cmp::Reverse<(std::time::Instant, u64)>>,
183 aggregates: std::collections::BTreeMap<&'static str, Aggregate>,
184 summary: Option<std::fs::File>,
185 timeline: Option<std::io::BufWriter<std::fs::File>>,
186 timeline_started: bool,
187 error: Option<anyhow::Error>,
188 finalized: bool,
189}
190
191impl State {
192 fn allocate_lane(&mut self, start: std::time::Instant) -> u64 {
193 if self.timeline.is_none() {
194 return 0;
195 }
196 if let Some(std::cmp::Reverse((end, _))) = self.available_lanes.peek()
198 && *end <= start
199 {
200 return self.available_lanes.pop().unwrap().0.1;
201 }
202 self.next_lane += 1;
203 self.next_lane
204 }
205
206 fn record(&mut self, scope: ActiveScope, finished: bool, end: std::time::Instant) {
207 if self.finalized {
208 return;
209 }
210 let elapsed = end.duration_since(scope.start);
211 if self.summary.is_some() {
212 let name = if self.aggregates.contains_key(scope.name)
213 || self.aggregates.len() < MAX_SCOPES - 1
214 {
215 scope.name
216 } else {
217 "__overflow__"
218 };
219 self.aggregates
220 .entry(name)
221 .or_default()
222 .record(elapsed, finished);
223 }
224 if let Some(timeline) = &mut self.timeline {
225 let event = serde_json::json!({
226 "name": scope.name, "cat": TARGET, "ph": "X",
227 "pid": std::process::id(), "tid": scope.lane,
228 "ts": scope.start.duration_since(self.epoch).as_secs_f64() * 1_000_000.0,
229 "dur": elapsed.as_secs_f64() * 1_000_000.0,
230 "args": { "identifier": self.identifier, "finished": finished }
231 });
232 let separator: &[u8] = if self.timeline_started {
233 b",\n"
234 } else {
235 b"[\n"
236 };
237 let result = timeline
238 .write_all(separator)
239 .map_err(anyhow::Error::from)
240 .and_then(|()| serde_json::to_writer(timeline, &event).map_err(Into::into));
241 self.timeline_started = true;
242 if self.error.is_none() {
243 self.error = result.err();
244 }
245 self.available_lanes
246 .push(std::cmp::Reverse((end, scope.lane)));
247 }
248 }
249}
250
251pub(crate) struct TimingLayer {
252 state: std::sync::Arc<std::sync::Mutex<State>>,
253 timeline_enabled: bool,
254}
255
256impl TimingLayer {
257 pub(crate) fn new(
258 identifier: String,
259 summary: Option<std::fs::File>,
260 timeline: Option<std::fs::File>,
261 ) -> (Self, TimingGuard) {
262 let timeline_enabled = timeline.is_some();
263 let state = std::sync::Arc::new(std::sync::Mutex::new(State {
264 identifier,
265 epoch: std::time::Instant::now(),
266 next_lane: 0,
267 available_lanes: std::collections::BinaryHeap::new(),
268 aggregates: std::collections::BTreeMap::new(),
269 summary,
270 timeline: timeline.map(std::io::BufWriter::new),
271 timeline_started: false,
272 error: None,
273 finalized: false,
274 }));
275 (
276 Self {
277 state: state.clone(),
278 timeline_enabled,
279 },
280 TimingGuard { state },
281 )
282 }
283}
284
285#[derive(Default)]
286struct Completion(Option<bool>);
287
288impl tracing::field::Visit for Completion {
289 fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
290 if field.name() == FINISHED_FIELD {
291 self.0 = Some(value);
292 }
293 }
294 fn record_debug(&mut self, _: &tracing::field::Field, _: &dyn std::fmt::Debug) {}
295}
296
297impl<S> tracing_subscriber::Layer<S> for TimingLayer
298where
299 S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
300{
301 fn on_new_span(
302 &self,
303 attributes: &tracing::span::Attributes<'_>,
304 id: &tracing::span::Id,
305 context: tracing_subscriber::layer::Context<'_, S>,
306 ) {
307 if attributes.metadata().target() != TARGET
308 || attributes
309 .metadata()
310 .fields()
311 .field(FINISHED_FIELD)
312 .is_none()
313 {
314 return;
315 }
316 let start = std::time::Instant::now();
317 let lane = if self.timeline_enabled {
318 let mut state = self
319 .state
320 .lock()
321 .unwrap_or_else(std::sync::PoisonError::into_inner);
322 state.allocate_lane(start)
323 } else {
324 0
325 };
326 if let Some(span) = context.span(id) {
327 span.extensions_mut().insert(ActiveScope {
328 name: attributes.metadata().name(),
329 start,
330 lane,
331 });
332 }
333 }
334
335 fn on_record(
336 &self,
337 id: &tracing::span::Id,
338 values: &tracing::span::Record<'_>,
339 context: tracing_subscriber::layer::Context<'_, S>,
340 ) {
341 let mut completion = Completion::default();
342 values.record(&mut completion);
343 if let Some(finished) = completion.0
344 && let Some(span) = context.span(id)
345 {
346 let scope = span.extensions_mut().remove::<ActiveScope>();
347 if let Some(scope) = scope {
348 let end = std::time::Instant::now();
349 self.state
350 .lock()
351 .unwrap_or_else(std::sync::PoisonError::into_inner)
352 .record(scope, finished, end);
353 }
354 }
355 }
356}
357
358pub(crate) struct TimingGuard {
359 state: std::sync::Arc<std::sync::Mutex<State>>,
360}
361
362impl TimingGuard {
363 pub(crate) fn finish(&mut self) -> anyhow::Result<()> {
364 let mut state = self
365 .state
366 .lock()
367 .unwrap_or_else(std::sync::PoisonError::into_inner);
368 if state.finalized {
369 return Ok(());
370 }
371 state.finalized = true;
372 let mut error = state.error.take();
373 if let Some(file) = state.summary.take() {
374 let summary = Summary {
375 schema_version: 1,
376 identifier: &state.identifier,
377 pid: std::process::id(),
378 scopes: state
379 .aggregates
380 .iter()
381 .map(|(&name, aggregate)| aggregate.summary(name))
382 .collect(),
383 };
384 let mut writer = std::io::BufWriter::new(file);
385 let result = serde_json::to_writer_pretty(&mut writer, &summary)
386 .context("failed to write timing summary")
387 .and_then(|()| writer.flush().context("failed to flush timing summary"));
388 if error.is_none() {
389 error = result.err();
390 }
391 }
392 if let Some(mut timeline) = state.timeline.take() {
393 let closing: &[u8] = if state.timeline_started {
394 b"\n]\n"
395 } else {
396 b"[]\n"
397 };
398 let result = timeline
399 .write_all(closing)
400 .and_then(|()| timeline.flush())
401 .context("failed to flush elapsed scope timeline");
402 if error.is_none() {
403 error = result.err();
404 }
405 }
406 match error {
407 Some(error) => Err(error),
408 None => Ok(()),
409 }
410 }
411}
412
413impl Drop for TimingGuard {
414 fn drop(&mut self) {
415 if let Err(error) = self.finish() {
416 eprintln!("Failed to write scoped timings: {error:#}");
417 }
418 }
419}
420
421#[cfg(test)]
422mod tests {
423 use super::*;
424 use tracing_subscriber::prelude::*;
425
426 fn collector(detail: bool) -> (tracing::Dispatch, TimingGuard, tempfile::NamedTempFile) {
427 let file = tempfile::NamedTempFile::new().unwrap();
428 let (layer, guard) =
429 TimingLayer::new("test-role".into(), Some(file.reopen().unwrap()), None);
430 let subscriber =
431 tracing_subscriber::registry().with(layer.with_filter(timing_filter(detail)));
432 (tracing::Dispatch::new(subscriber), guard, file)
433 }
434
435 fn report(guard: &mut TimingGuard, file: &tempfile::NamedTempFile) -> serde_json::Value {
436 guard.finish().unwrap();
437 serde_json::from_reader(file.reopen().unwrap()).unwrap()
438 }
439
440 #[test]
441 fn finished_scope_is_recorded_before_clones_and_children_drop() {
442 tracing::subscriber::with_default(tracing_subscriber::registry(), || {
444 let (dispatch, mut guard, file) = collector(false);
445 tracing::dispatcher::with_default(&dispatch, || {
446 let scope = crate::timing_scope!("parent");
447 let clone = scope.span().clone();
448 let child =
449 tracing::info_span!(target: "rcp::timing", parent: scope.span(), "child");
450 scope.finish();
451 let result = report(&mut guard, &file);
452 assert_eq!(result["schema_version"], 1);
453 assert_eq!(result["identifier"], "test-role");
454 assert_eq!(result["pid"], std::process::id());
455 assert_eq!(result["scopes"].as_array().unwrap().len(), 1);
456 assert_eq!(result["scopes"][0]["count"], 1);
457 assert_eq!(result["scopes"][0]["finished"], 1);
458 assert_eq!(result["scopes"][0]["interrupted"], 0);
459 drop((clone, child));
461 });
462 });
463 }
464
465 #[test]
466 fn scope_drop_records_interruption_with_original_subscriber() {
467 let (dispatch, mut guard, file) = collector(false);
468 let scope =
469 tracing::dispatcher::with_default(&dispatch, || crate::timing_scope!("dropped"));
470 drop(scope);
471 let result = report(&mut guard, &file);
472 assert_eq!(result["scopes"][0]["count"], 1);
473 assert_eq!(result["scopes"][0]["finished"], 0);
474 assert_eq!(result["scopes"][0]["interrupted"], 1);
475 }
476
477 #[test]
478 fn detail_scopes_require_explicit_enablement() {
479 for detail in [false, true] {
480 let (dispatch, mut guard, file) = collector(detail);
481 tracing::dispatcher::with_default(&dispatch, || {
482 crate::timing_scope!("coarse").finish();
483 crate::timing_scope!(trace, "detail").finish();
484 });
485 let result = report(&mut guard, &file);
486 assert_eq!(
487 result["scopes"].as_array().unwrap().len(),
488 if detail { 2 } else { 1 }
489 );
490 }
491 }
492
493 #[test]
494 fn elapsed_time_includes_async_suspension_and_cancellation() {
495 let (dispatch, mut guard, file) = collector(false);
496 let runtime = tokio::runtime::Builder::new_current_thread()
497 .enable_time()
498 .build()
499 .unwrap();
500 tracing::dispatcher::with_default(&dispatch, || {
501 runtime.block_on(async {
502 let scope = crate::timing_scope!("suspension");
503 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
504 scope.finish();
505 let task = tokio::spawn(async {
506 let _scope = crate::timing_scope!("cancellation");
507 std::future::pending::<()>().await;
508 });
509 tokio::task::yield_now().await;
510 task.abort();
511 assert!(task.await.unwrap_err().is_cancelled());
512 })
513 });
514 let result = report(&mut guard, &file);
515 let scopes = result["scopes"].as_array().unwrap();
516 let suspended = scopes.iter().find(|s| s["name"] == "suspension").unwrap();
517 assert!(suspended["total_seconds"].as_f64().unwrap() >= 0.015);
518 let cancelled = scopes.iter().find(|s| s["name"] == "cancellation").unwrap();
519 assert_eq!(cancelled["interrupted"], 1);
520 }
521
522 #[test]
523 fn measured_error_results_are_finished_and_cancelled_futures_are_interrupted() {
524 let (dispatch, mut guard, file) = collector(false);
525 let runtime = tokio::runtime::Builder::new_current_thread()
526 .build()
527 .unwrap();
528 tracing::dispatcher::with_default(&dispatch, || {
529 runtime.block_on(async {
530 let result = crate::timing_scope!("error-result")
531 .measure(async { Err::<(), _>("failed") })
532 .await;
533 assert_eq!(result, Err("failed"));
534 let task = tokio::spawn(
535 crate::timing_scope!("cancelled-future").measure(std::future::pending::<()>()),
536 );
537 tokio::task::yield_now().await;
538 task.abort();
539 assert!(task.await.unwrap_err().is_cancelled());
540 })
541 });
542 let result = report(&mut guard, &file);
543 let scopes = result["scopes"].as_array().unwrap();
544 assert_eq!(
545 scopes.iter().find(|s| s["name"] == "error-result").unwrap()["finished"],
546 1
547 );
548 assert_eq!(
549 scopes
550 .iter()
551 .find(|s| s["name"] == "cancelled-future")
552 .unwrap()["interrupted"],
553 1
554 );
555 }
556
557 #[test]
558 fn concurrent_scopes_keep_exact_counts() {
559 let (dispatch, mut guard, file) = collector(false);
560 std::thread::scope(|threads| {
561 for _ in 0..8 {
562 threads.spawn(|| {
563 tracing::dispatcher::with_default(&dispatch, || {
564 for _ in 0..100 {
565 crate::timing_scope!("parallel").finish();
566 drop(crate::timing_scope!("parallel"));
567 }
568 })
569 });
570 }
571 });
572 let result = report(&mut guard, &file);
573 assert_eq!(result["scopes"][0]["count"], 1600);
574 assert_eq!(result["scopes"][0]["finished"], 800);
575 assert_eq!(result["scopes"][0]["interrupted"], 800);
576 }
577
578 #[test]
579 fn summary_distribution_includes_interrupted_samples() {
580 let mut aggregate = Aggregate::default();
581 aggregate.record(std::time::Duration::from_secs(1), true);
582 aggregate.record(std::time::Duration::from_secs(3), false);
583 let summary = aggregate.summary("distribution");
584 assert_eq!(summary.count, 2);
585 assert_eq!(summary.total_seconds, 4.0);
586 assert_eq!(summary.mean_seconds, 2.0);
587 assert!((summary.p50_seconds - 1.0).abs() < 0.01);
588 assert!((summary.p95_seconds - 3.0).abs() < 0.03);
589 assert_eq!(summary.max_seconds, 3.0);
590 }
591
592 #[test]
593 fn overlapping_timeline_scopes_have_distinct_lanes() {
594 let file = tempfile::NamedTempFile::new().unwrap();
595 let (layer, mut guard) =
596 TimingLayer::new("timeline".into(), None, Some(file.reopen().unwrap()));
597 let subscriber =
598 tracing_subscriber::registry().with(layer.with_filter(timing_filter(false)));
599 tracing::subscriber::with_default(subscriber, || {
600 let first = crate::timing_scope!("overlap");
601 let second = crate::timing_scope!("overlap");
602 first.finish();
603 drop(second);
604 });
605 guard.finish().unwrap();
606 let events: serde_json::Value = serde_json::from_reader(file.reopen().unwrap()).unwrap();
607 let events = events.as_array().unwrap();
608 assert_eq!(events.len(), 2);
609 assert_ne!(events[0]["tid"], events[1]["tid"]);
610 assert_eq!(events[0]["ph"], "X");
611 assert_eq!(events[0]["args"]["finished"], true);
612 assert_eq!(events[1]["args"]["finished"], false);
613 }
614
615 #[test]
616 fn sequential_timeline_scopes_reuse_lanes_while_another_scope_stays_active() {
617 let file = tempfile::NamedTempFile::new().unwrap();
618 let (layer, mut guard) =
619 TimingLayer::new("timeline".into(), None, Some(file.reopen().unwrap()));
620 let subscriber =
621 tracing_subscriber::registry().with(layer.with_filter(timing_filter(false)));
622 tracing::subscriber::with_default(subscriber, || {
623 let outer = crate::timing_scope!("outer");
624 for _ in 0..64 {
625 crate::timing_scope!("sequential").finish();
626 }
627 drop(outer);
628 });
629 guard.finish().unwrap();
630 let events: serde_json::Value = serde_json::from_reader(file.reopen().unwrap()).unwrap();
631 let events = events.as_array().unwrap();
632 assert_eq!(events.len(), 65);
633 let sequential_lane = &events[0]["tid"];
634 for event in &events[..64] {
635 assert_eq!(&event["tid"], sequential_lane);
636 }
637 assert_ne!(&events[64]["tid"], sequential_lane);
638 }
639
640 #[test]
641 fn delayed_scope_registration_cannot_reuse_an_overlapping_lane() {
642 let file = tempfile::NamedTempFile::new().unwrap();
643 let (_, guard) = TimingLayer::new("timeline".into(), None, Some(file.reopen().unwrap()));
644 let mut state = guard.state.lock().unwrap();
645 let start = state.epoch;
646 let first_lane = state.allocate_lane(start);
647 state.record(
648 ActiveScope {
649 name: "first",
650 start,
651 lane: first_lane,
652 },
653 true,
654 start + std::time::Duration::from_secs(2),
655 );
656 let overlapping_lane = state.allocate_lane(start + std::time::Duration::from_secs(1));
657 assert_ne!(overlapping_lane, first_lane);
658 let later_lane = state.allocate_lane(start + std::time::Duration::from_secs(3));
659 assert_eq!(later_lane, first_lane);
660 }
661
662 #[test]
663 fn summary_only_scopes_do_not_allocate_timeline_lanes() {
664 let (dispatch, guard, _file) = collector(false);
665 tracing::dispatcher::with_default(&dispatch, || {
666 for _ in 0..64 {
667 crate::timing_scope!("summary").finish();
668 }
669 });
670 let state = guard.state.lock().unwrap();
671 assert_eq!(state.next_lane, 0);
672 assert_eq!(state.aggregates["summary"].finished, 64);
673 }
674
675 #[test]
676 fn output_write_failures_are_returned() {
677 let file = std::fs::OpenOptions::new()
678 .write(true)
679 .open("/dev/full")
680 .unwrap();
681 let (_, mut guard) = TimingLayer::new("unwritable".into(), Some(file), None);
682 assert!(guard.finish().is_err());
683 }
684
685 #[test]
686 fn empty_outputs_are_valid_and_finalization_is_idempotent() {
687 let summary = tempfile::NamedTempFile::new().unwrap();
688 let timeline = tempfile::NamedTempFile::new().unwrap();
689 let (_, mut guard) = TimingLayer::new(
690 "empty".into(),
691 Some(summary.reopen().unwrap()),
692 Some(timeline.reopen().unwrap()),
693 );
694 guard.finish().unwrap();
695 guard.finish().unwrap();
696 let result: serde_json::Value = serde_json::from_reader(summary.reopen().unwrap()).unwrap();
697 assert_eq!(result["scopes"], serde_json::json!([]));
698 let events: serde_json::Value =
699 serde_json::from_reader(timeline.reopen().unwrap()).unwrap();
700 assert_eq!(events, serde_json::json!([]));
701 }
702
703 #[test]
704 fn extra_scope_names_fold_into_bounded_overflow_bucket() {
705 let (dispatch, mut guard, file) = collector(false);
706 drop(dispatch);
707 {
708 let mut state = guard.state.lock().unwrap();
709 for index in 0..300 {
710 let name = Box::leak(format!("scope-{index}").into_boxed_str());
711 let start = std::time::Instant::now();
712 state.record(
713 ActiveScope {
714 name,
715 start,
716 lane: index,
717 },
718 true,
719 start,
720 );
721 }
722 }
723 let result = report(&mut guard, &file);
724 let scopes = result["scopes"].as_array().unwrap();
725 assert_eq!(scopes.len(), 256);
726 assert_eq!(
727 scopes
728 .iter()
729 .map(|scope| scope["count"].as_u64().unwrap())
730 .sum::<u64>(),
731 300
732 );
733 let overflow = scopes
734 .iter()
735 .find(|scope| scope["name"] == "__overflow__")
736 .unwrap();
737 assert_eq!(overflow["count"], 45);
738 }
739
740 #[test]
741 fn elapsed_timeline_write_failures_are_returned() {
742 let file = std::fs::OpenOptions::new()
743 .write(true)
744 .open("/dev/full")
745 .unwrap();
746 let (layer, mut guard) = TimingLayer::new("unwritable".into(), None, Some(file));
747 let subscriber =
748 tracing_subscriber::registry().with(layer.with_filter(timing_filter(false)));
749 tracing::subscriber::with_default(subscriber, || crate::timing_scope!("scope").finish());
750 assert!(guard.finish().is_err());
751 }
752}