-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathanalysis.rs
More file actions
1630 lines (1532 loc) · 57.8 KB
/
analysis.rs
File metadata and controls
1630 lines (1532 loc) · 57.8 KB
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::telemetry::events::{CpuSampleSource, TelemetryEvent};
use crate::telemetry::format::{self, TelemetryEventRef, WorkerId};
use crate::telemetry::task_metadata::TaskId;
use dial9_trace_format::FieldValue;
use dial9_trace_format::InternedString;
use dial9_trace_format::decoder::{Decoder, StringPool};
use std::cmp::Reverse;
use std::collections::HashMap;
use std::io::{Read as _, Result};
/// Reads a trace file written in the `dial9-trace-format` binary format.
///
/// Decodes the entire file eagerly and populates lookup tables for spawn
/// locations (from the string pool), task→spawn-location mappings, callframe
/// symbols, thread names, and segment metadata.
#[derive(Debug)]
pub struct TraceReader {
/// All decoded events (including metadata like TaskSpawn).
pub all_events: Vec<TelemetryEvent>,
/// Runtime events only (excludes TaskSpawn, ThreadNameDef, SegmentMetadata).
pub runtime_events: Vec<TelemetryEvent>,
/// Spawn location strings keyed by `InternedString` from the string pool.
pub spawn_locations: HashMap<InternedString, String>,
/// Task ID → spawn location mapping built from TaskSpawn events.
pub task_spawn_locs: HashMap<TaskId, InternedString>,
/// OS tid → thread name mapping built from ThreadNameDef events.
pub thread_names: HashMap<u32, String>,
/// Key-value metadata from the most recent SegmentMetadata event.
pub segment_metadata: Vec<(String, String)>,
}
impl TraceReader {
/// Read and decode a trace file at the given path.
pub fn new(path: &str) -> Result<Self> {
let data = read_trace_file(path)?;
let mut dec = Decoder::new(&data).ok_or_else(|| {
std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid trace header")
})?;
let mut spawn_locations = HashMap::new();
let mut task_spawn_locs = HashMap::new();
let mut thread_names = HashMap::new();
let mut segment_metadata = Vec::new();
let mut events = Vec::new();
// Resolve InternedString fields (spawn_loc, thread_name) inside the
// callback where the string pool is still valid for the current batch.
// After a mid-stream header the pool resets, so deferred resolution
// would use the wrong pool for earlier batches.
dec.for_each_event(|ev| {
if let Some(r) = format::decode_ref(ev.name, ev.timestamp_ns, ev.fields, ev.schema) {
match &r {
TelemetryEventRef::PollStart(e) => {
populate_spawn_loc(&mut spawn_locations, e.spawn_loc, ev.string_pool);
}
TelemetryEventRef::TaskSpawn(e) => {
populate_spawn_loc(&mut spawn_locations, e.spawn_loc, ev.string_pool);
task_spawn_locs.insert(e.task_id, e.spawn_loc);
}
TelemetryEventRef::SegmentMetadata(e) => {
segment_metadata = e
.entries
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
}
_ => {}
}
let owned = format::to_owned_event(r, ev.string_pool, ev.stack_pool);
if let TelemetryEvent::CpuSample {
tid,
thread_name: Some(ref name),
..
} = owned
{
thread_names.insert(tid, name.clone());
}
events.push(owned);
} else {
// Unknown event name: capture as Custom, resolving any
// pooled fields to owned data while the segment-local pools
// are still available.
let fields = ev
.field_names()
.zip(ev.fields.iter())
.map(|(name, val)| {
let owned = match val {
dial9_trace_format::types::FieldValueRef::PooledString(id) => {
let s = ev
.string_pool
.get(*id)
.unwrap_or("<unresolved>")
.to_string();
FieldValue::String(s)
}
dial9_trace_format::types::FieldValueRef::PooledStackFrames(id) => {
let frames = ev
.stack_pool
.get(*id)
.expect("stack pool entry must exist for PooledStackFrames")
.to_vec();
FieldValue::StackFrames(frames.into())
}
other => other.to_owned(),
};
(name.to_string(), owned)
})
.collect();
events.push(TelemetryEvent::Custom {
timestamp_nanos: ev.timestamp_ns,
name: ev.name.to_string(),
fields,
});
}
})
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;
let all_events: Vec<TelemetryEvent> = events;
let runtime_events = all_events
.iter()
.filter(|e| {
!matches!(
e,
TelemetryEvent::TaskSpawn { .. }
| TelemetryEvent::ThreadNameDef { .. }
| TelemetryEvent::SegmentMetadata { .. }
| TelemetryEvent::ClockSync { .. }
)
})
.cloned()
.collect();
Ok(Self {
all_events,
runtime_events,
spawn_locations,
task_spawn_locs,
thread_names,
segment_metadata,
})
}
}
fn read_trace_file(path: &str) -> Result<Vec<u8>> {
let data = std::fs::read(path)?;
maybe_decompress_gzip(data)
}
fn maybe_decompress_gzip(data: Vec<u8>) -> Result<Vec<u8>> {
const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b];
if !data.starts_with(&GZIP_MAGIC) {
return Ok(data);
}
let mut decoder = flate2::read::GzDecoder::new(&data[..]);
let mut decompressed = Vec::new();
decoder.read_to_end(&mut decompressed).map_err(|error| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("failed to decompress gzip trace: {error}"),
)
})?;
Ok(decompressed)
}
fn populate_spawn_loc(
map: &mut HashMap<InternedString, String>,
interned: dial9_trace_format::InternedString,
pool: &StringPool,
) {
if !map.contains_key(&interned)
&& let Some(s) = pool.get(interned)
{
map.insert(interned, s.to_string());
}
}
/// Aggregated statistics for a single Tokio worker thread.
#[derive(Debug, Default)]
pub struct WorkerStats {
/// Number of task polls executed by this worker.
pub poll_count: usize,
/// Number of times this worker parked (went idle).
pub park_count: usize,
/// Number of times this worker was unparked (resumed).
pub unpark_count: usize,
/// Cumulative time spent polling tasks, in nanoseconds.
pub total_poll_time_ns: u64,
/// Maximum observed local queue depth for this worker.
pub max_local_queue: usize,
/// Maximum OS scheduling wait observed during any single unpark, in nanoseconds.
pub max_sched_wait_ns: u64,
/// Cumulative OS scheduling wait across all unparks, in nanoseconds.
pub total_sched_wait_ns: u64,
}
/// Aggregated poll statistics for a single spawn location.
#[derive(Debug, Default)]
pub struct SpawnLocationStats {
/// Number of polls from tasks spawned at this location.
pub poll_count: usize,
/// Cumulative poll time for tasks from this location, in nanoseconds.
pub total_poll_time_ns: u64,
}
/// Summary of a decoded trace: event counts, timing, and per-worker statistics.
#[derive(Debug)]
pub struct TraceAnalysis {
/// Total number of events in the trace.
pub total_events: usize,
/// Wall-clock duration of the trace in nanoseconds.
pub duration_ns: u64,
/// Per-worker aggregated statistics.
pub worker_stats: HashMap<WorkerId, WorkerStats>,
/// Maximum observed global queue depth across all samples.
pub max_global_queue: usize,
/// Average global queue depth across all samples.
pub avg_global_queue: f64,
/// Per-spawn-location statistics (only populated when task tracking is enabled).
pub spawn_location_stats: HashMap<InternedString, SpawnLocationStats>,
}
/// Build a sorted list of (timestamp, global_queue_depth) from QueueSample events.
fn build_global_queue_timeline(events: &[TelemetryEvent]) -> Vec<(u64, usize)> {
let mut timeline: Vec<(u64, usize)> = events
.iter()
.filter_map(|e| match e {
TelemetryEvent::QueueSample {
timestamp_nanos,
global_queue_depth,
} => Some((*timestamp_nanos, *global_queue_depth)),
_ => None,
})
.collect();
timeline.sort_by_key(|&(ts, _)| ts);
timeline
}
/// Look up the most recent global queue depth at or before the given timestamp.
/// Returns 0 if no sample has been recorded yet.
fn lookup_global_queue_depth(timeline: &[(u64, usize)], timestamp: u64) -> usize {
match timeline.binary_search_by_key(×tamp, |&(ts, _)| ts) {
Ok(idx) => timeline[idx].1,
Err(0) => 0,
Err(idx) => timeline[idx - 1].1,
}
}
/// Analyze a slice of telemetry events and produce a [`TraceAnalysis`] summary.
pub fn analyze_trace(events: &[TelemetryEvent]) -> TraceAnalysis {
let mut worker_stats: HashMap<WorkerId, WorkerStats> = HashMap::new();
let mut poll_starts: HashMap<WorkerId, u64> = HashMap::new();
// Track spawn_loc at PollStart for computing per-location poll time at PollEnd
let mut poll_start_locs: HashMap<WorkerId, InternedString> = HashMap::new();
let mut spawn_location_stats: HashMap<InternedString, SpawnLocationStats> = HashMap::new();
let mut max_global_queue = 0;
let mut global_queue_sum = 0u64;
let mut global_queue_count = 0u64;
let start_time = events
.first()
.and_then(|e| e.timestamp_nanos())
.unwrap_or(0);
let end_time = events.last().and_then(|e| e.timestamp_nanos()).unwrap_or(0);
for event in events {
match event {
TelemetryEvent::QueueSample {
global_queue_depth, ..
} => {
max_global_queue = max_global_queue.max(*global_queue_depth);
global_queue_sum += *global_queue_depth as u64;
global_queue_count += 1;
}
TelemetryEvent::PollStart {
timestamp_nanos,
worker_id,
worker_local_queue_depth,
spawn_loc,
..
} => {
let stats = worker_stats.entry(*worker_id).or_default();
stats.max_local_queue = stats.max_local_queue.max(*worker_local_queue_depth);
stats.poll_count += 1;
poll_starts.insert(*worker_id, *timestamp_nanos);
if spawn_loc.raw_id() != 0 {
spawn_location_stats
.entry(*spawn_loc)
.or_default()
.poll_count += 1;
poll_start_locs.insert(*worker_id, *spawn_loc);
}
}
TelemetryEvent::PollEnd {
timestamp_nanos,
worker_id,
} => {
let stats = worker_stats.entry(*worker_id).or_default();
if let Some(start) = poll_starts.get(worker_id) {
let duration = timestamp_nanos.saturating_sub(*start);
stats.total_poll_time_ns += duration;
if let Some(loc_id) = poll_start_locs.remove(worker_id) {
spawn_location_stats
.entry(loc_id)
.or_default()
.total_poll_time_ns += duration;
}
}
}
TelemetryEvent::WorkerPark {
worker_id,
worker_local_queue_depth,
..
} => {
let stats = worker_stats.entry(*worker_id).or_default();
stats.max_local_queue = stats.max_local_queue.max(*worker_local_queue_depth);
stats.park_count += 1;
}
TelemetryEvent::WorkerUnpark {
worker_id,
worker_local_queue_depth,
sched_wait_delta_nanos,
..
} => {
let stats = worker_stats.entry(*worker_id).or_default();
stats.max_local_queue = stats.max_local_queue.max(*worker_local_queue_depth);
stats.unpark_count += 1;
stats.total_sched_wait_ns += sched_wait_delta_nanos;
stats.max_sched_wait_ns = stats.max_sched_wait_ns.max(*sched_wait_delta_nanos);
}
TelemetryEvent::TaskSpawn { .. }
| TelemetryEvent::TaskTerminate { .. }
| TelemetryEvent::CpuSample { .. }
| TelemetryEvent::TaskDump { .. }
| TelemetryEvent::Alloc { .. }
| TelemetryEvent::Free { .. }
| TelemetryEvent::ThreadNameDef { .. }
| TelemetryEvent::WakeEvent { .. }
| TelemetryEvent::SegmentMetadata { .. }
| TelemetryEvent::ClockSync { .. }
| TelemetryEvent::Custom { .. } => {}
}
}
TraceAnalysis {
total_events: events.len(),
duration_ns: end_time.saturating_sub(start_time),
worker_stats,
max_global_queue,
avg_global_queue: if global_queue_count > 0 {
global_queue_sum as f64 / global_queue_count as f64
} else {
0.0
},
spawn_location_stats,
}
}
/// Compute wake→poll scheduling delays from wake events and poll starts.
/// Returns a sorted vec of delay durations in nanoseconds.
pub fn compute_wake_to_poll_delays(events: &[TelemetryEvent]) -> Vec<u64> {
// Index: task_id → sorted vec of wake timestamps
let mut wakes_by_task: HashMap<TaskId, Vec<u64>> = HashMap::new();
for e in events {
if let TelemetryEvent::WakeEvent {
timestamp_nanos,
woken_task_id,
..
} = e
{
wakes_by_task
.entry(*woken_task_id)
.or_default()
.push(*timestamp_nanos);
}
}
for v in wakes_by_task.values_mut() {
v.sort_unstable();
}
let mut delays = Vec::new();
for e in events {
if let TelemetryEvent::PollStart {
timestamp_nanos,
task_id,
..
} = e
&& let Some(wakes) = wakes_by_task.get(task_id)
{
// Binary search for last wake <= poll start
let idx = wakes.partition_point(|&t| t <= *timestamp_nanos);
if idx > 0 {
let delay = timestamp_nanos - wakes[idx - 1];
if delay > 0 && delay < 1_000_000_000 {
delays.push(delay);
}
}
}
}
delays.sort_unstable();
delays
}
/// An active period between WorkerUnpark and WorkerPark, with scheduling ratio.
#[derive(Debug)]
pub struct ActivePeriod {
/// Worker thread that was active during this period.
pub worker_id: WorkerId,
/// Timestamp when the worker was unparked (nanos).
pub start_ns: u64,
/// Timestamp when the worker parked again (nanos).
pub end_ns: u64,
/// CPU time consumed during this active period (nanos).
pub cpu_delta_ns: u64,
/// Fraction of wall time the thread was actually on-CPU (0.0–1.0).
pub scheduling_ratio: f64,
}
/// Compute scheduling ratios for each active period (unpark→park) per worker.
pub fn compute_active_periods(events: &[TelemetryEvent]) -> Vec<ActivePeriod> {
let mut periods = Vec::new();
// Track (wall_ns, cpu_ns) at unpark
let mut unpark_state: HashMap<WorkerId, (u64, u64)> = HashMap::new();
for event in events {
match event {
TelemetryEvent::WorkerUnpark {
timestamp_nanos,
worker_id,
cpu_time_nanos,
..
} => {
unpark_state.insert(*worker_id, (*timestamp_nanos, *cpu_time_nanos));
}
TelemetryEvent::WorkerPark {
timestamp_nanos,
worker_id,
cpu_time_nanos,
..
} => {
if let Some((start_wall, start_cpu)) = unpark_state.remove(worker_id) {
let wall_delta = timestamp_nanos.saturating_sub(start_wall);
let cpu_delta = cpu_time_nanos.saturating_sub(start_cpu);
let ratio = if wall_delta > 0 {
(cpu_delta as f64 / wall_delta as f64).min(1.0)
} else {
1.0
};
periods.push(ActivePeriod {
worker_id: *worker_id,
start_ns: start_wall,
end_ns: *timestamp_nanos,
cpu_delta_ns: cpu_delta,
scheduling_ratio: ratio,
});
}
}
_ => {}
}
}
periods
}
/// Print a human-readable summary of a [`TraceAnalysis`] to stdout.
pub fn print_analysis(analysis: &TraceAnalysis, spawn_locations: &HashMap<InternedString, String>) {
println!("\n=== Trace Analysis ===");
println!("Total events: {}", analysis.total_events);
println!(
"Duration: {:.2}s",
analysis.duration_ns as f64 / 1_000_000_000.0
);
println!("Max global queue depth: {}", analysis.max_global_queue);
println!("Avg global queue depth: {:.2}", analysis.avg_global_queue);
println!("\n=== Worker Statistics ===");
for (worker_id, stats) in &analysis.worker_stats {
println!("\nWorker {}:", worker_id);
println!(" Polls: {}", stats.poll_count);
println!(" Parks: {}", stats.park_count);
println!(" Unparks: {}", stats.unpark_count);
println!(
" Avg poll time: {:.2}µs",
if stats.poll_count > 0 {
stats.total_poll_time_ns as f64 / stats.poll_count as f64 / 1000.0
} else {
0.0
}
);
println!(" Max local queue: {}", stats.max_local_queue);
if stats.unpark_count > 0 {
println!(
" Sched wait: avg {:.1}µs, max {:.1}µs",
stats.total_sched_wait_ns as f64 / stats.unpark_count as f64 / 1000.0,
stats.max_sched_wait_ns as f64 / 1000.0,
);
}
}
if !analysis.spawn_location_stats.is_empty() {
println!("\n=== Spawn Locations (by poll count) ===");
let mut locs: Vec<_> = analysis.spawn_location_stats.iter().collect();
locs.sort_by_key(|b| Reverse(b.1.poll_count));
for (id, stats) in locs {
let name = spawn_locations
.get(id)
.map(|s| s.as_str())
.unwrap_or("<unknown>");
let avg_poll_us = if stats.poll_count > 0 {
stats.total_poll_time_ns as f64 / stats.poll_count as f64 / 1000.0
} else {
0.0
};
println!(
" {} — {} polls, avg {:.2}µs",
name, stats.poll_count, avg_poll_us
);
}
}
}
/// Detect periods where a worker was parked while the global queue had pending work.
///
/// Uses the global queue sample timeline to look up the queue depth at unpark time,
/// since global_queue_depth is only recorded on QueueSample events.
pub fn detect_idle_workers(events: &[TelemetryEvent]) -> Vec<(WorkerId, u64, usize)> {
let global_queue_timeline = build_global_queue_timeline(events);
let mut idle_periods = Vec::new();
let mut worker_park_times: HashMap<WorkerId, u64> = HashMap::new();
for event in events {
match event {
TelemetryEvent::WorkerPark {
timestamp_nanos,
worker_id,
..
} => {
worker_park_times.insert(*worker_id, *timestamp_nanos);
}
TelemetryEvent::WorkerUnpark {
timestamp_nanos,
worker_id,
..
} => {
if let Some(park_time) = worker_park_times.remove(worker_id) {
let idle_duration = timestamp_nanos.saturating_sub(park_time);
let global_queue_at_unpark =
lookup_global_queue_depth(&global_queue_timeline, *timestamp_nanos);
if idle_duration > 1_000_000 && global_queue_at_unpark > 0 {
idle_periods.push((*worker_id, idle_duration, global_queue_at_unpark));
}
}
}
_ => {}
}
}
idle_periods
}
/// A poll that exceeded the given duration threshold.
#[derive(Debug)]
pub struct LongPoll {
/// Worker that executed the poll.
pub worker_id: WorkerId,
/// Poll start timestamp (nanos).
pub start_ns: u64,
/// Poll end timestamp (nanos).
pub end_ns: u64,
/// Duration of the poll in nanoseconds.
pub duration_ns: u64,
/// Task that was being polled.
pub task_id: TaskId,
/// Spawn location of the task.
pub spawn_loc: InternedString,
}
/// Detect polls that exceed `threshold_ns` nanoseconds.
///
/// Returns long polls in timestamp order. Each entry captures the worker,
/// time range, and task metadata (when task tracking is enabled).
pub fn detect_long_polls(events: &[TelemetryEvent], threshold_ns: u64) -> Vec<LongPoll> {
let mut long_polls = Vec::new();
let mut poll_starts: HashMap<WorkerId, (u64, TaskId, InternedString)> = HashMap::new();
for event in events {
match event {
TelemetryEvent::PollStart {
timestamp_nanos,
worker_id,
task_id,
spawn_loc,
..
} => {
poll_starts.insert(*worker_id, (*timestamp_nanos, *task_id, *spawn_loc));
}
TelemetryEvent::PollEnd {
timestamp_nanos,
worker_id,
} => {
if let Some((start, task_id, spawn_loc)) = poll_starts.remove(worker_id) {
let duration = timestamp_nanos.saturating_sub(start);
if duration >= threshold_ns {
long_polls.push(LongPoll {
worker_id: *worker_id,
start_ns: start,
end_ns: *timestamp_nanos,
duration_ns: duration,
task_id,
spawn_loc,
});
}
}
}
_ => {}
}
}
long_polls
}
/// A park period where the OS scheduler delayed the worker thread.
#[derive(Debug)]
pub struct SchedDelay {
/// Worker that experienced the scheduling delay.
pub worker_id: WorkerId,
/// Timestamp when the worker parked (nanos).
pub park_ns: u64,
/// Timestamp when the worker was unparked (nanos).
pub unpark_ns: u64,
/// OS scheduling wait during this park period (nanos).
pub sched_wait_ns: u64,
}
/// Detect park periods where OS scheduling wait exceeded `threshold_ns`.
///
/// `sched_wait_delta_nanos` on `WorkerUnpark` reports how long the thread was
/// runnable but not scheduled by the OS during the preceding park.
pub fn detect_sched_delays(events: &[TelemetryEvent], threshold_ns: u64) -> Vec<SchedDelay> {
let mut delays = Vec::new();
let mut park_times: HashMap<WorkerId, u64> = HashMap::new();
for event in events {
match event {
TelemetryEvent::WorkerPark {
timestamp_nanos,
worker_id,
..
} => {
park_times.insert(*worker_id, *timestamp_nanos);
}
TelemetryEvent::WorkerUnpark {
timestamp_nanos,
worker_id,
sched_wait_delta_nanos,
..
} => {
if let Some(park_ns) = park_times.remove(worker_id)
&& *sched_wait_delta_nanos >= threshold_ns
{
delays.push(SchedDelay {
worker_id: *worker_id,
park_ns,
unpark_ns: *timestamp_nanos,
sched_wait_ns: *sched_wait_delta_nanos,
});
}
}
_ => {}
}
}
delays
}
/// A wake-to-poll scheduling delay that exceeded a threshold.
#[derive(Debug)]
pub struct WakeDelay {
/// Worker that polled the task after the wake.
pub worker_id: WorkerId,
/// Timestamp of the wake event (nanos).
pub wake_ns: u64,
/// Timestamp of the subsequent poll start (nanos).
pub poll_ns: u64,
/// Delay between wake and poll in nanoseconds.
pub delay_ns: u64,
/// Task that experienced the scheduling delay.
pub task_id: TaskId,
}
/// Detect wake-to-poll delays exceeding `threshold_ns`.
///
/// For each `PollStart`, finds the most recent wake for that task and reports
/// the delay if it exceeds the threshold. Delays >= 1s are discarded as likely
/// representing idle tasks rather than scheduling problems.
pub fn detect_wake_delays(events: &[TelemetryEvent], threshold_ns: u64) -> Vec<WakeDelay> {
const MAX_REASONABLE_DELAY_NS: u64 = 1_000_000_000;
let mut wakes_by_task: HashMap<TaskId, Vec<u64>> = HashMap::new();
for event in events {
if let TelemetryEvent::WakeEvent {
timestamp_nanos,
woken_task_id,
..
} = event
{
wakes_by_task
.entry(*woken_task_id)
.or_default()
.push(*timestamp_nanos);
}
}
for v in wakes_by_task.values_mut() {
v.sort_unstable();
}
let mut delays = Vec::new();
for event in events {
if let TelemetryEvent::PollStart {
timestamp_nanos,
worker_id,
task_id,
..
} = event
&& let Some(wakes) = wakes_by_task.get(task_id)
{
let idx = wakes.partition_point(|&t| t <= *timestamp_nanos);
if idx > 0 {
let delay = timestamp_nanos.saturating_sub(wakes[idx - 1]);
if delay >= threshold_ns && delay < MAX_REASONABLE_DELAY_NS {
delays.push(WakeDelay {
worker_id: *worker_id,
wake_ns: wakes[idx - 1],
poll_ns: *timestamp_nanos,
delay_ns: delay,
task_id: *task_id,
});
}
}
}
}
delays
}
/// A poll that had CPU or scheduler samples collected during its execution.
#[derive(Debug)]
pub struct SampledPoll {
/// Worker that executed the poll.
pub worker_id: WorkerId,
/// Poll start timestamp (nanos).
pub start_ns: u64,
/// Poll end timestamp (nanos).
pub end_ns: u64,
/// Task that was being polled.
pub task_id: TaskId,
/// Spawn location of the task.
pub spawn_loc: InternedString,
/// Number of CPU profile samples collected during this poll.
pub cpu_sample_count: usize,
/// Number of scheduler event samples collected during this poll.
pub sched_sample_count: usize,
}
/// Find polls that had CPU profile or scheduler event samples collected during
/// their execution. Correlates `CpuSample` events with poll time ranges on the
/// same worker.
pub fn detect_sampled_polls(events: &[TelemetryEvent]) -> Vec<SampledPoll> {
struct PollSpan {
worker_id: WorkerId,
start_ns: u64,
end_ns: u64,
task_id: TaskId,
spawn_loc: InternedString,
cpu_samples: usize,
sched_samples: usize,
}
// First pass: build poll spans per worker
let mut polls: Vec<PollSpan> = Vec::new();
let mut poll_starts: HashMap<WorkerId, (u64, TaskId, InternedString)> = HashMap::new();
for event in events {
match event {
TelemetryEvent::PollStart {
timestamp_nanos,
worker_id,
task_id,
spawn_loc,
..
} => {
poll_starts.insert(*worker_id, (*timestamp_nanos, *task_id, *spawn_loc));
}
TelemetryEvent::PollEnd {
timestamp_nanos,
worker_id,
} => {
if let Some((start, task_id, spawn_loc)) = poll_starts.remove(worker_id) {
polls.push(PollSpan {
worker_id: *worker_id,
start_ns: start,
end_ns: *timestamp_nanos,
task_id,
spawn_loc,
cpu_samples: 0,
sched_samples: 0,
});
}
}
_ => {}
}
}
// Sort polls by (worker_id, start_ns) for binary search
polls.sort_unstable_by_key(|p| (p.worker_id, p.start_ns));
// Second pass: attribute each CpuSample to a poll
for event in events {
if let TelemetryEvent::CpuSample {
timestamp_nanos,
worker_id,
source,
..
} = event
{
let start_idx = polls.partition_point(|p| p.worker_id < *worker_id);
let end_idx = polls.partition_point(|p| p.worker_id <= *worker_id);
let worker_polls = &mut polls[start_idx..end_idx];
let idx = worker_polls.partition_point(|p| p.start_ns <= *timestamp_nanos);
if idx > 0 && *timestamp_nanos <= worker_polls[idx - 1].end_ns {
match source {
CpuSampleSource::CpuProfile => worker_polls[idx - 1].cpu_samples += 1,
CpuSampleSource::SchedEvent => worker_polls[idx - 1].sched_samples += 1,
}
}
}
}
// Collect polls that had any samples, grouped by worker
polls
.into_iter()
.filter(|p| p.cpu_samples > 0 || p.sched_samples > 0)
.map(|p| SampledPoll {
worker_id: p.worker_id,
start_ns: p.start_ns,
end_ns: p.end_ns,
task_id: p.task_id,
spawn_loc: p.spawn_loc,
cpu_sample_count: p.cpu_samples,
sched_sample_count: p.sched_samples,
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::telemetry::format::WorkerId;
use crate::telemetry::task_metadata::UNKNOWN_TASK_ID;
use dial9_trace_format::encoder::Encoder;
use dial9_trace_format::{FieldValue, InternedString};
const UNKNOWN_SPAWN_LOC: InternedString = InternedString::from_raw(0);
#[test]
fn trace_reader_reads_gzip_trace_files() {
use crate::telemetry::buffer::ThreadLocalBuffer;
use crate::telemetry::format::WorkerParkEvent;
use crate::telemetry::writer::{RotatingWriter, TraceWriter};
use flate2::Compression;
use flate2::write::GzEncoder;
use std::io::Write;
let dir = tempfile::tempdir().unwrap();
let raw_path = dir.path().join("trace.bin");
let mut writer = RotatingWriter::single_file(&raw_path).unwrap();
let batch = crate::telemetry::collector::Batch::new(
ThreadLocalBuffer::encode_single(&WorkerParkEvent {
timestamp_ns: 1_000,
worker_id: WorkerId::from(7usize),
local_queue: 3,
cpu_time_ns: 11,
tid: 0,
}),
1,
);
writer.write_encoded_batch(&batch).unwrap();
writer.flush().unwrap();
let active = writer.current_active_path().to_owned();
drop(writer);
let raw = std::fs::read(&active).unwrap();
let gzip_path = dir.path().join("trace.bin.gz");
let mut encoder = GzEncoder::new(Vec::new(), Compression::fast());
encoder.write_all(&raw).unwrap();
let compressed = encoder.finish().unwrap();
std::fs::write(&gzip_path, compressed).unwrap();
let reader = TraceReader::new(gzip_path.to_str().unwrap()).unwrap();
let events = &reader.runtime_events;
assert_eq!(events.len(), 1);
assert!(matches!(
events[0],
TelemetryEvent::WorkerPark {
timestamp_nanos: 1_000,
worker_id,
worker_local_queue_depth: 3,
cpu_time_nanos: 11,
..
} if worker_id == WorkerId::from(7usize)
));
}
#[test]
fn test_analyze_empty() {
let events = vec![];
let analysis = analyze_trace(&events);
assert_eq!(analysis.total_events, 0);
assert_eq!(analysis.max_global_queue, 0);
}
#[test]
fn test_global_queue_from_samples_only() {
let events = vec![
TelemetryEvent::PollStart {
timestamp_nanos: 1_000_000,
worker_id: WorkerId::from(0usize),
worker_local_queue_depth: 3,
task_id: UNKNOWN_TASK_ID,
spawn_loc: UNKNOWN_SPAWN_LOC,
},
TelemetryEvent::QueueSample {
timestamp_nanos: 2_000_000,
global_queue_depth: 42,
},
TelemetryEvent::PollEnd {
timestamp_nanos: 3_000_000,
worker_id: WorkerId::from(0usize),
},
];
let analysis = analyze_trace(&events);
assert_eq!(analysis.max_global_queue, 42);
assert_eq!(analysis.total_events, 3);
// Only the QueueSample contributes to avg
assert!((analysis.avg_global_queue - 42.0).abs() < f64::EPSILON);
}
#[test]
fn test_local_queue_tracked_on_all_worker_events() {
let events = vec![
TelemetryEvent::PollStart {
timestamp_nanos: 1_000_000,
worker_id: WorkerId::from(0usize),
worker_local_queue_depth: 10,
task_id: UNKNOWN_TASK_ID,
spawn_loc: UNKNOWN_SPAWN_LOC,
},
TelemetryEvent::PollEnd {
timestamp_nanos: 2_000_000,
worker_id: WorkerId::from(0usize),
},
];
let analysis = analyze_trace(&events);
let stats = analysis.worker_stats.get(&WorkerId::from(0usize)).unwrap();
assert_eq!(stats.max_local_queue, 10);
}
#[test]
fn test_lookup_global_queue_depth() {
let timeline = vec![(1_000_000u64, 5), (3_000_000, 10), (5_000_000, 2)];
// Before any sample
assert_eq!(lookup_global_queue_depth(&timeline, 500_000), 0);
// Exact match
assert_eq!(lookup_global_queue_depth(&timeline, 1_000_000), 5);
// Between samples — use most recent
assert_eq!(lookup_global_queue_depth(&timeline, 2_000_000), 5);
assert_eq!(lookup_global_queue_depth(&timeline, 4_000_000), 10);
// After last sample
assert_eq!(lookup_global_queue_depth(&timeline, 9_000_000), 2);
}
#[test]
fn test_detect_idle_workers_with_samples() {
let events = vec![
TelemetryEvent::QueueSample {
timestamp_nanos: 1_000_000,
global_queue_depth: 15,
},
TelemetryEvent::WorkerPark {
timestamp_nanos: 2_000_000,
worker_id: WorkerId::from(0usize),
worker_local_queue_depth: 0,
cpu_time_nanos: 0,
tid: 0,
},
TelemetryEvent::QueueSample {
timestamp_nanos: 5_000_000,
global_queue_depth: 20,
},
TelemetryEvent::WorkerUnpark {