-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtrace_viewer.html
More file actions
2018 lines (1871 loc) · 92.3 KB
/
trace_viewer.html
File metadata and controls
2018 lines (1871 loc) · 92.3 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
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tokio Trace Viewer</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
monospace;
background: #1a1a2e;
color: #e0e0e0;
overflow: hidden;
height: 100vh;
display: flex;
flex-direction: column;
}
#drop-zone {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
width: 100vw;
border: 3px dashed #444;
border-radius: 12px;
margin: 20px;
font-size: 1.2em;
color: #888;
cursor: pointer;
transition: all 0.2s;
}
#drop-zone:hover,
#drop-zone.dragover {
border-color: #6c63ff;
color: #6c63ff;
background: rgba(108, 99, 255, 0.05);
}
#drop-zone input {
display: none;
}
#viewer {
display: none;
flex-direction: column;
height: 100vh;
}
#toolbar {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 16px;
background: #16213e;
border-bottom: 1px solid #333;
flex-shrink: 0;
min-height: 44px;
}
#toolbar .filename {
font-weight: 600;
color: #6c63ff;
}
#toolbar .filename::after {
content: " v15";
font-size: 0.7em;
color: #888;
}
#toolbar .stats {
color: #888;
font-size: 0.85em;
}
#toolbar button {
background: #2a2a4a;
border: 1px solid #444;
color: #ccc;
padding: 4px 12px;
border-radius: 4px;
cursor: pointer;
font-size: 0.85em;
}
#toolbar button:hover {
background: #3a3a5a;
}
#toolbar button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
#toolbar select {
background: #2a2a4a;
border: 1px solid #444;
color: #ccc;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.85em;
}
#tooltip {
display: none;
position: fixed;
background: #222244;
border: 1px solid #555;
padding: 8px 12px;
border-radius: 6px;
font-size: 0.8em;
pointer-events: none;
z-index: 100;
max-width: 320px;
line-height: 1.5;
}
#tooltip .label {
color: #888;
}
#tooltip .value {
color: #fff;
font-weight: 600;
}
#main-area {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
position: relative;
}
#timeline-header {
height: 30px;
background: #16213e;
border-bottom: 1px solid #333;
flex-shrink: 0;
position: relative;
overflow: hidden;
}
#lanes-container {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
position: relative;
}
#task-detail {
display: none;
height: 160px;
background: #16213e;
border-top: 1px solid #333;
flex-shrink: 0;
position: relative;
overflow: hidden;
}
#task-detail .chart-label {
position: absolute;
top: 4px;
left: 8px;
font-size: 0.75em;
color: #888;
z-index: 2;
}
#queue-chart {
height: 120px;
background: #16213e;
border-top: 1px solid #333;
flex-shrink: 0;
position: relative;
overflow: hidden;
}
#queue-chart .chart-label {
position: absolute;
top: 4px;
left: 8px;
font-size: 0.75em;
color: #888;
z-index: 2;
}
.lane {
height: 60px;
border-bottom: 1px solid #222;
position: relative;
display: flex;
}
.lane-label {
width: 100px;
flex-shrink: 0;
display: flex;
align-items: center;
padding-left: 12px;
font-size: 0.8em;
color: #aaa;
background: #16213e;
border-right: 1px solid #333;
z-index: 1;
}
.lane-content {
flex: 1;
position: relative;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<div id="drop-zone">
<div>
<div style="font-size: 2em; margin-bottom: 12px">📊</div>
<div>
Drop a <code>.bin</code> trace file here or click to open
</div>
<div style="font-size: 0.8em; margin-top: 8px; color: #666">
Expects TOKIOTRC binary format
</div>
</div>
<input type="file" id="file-input" accept=".bin" />
</div>
<div id="viewer">
<div id="toolbar">
<span class="filename" id="tb-filename"></span>
<span class="stats" id="tb-stats"></span>
<span style="flex: 1"></span>
<select id="poi-filter">
<option value="sched">Kernel Scheduling Delays</option>
<option value="long-poll">Long Polls (>1ms)</option>
<option value="wake-delay">Wake→Poll Delays (>100µs)</option>
</select>
<label style="display:flex;align-items:center;gap:4px;font-size:0.85em;cursor:pointer">
<input type="checkbox" id="sort-by-worst" style="cursor:pointer">
Worst first
</label>
<button id="btn-prev-poi">◀ Prev</button>
<button id="btn-next-poi">Next ▶</button>
<span id="poi-counter" style="font-size:0.85em;color:#888"></span>
<span style="width:1px;height:20px;background:#444;margin:0 8px"></span>
<button id="btn-zoom-in">Zoom +</button>
<button id="btn-zoom-out">Zoom −</button>
<button id="btn-fit">Fit All</button>
<button id="btn-reset">New File</button>
</div>
<div id="main-area">
<canvas id="crosshair-overlay" style="position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:10"></canvas>
<div id="timeline-header">
<canvas id="timeline-canvas"></canvas>
</div>
<div id="lanes-container" id="lanes"></div>
<div id="task-detail">
<span class="chart-label" id="task-detail-label">Task Detail</span>
<span id="task-detail-status" style="position:absolute;top:4px;right:12px;font-size:0.75em;color:#aaa;z-index:2"></span>
<canvas id="task-detail-canvas"></canvas>
</div>
<div id="queue-chart">
<span class="chart-label"
>Queue Depth (global=blue, local max=orange)</span
>
<canvas id="queue-canvas"></canvas>
</div>
</div>
</div>
<div id="tooltip"></div>
<script>
// ── Binary Parser (v9 format) ──
// Wire codes:
// 0: PollStart → code(1) + ts(4) + worker(1) + local_q(1) + task_id(4) + spawn_loc_id(2) = 13 bytes
// 1: PollEnd → code(1) + ts(4) + worker(1) = 6 bytes
// 2: WorkerPark → code(1) + ts(4) + worker(1) + local_q(1) + cpu_us(4) = 11 bytes
// 3: WorkerUnpark → code(1) + ts(4) + worker(1) + local_q(1) + cpu_us(4) + sched_wait_us(4) = 15 bytes
// 4: QueueSample → code(1) + ts(4) + global_q(1) = 6 bytes
// 5: SpawnLocationDef → code(1) + spawn_loc_id(2) + string_len(2) + string_bytes(N)
// 6: TaskSpawn → code(1) + task_id(4) + spawn_loc_id(2) = 7 bytes
// 7: WakeEvent → code(1) + ts(4) + waker_task_id(4) + woken_task_id(4) + target_worker(1) = 14 bytes
const MAX_EVENTS = 2_000_000; // cap parsed events to keep UI responsive
function parseTrace(buffer) {
const view = new DataView(buffer);
let off = 0;
const magic = String.fromCharCode(
...new Uint8Array(buffer, 0, 8),
);
off += 8;
const version = view.getUint32(off, true);
off += 4;
if (magic !== "TOKIOTRC")
throw new Error("Not a TOKIOTRC file (got: " + magic + ")");
if (version !== 8 && version !== 9) {
console.warn(`Expected version 8 or 9, got ${version}. Some data may be missing.`);
}
const hasCpuTime = version >= 5;
const hasSchedWait = version >= 6;
const hasTaskTracking = version >= 7;
const events = [];
const spawnLocations = new Map(); // SpawnLocationId (number) → string
const taskSpawnLocs = new Map(); // taskId (number) → SpawnLocationId (number)
const decoder = new TextDecoder();
while (off < buffer.byteLength && events.length < MAX_EVENTS) {
if (off + 1 > buffer.byteLength) break;
const wireCode = view.getUint8(off);
off += 1;
// SpawnLocationDef and TaskSpawn have no timestamp — handle before reading ts
if (wireCode === 5) {
if (off + 4 > buffer.byteLength) break;
const spawnLocId = view.getUint16(off, true); off += 2;
const strLen = view.getUint16(off, true); off += 2;
if (off + strLen > buffer.byteLength) break;
spawnLocations.set(spawnLocId, decoder.decode(new Uint8Array(buffer, off, strLen)));
off += strLen;
continue;
}
if (wireCode === 6) {
if (off + 6 > buffer.byteLength) break;
const taskId = view.getUint32(off, true); off += 4;
const spawnLocId = view.getUint16(off, true); off += 2;
taskSpawnLocs.set(taskId, spawnLocId);
continue;
}
if (wireCode === 7) {
// WakeEvent: ts(4) + waker_task_id(4) + woken_task_id(4) + target_worker(1) = 13 after code
if (off + 13 > buffer.byteLength) break;
const timestampUs = view.getUint32(off, true); off += 4;
const wakerTaskId = view.getUint32(off, true); off += 4;
const wokenTaskId = view.getUint32(off, true); off += 4;
const targetWorker = view.getUint8(off); off += 1;
events.push({
eventType: 7, // WakeEvent
timestamp: timestampUs * 1000,
workerId: targetWorker,
wakerTaskId,
wokenTaskId,
targetWorker,
globalQueue: 0, localQueue: 0, cpuTime: 0, schedWait: 0,
taskId: 0, spawnLocId: 0, spawnLoc: null,
});
continue;
}
if (wireCode > 7) break; // unknown code
// All regular codes have a 4-byte timestamp next
if (off + 4 > buffer.byteLength) break;
const timestampUs = view.getUint32(off, true);
off += 4;
const timestamp = timestampUs * 1000;
let eventType,
workerId = 0,
globalQueue = 0,
localQueue = 0,
cpuTime = 0,
schedWait = 0,
taskId = 0,
spawnLocId = 0;
switch (wireCode) {
case 0: // PollStart
if (hasTaskTracking) {
// v8: worker(1) + lq(1) + task_id(4) + spawn_loc_id(2) = 8
if (off + 8 > buffer.byteLength) break;
eventType = 0;
workerId = view.getUint8(off); off += 1;
localQueue = view.getUint8(off); off += 1;
taskId = view.getUint32(off, true); off += 4;
spawnLocId = view.getUint16(off, true); off += 2;
} else {
if (off + 1 > buffer.byteLength) break;
eventType = 0;
workerId = view.getUint8(off); off += 1;
}
break;
case 1: // PollEnd
if (off + 1 > buffer.byteLength) break;
eventType = 1;
workerId = view.getUint8(off); off += 1;
break;
case 2: { // WorkerPark
const need = hasCpuTime ? 6 : 2;
if (off + need > buffer.byteLength) break;
eventType = 2;
workerId = view.getUint8(off); off += 1;
localQueue = view.getUint8(off); off += 1;
if (hasCpuTime) {
cpuTime = view.getUint32(off, true) * 1000; off += 4;
}
break;
}
case 3: { // WorkerUnpark
const need = hasCpuTime ? (hasSchedWait ? 10 : 6) : 2;
if (off + need > buffer.byteLength) break;
eventType = 3;
workerId = view.getUint8(off); off += 1;
localQueue = view.getUint8(off); off += 1;
if (hasCpuTime) {
cpuTime = view.getUint32(off, true) * 1000; off += 4;
}
if (hasSchedWait) {
schedWait = view.getUint32(off, true); off += 4;
}
break;
}
case 4: // QueueSample
if (off + 1 > buffer.byteLength) break;
eventType = 4;
globalQueue = view.getUint8(off); off += 1;
break;
}
// Also build taskSpawnLocs from PollStart (covers tasks without TaskSpawn events)
if (eventType === 0 && taskId && spawnLocId && !taskSpawnLocs.has(taskId)) {
taskSpawnLocs.set(taskId, spawnLocId);
}
events.push({
eventType, timestamp, workerId,
globalQueue, localQueue, cpuTime, schedWait,
taskId, spawnLocId,
spawnLoc: spawnLocations.get(spawnLocId) ?? null,
});
}
return { magic, version, events, truncated: events.length >= MAX_EVENTS, hasCpuTime, hasSchedWait, hasTaskTracking, spawnLocations, taskSpawnLocs };
}
// ── Event type helpers ──
const ET = {
PollStart: 0,
PollEnd: 1,
WorkerPark: 2,
WorkerUnpark: 3,
QueueSample: 4,
WakeEvent: 7,
};
const ET_NAMES = [
"PollStart",
"PollEnd",
"WorkerPark",
"WorkerUnpark",
"QueueSample",
];
const ET_COLORS = { poll: "#4fc3f7", park: "#ff8a65" };
// Duration-based poll coloring: short=dim, long=hot
function pollColor(startNs, endNs) {
const durUs = (endNs - startNs) / 1e3;
if (durUs > 1000) return "#ff4444"; // >1ms: red
if (durUs > 100) return "#ff8a65"; // >100µs: orange
if (durUs > 10) return "#4fc3f7"; // >10µs: bright blue
return "#2a5a7a"; // ≤10µs: dim blue
}
function pollColorDim(startNs, endNs) {
const durUs = (endNs - startNs) / 1e3;
if (durUs > 1000) return "#803030"; // >1ms: muted red
if (durUs > 100) return "#805540"; // >100µs: muted orange
if (durUs > 10) return "#2a5a7a"; // >10µs: dim blue
return "#1e3040"; // ≤10µs: very dim
}
// ── State ──
let trace = null;
let workerIds = [];
let minTs = 0,
maxTs = 0,
durationNs = 0;
// View window in nanoseconds
let viewStart = 0,
viewEnd = 0;
// Precomputed spans per worker: { polls: [{start,end}], parks: [{start,end}] }
let workerSpans = {};
// Queue depth samples sorted by time
let queueSamples = [];
// Per-worker local queue samples
let workerQueueSamples = {};
let maxLocalQueue = 1;
// Points of interest for navigation
let pointsOfInterest = [];
let currentPoiIndex = -1;
// Task selection state
let selectedTaskId = null;
// Hovered waker task in task detail panel
let hoveredWakerTaskId = null;
// Stored wake hit regions for task detail mouseover: [{x1, x2, y1, y2, wakerTaskId}]
let taskDetailWakeRegions = [];
// Wake events indexed by woken task ID
let wakesByTask = {}; // taskId → [{timestamp, wakerTaskId, targetWorker}]
// Wake events indexed by target worker
let wakesByWorker = {}; // workerId → [{timestamp, wakerTaskId, wokenTaskId}]
// Scheduling delays: wake → next poll for same task
let schedDelays = []; // [{wakeTime, pollTime, delay, taskId, wakerTaskId, worker}]
const LABEL_W = 100;
const LANE_H = 60;
// ── DOM refs ──
const dropZone = document.getElementById("drop-zone");
const fileInput = document.getElementById("file-input");
const viewer = document.getElementById("viewer");
const tooltip = document.getElementById("tooltip");
const timelineCanvas = document.getElementById("timeline-canvas");
const queueCanvas = document.getElementById("queue-canvas");
const lanesContainer = document.getElementById("lanes-container");
// ── File loading ──
dropZone.addEventListener("click", () => fileInput.click());
dropZone.addEventListener("dragover", (e) => {
e.preventDefault();
dropZone.classList.add("dragover");
});
dropZone.addEventListener("dragleave", () =>
dropZone.classList.remove("dragover"),
);
dropZone.addEventListener("drop", (e) => {
e.preventDefault();
dropZone.classList.remove("dragover");
loadFile(e.dataTransfer.files[0]);
});
fileInput.addEventListener("change", (e) => {
if (e.target.files[0]) loadFile(e.target.files[0]);
});
document
.getElementById("btn-reset")
.addEventListener("click", () => {
viewer.style.display = "none";
dropZone.style.display = "flex";
});
function loadFile(file) {
const reader = new FileReader();
reader.onload = (e) => {
try {
trace = parseTrace(e.target.result);
processTrace();
showViewer(file.name);
} catch (err) {
alert("Error: " + err.message);
}
};
// Only read first 20MB — parser caps at MAX_EVENTS anyway
const maxBytes = 20 * 1024 * 1024;
const blob = file.size > maxBytes ? file.slice(0, maxBytes) : file;
reader.readAsArrayBuffer(blob);
}
function processTrace() {
const evts = trace.events;
if (!evts.length) {
alert("No events in trace");
return;
}
const wSet = new Set();
evts.forEach((e) => {
if (e.eventType !== ET.QueueSample && e.eventType !== ET.WakeEvent) wSet.add(e.workerId);
});
workerIds = [...wSet].sort((a, b) => a - b);
minTs = evts[0].timestamp;
maxTs = evts[evts.length - 1].timestamp;
// Scan for true min/max in case events aren't sorted
for (const e of evts) {
if (e.timestamp < minTs) minTs = e.timestamp;
if (e.timestamp > maxTs) maxTs = e.timestamp;
}
durationNs = maxTs - minTs || 1;
viewStart = minTs;
viewEnd = maxTs;
// Build spans
workerSpans = {};
const openPoll = {},
openPark = {},
openUnpark = {}; // track {timestamp, cpuTime} at unpark
const openPollMeta = {}; // track {taskId, spawnLocId} at PollStart
for (const w of workerIds) {
workerSpans[w] = { polls: [], parks: [], actives: [] };
}
// Group events by worker and sort per-worker by timestamp
// (events arrive in flush order, not global timestamp order)
const perWorker = {};
const globalEvts = []; // QueueSample etc
for (const e of evts) {
if (e.eventType === ET.QueueSample || e.eventType === ET.WakeEvent) {
globalEvts.push(e);
} else {
(perWorker[e.workerId] ??= []).push(e);
}
}
for (const wEvents of Object.values(perWorker)) {
wEvents.sort((a, b) => a.timestamp - b.timestamp);
}
for (const [w, wEvents] of Object.entries(perWorker)) {
for (const e of wEvents) {
if (e.eventType === ET.PollStart) {
openPoll[w] = e.timestamp;
openPollMeta[w] = { taskId: e.taskId, spawnLocId: e.spawnLocId, spawnLoc: e.spawnLoc };
} else if (e.eventType === ET.PollEnd) {
if (openPoll[w] != null) {
const meta = openPollMeta[w] || { taskId: 0, spawnLocId: 0, spawnLoc: null };
workerSpans[w].polls.push({
start: openPoll[w],
end: e.timestamp,
taskId: meta.taskId,
spawnLocId: meta.spawnLocId,
spawnLoc: meta.spawnLoc,
});
openPoll[w] = null;
}
} else if (e.eventType === ET.WorkerPark) {
openPark[w] = e.timestamp;
// Close active period
if (openUnpark[w] != null) {
const wallDelta = e.timestamp - openUnpark[w].timestamp;
const cpuDelta = e.cpuTime - openUnpark[w].cpuTime;
const ratio = wallDelta > 0 ? Math.min(cpuDelta / wallDelta, 1.0) : 1.0;
workerSpans[w].actives.push({
start: openUnpark[w].timestamp,
end: e.timestamp,
ratio,
});
openUnpark[w] = null;
}
} else if (e.eventType === ET.WorkerUnpark) {
if (openPark[w] != null) {
workerSpans[w].parks.push({
start: openPark[w],
end: e.timestamp,
schedWait: e.schedWait,
});
openPark[w] = null;
}
openUnpark[w] = { timestamp: e.timestamp, cpuTime: e.cpuTime };
}
}
}
// Close any open spans at trace end
for (const w of workerIds) {
if (openPoll[w] != null)
workerSpans[w].polls.push({
start: openPoll[w],
end: maxTs,
});
if (openPark[w] != null)
workerSpans[w].parks.push({
start: openPark[w],
end: maxTs,
});
}
// Debug: log active period stats
for (const w of workerIds) {
const a = workerSpans[w].actives;
console.log(`Worker ${w}: ${a.length} active periods` +
(a.length > 0 ? `, first ratio=${a[0].ratio.toFixed(3)}` : ''));
}
// Global queue samples (from QueueSample events only)
queueSamples = evts
.filter((e) => e.eventType === ET.QueueSample)
.map((e) => ({ t: e.timestamp, global: e.globalQueue }));
console.log(`Found ${queueSamples.length} global queue samples`);
// Per-worker local queue samples (from events that have local_queue)
workerQueueSamples = {};
maxLocalQueue = 1;
for (const w of workerIds) {
workerQueueSamples[w] = [];
}
for (const [w, wEvents] of Object.entries(perWorker)) {
for (const e of wEvents) {
if (e.eventType === ET.PollStart || e.eventType === ET.WorkerPark || e.eventType === ET.WorkerUnpark) {
workerQueueSamples[w] ??= [];
workerQueueSamples[w].push({
t: e.timestamp,
local: e.localQueue,
});
if (e.localQueue > maxLocalQueue)
maxLocalQueue = e.localQueue;
}
}
}
// Index wake events by woken task ID
wakesByTask = {};
for (const e of evts) {
if (e.eventType === ET.WakeEvent) {
(wakesByTask[e.wokenTaskId] ??= []).push({
timestamp: e.timestamp,
wakerTaskId: e.wakerTaskId,
targetWorker: e.targetWorker,
});
}
}
for (const arr of Object.values(wakesByTask)) {
arr.sort((a, b) => a.timestamp - b.timestamp);
}
// Index wake events by target worker
wakesByWorker = {};
for (const e of evts) {
if (e.eventType === ET.WakeEvent) {
(wakesByWorker[e.targetWorker] ??= []).push({
timestamp: e.timestamp,
wakerTaskId: e.wakerTaskId,
wokenTaskId: e.wokenTaskId,
});
}
}
for (const arr of Object.values(wakesByWorker)) {
arr.sort((a, b) => a.timestamp - b.timestamp);
}
// Compute scheduling delays: for each poll, find the most recent wake before it
// Build task → sorted polls index for mid-poll wake adjustment
const pollsByTask = {};
for (const w of workerIds) {
for (const s of workerSpans[w].polls) {
if (s.taskId) (pollsByTask[s.taskId] ??= []).push(s);
}
}
for (const arr of Object.values(pollsByTask)) {
arr.sort((a, b) => a.start - b.start);
}
schedDelays = [];
for (const w of workerIds) {
for (const s of workerSpans[w].polls) {
if (!s.taskId) continue;
const wakes = wakesByTask[s.taskId];
if (!wakes || !wakes.length) continue;
// Binary search for last wake <= s.start
let lo = 0, hi = wakes.length - 1, best = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (wakes[mid].timestamp <= s.start) { best = mid; lo = mid + 1; }
else hi = mid - 1;
}
if (best >= 0) {
const wake = wakes[best];
// If wake arrived during an earlier poll of this task, effective wait starts at that poll's end
let effectiveWake = wake.timestamp;
const taskPolls = pollsByTask[s.taskId];
if (taskPolls) {
for (const p of taskPolls) {
if (p.start >= s.start) break; // only earlier polls
if (wake.timestamp >= p.start && wake.timestamp <= p.end) {
effectiveWake = p.end;
break;
}
}
}
const delay = s.start - effectiveWake;
if (delay > 0 && delay < 1e9) { // sanity: < 1s
schedDelays.push({
wakeTime: effectiveWake,
pollTime: s.start,
delay,
taskId: s.taskId,
wakerTaskId: wake.wakerTaskId,
worker: w,
poll: s,
});
}
}
}
}
schedDelays.sort((a, b) => a.wakeTime - b.wakeTime);
console.log(`Found ${Object.keys(wakesByTask).length} tasks with wake events, ${schedDelays.length} scheduling delays`);
}
function showViewer(filename) {
dropZone.style.display = "none";
viewer.style.display = "flex";
document.getElementById("tb-filename").textContent = filename;
const durMs = durationNs / 1e6;
const truncNote = trace.truncated ? " (truncated)" : "";
document.getElementById("tb-stats").textContent =
`${trace.events.length.toLocaleString()} events · ${workerIds.length} workers · ${durMs.toFixed(1)}ms${truncNote}`;
buildLanes();
updatePointsOfInterest();
requestAnimationFrame(renderAll);
}
function updatePointsOfInterest() {
const filterType = document.getElementById("poi-filter").value;
pointsOfInterest = [];
for (const w of workerIds) {
const spans = workerSpans[w];
if (filterType === "sched") {
// Find parks with scheduling delays > 100µs
for (const s of spans.parks) {
if (trace.hasSchedWait && s.schedWait > 100) {
const schedWaitNs = s.schedWait * 1000;
const wakeupShouldBe = s.end - schedWaitNs;
pointsOfInterest.push({
time: wakeupShouldBe,
worker: w,
type: "sched",
value: s.schedWait,
span: s
});
}
}
} else if (filterType === "long-poll") {
// Polls longer than 1ms
for (const s of spans.polls) {
const durMs = (s.end - s.start) / 1e6;
if (durMs > 1) {
pointsOfInterest.push({
time: s.start,
worker: w,
type: "long-poll",
value: durMs,
span: s
});
}
}
}
}
if (filterType === "wake-delay") {
// Wake→Poll scheduling delays > 100µs
for (const sd of schedDelays) {
const delayUs = sd.delay / 1000;
if (delayUs > 100) {
pointsOfInterest.push({
time: sd.wakeTime,
worker: sd.worker,
type: "wake-delay",
value: delayUs,
span: sd.poll,
schedDelay: sd,
});
}
}
}
// Sort by time or by worst value
const sortByWorst = document.getElementById("sort-by-worst").checked;
if (sortByWorst) {
pointsOfInterest.sort((a, b) => b.value - a.value);
} else {
pointsOfInterest.sort((a, b) => a.time - b.time);
}
currentPoiIndex = -1;
updatePoiCounter();
}
function updatePoiCounter() {
const counter = document.getElementById("poi-counter");
const prevBtn = document.getElementById("btn-prev-poi");
const nextBtn = document.getElementById("btn-next-poi");
if (pointsOfInterest.length === 0) {
counter.textContent = "None found";
prevBtn.disabled = true;
nextBtn.disabled = true;
} else {
const idx = currentPoiIndex >= 0 ? currentPoiIndex + 1 : 0;
counter.textContent = `${idx}/${pointsOfInterest.length}`;
prevBtn.disabled = currentPoiIndex <= 0;
nextBtn.disabled = currentPoiIndex >= pointsOfInterest.length - 1;
}
}
function jumpToPoi(index) {
if (index < 0 || index >= pointsOfInterest.length) return;
currentPoiIndex = index;
const poi = pointsOfInterest[index];
// Center view on this POI with appropriate zoom
const spanDur = poi.span.end - poi.span.start;
const viewDur = Math.max(spanDur * 5, 1e6); // Show 5x the span duration, min 1ms
viewStart = Math.max(minTs, poi.time - viewDur * 0.3);
viewEnd = Math.min(maxTs, viewStart + viewDur);
// For wake-delay POIs, include the wake event in the view and select the task
if (poi.schedDelay) {
const sd = poi.schedDelay;
const totalDur = sd.poll.end - sd.wakeTime;
const padded = Math.max(totalDur * 3, 1e6);
viewStart = Math.max(minTs, sd.wakeTime - padded * 0.2);
viewEnd = Math.min(maxTs, viewStart + padded);
selectedTaskId = sd.taskId;
}
// Scroll to worker lane
const laneIdx = workerIds.indexOf(poi.worker);
if (laneIdx >= 0) {
const scrollTop = laneIdx * LANE_H;
lanesContainer.scrollTop = scrollTop;
}
updatePoiCounter();
renderAll();
}
// ── Lane DOM ──
let laneCanvases = {};
function buildLanes() {
lanesContainer.innerHTML = "";
laneCanvases = {};
for (const w of workerIds) {
const lane = document.createElement("div");
lane.className = "lane";
const label = document.createElement("div");
label.className = "lane-label";
label.textContent = `Worker ${w}`;
const content = document.createElement("div");
content.className = "lane-content";
const canvas = document.createElement("canvas");
canvas.id = `worker-${w}-canvas`;
content.appendChild(canvas);
lane.appendChild(label);
lane.appendChild(content);
lanesContainer.appendChild(lane);
laneCanvases[w] = canvas;
}
}
// ── Rendering ──
let mouseNs = null; // Track mouse position for crosshair
let queueChartRafId = null; // Throttle queue chart redraws
function renderAll() {
const rect = lanesContainer.getBoundingClientRect();
const drawW = rect.width - LABEL_W;
if (drawW <= 0) return;
// Scrollbar width: difference between container and its usable content area
const scrollbarW = lanesContainer.offsetWidth - lanesContainer.clientWidth;
// First pass: calculate max visible queue across all workers
window.visibleQueueRanges = {};
let maxVisibleQ = 1;
for (const w of workerIds) {
const samples = workerQueueSamples[w];
if (!samples || !samples.length) continue;
for (const s of samples) {
if (s.t >= viewStart && s.t <= viewEnd && s.local > maxVisibleQ) {
maxVisibleQ = s.local;
}
}
}
window.sharedVisibleMaxQ = maxVisibleQ;
renderTimeline(drawW - scrollbarW);
for (const w of workerIds) renderLane(w, drawW);
renderTaskDetail(scrollbarW);
renderQueueChart(drawW, scrollbarW);
}
function nsToX(ns, drawW) {
return ((ns - viewStart) / (viewEnd - viewStart)) * drawW;
}
function renderTimeline(drawW) {
const c = timelineCanvas;
const parent = c.parentElement;
const dpr = devicePixelRatio || 1;
c.width = parent.clientWidth * dpr;
c.height = 30 * dpr;
c.style.width = parent.clientWidth + "px";
c.style.height = "30px";
const ctx = c.getContext("2d");
ctx.scale(dpr, dpr);
const w = parent.clientWidth;
ctx.fillStyle = "#16213e";
ctx.fillRect(0, 0, w, 30);
const viewDur = viewEnd - viewStart;
// Pick nice tick interval
const targetTicks = Math.max(4, Math.floor(drawW / 100));
const rawInterval = viewDur / targetTicks;
const niceIntervals = [
1e3, 5e3, 1e4, 5e4, 1e5, 5e5, 1e6, 5e6, 1e7, 5e7, 1e8, 5e8,
1e9, 5e9, 1e10,
];
let interval =
niceIntervals.find((i) => i >= rawInterval) || rawInterval;
ctx.fillStyle = "#888";
ctx.font = "10px monospace";
ctx.textAlign = "center";
ctx.strokeStyle = "#333";
const firstTick = Math.ceil(viewStart / interval) * interval;
for (let t = firstTick; t <= viewEnd; t += interval) {
const x = LABEL_W + nsToX(t, drawW);