Repository navigation
Expand file tree
/
Copy pathtrace_viewer.py
More file actions
1718 lines (1435 loc) · 64.6 KB
/
Copy pathtrace_viewer.py
File metadata and controls
1718 lines (1435 loc) · 64.6 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
"""
Trace Viewer Module for Neuron Architecture
Provides CLI or browser-based tools for visualizing and
stepping through circuit execution traces.
"""
import os
import json
import time
import logging
import argparse
import webbrowser
from pathlib import Path
from typing import Dict, List, Any, Optional, Union, Set, Callable, Tuple
from datetime import datetime, timedelta
import http.server
import socketserver
import threading
import tempfile
import shutil
logger = logging.getLogger(__name__)
# HTML templates for visualization
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Neuron Trace Viewer</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #333;
margin: 0;
padding: 0;
background-color: #f8f9fa;
}
.container {
display: flex;
height: 100vh;
}
.sidebar {
width: 300px;
background-color: #343a40;
color: #fff;
padding: 20px;
overflow-y: auto;
}
.content {
flex: 1;
padding: 20px;
overflow-y: auto;
}
.tabs {
display: flex;
border-bottom: 1px solid #dee2e6;
margin-bottom: 20px;
}
.tab {
padding: 10px 20px;
cursor: pointer;
border: 1px solid transparent;
}
.tab.active {
border: 1px solid #dee2e6;
border-bottom-color: #fff;
background-color: #fff;
margin-bottom: -1px;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.trace-item {
padding: 10px;
margin-bottom: 10px;
cursor: pointer;
border-left: 3px solid transparent;
}
.trace-item:hover {
background-color: #49505a;
}
.trace-item.selected {
border-left-color: #007bff;
background-color: #49505a;
}
.event-item {
padding: 10px;
margin-bottom: 5px;
border-radius: 4px;
border-left: 4px solid #6c757d;
}
.event-item:hover {
background-color: #f1f3f5;
}
.event-item.selected {
background-color: #e2e6ea;
}
.event-agent-call { border-left-color: #28a745; }
.event-memory-access { border-left-color: #fd7e14; }
.event-circuit-execution { border-left-color: #007bff; }
.event-error { border-left-color: #dc3545; }
.event-span-start { border-left-color: #20c997; }
.event-span-end { border-left-color: #20c997; }
.event-agent-failure { border-left-color: #dc3545; }
.event-fallback-result { border-left-color: #6f42c1; }
pre {
background-color: #f8f9fa;
padding: 15px;
border-radius: 4px;
overflow-x: auto;
}
.event-time {
font-size: 0.8em;
color: #6c757d;
}
.btn {
padding: 8px 16px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.btn:hover {
background-color: #0069d9;
}
.timeline {
position: relative;
margin: 20px 0;
padding-bottom: 20px;
}
.timeline-bar {
position: absolute;
left: 0;
right: 0;
height: 4px;
background-color: #dee2e6;
top: 20px;
}
.timeline-events {
position: relative;
height: 40px;
}
.timeline-event {
position: absolute;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #6c757d;
top: 17px;
transform: translateX(-50%);
cursor: pointer;
}
.timeline-event.active {
background-color: #007bff;
width: 14px;
height: 14px;
top: 15px;
}
.timeline-event:hover {
transform: translateX(-50%) scale(1.2);
}
.badge {
display: inline-block;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.8em;
font-weight: 600;
color: white;
}
.badge-success { background-color: #28a745; }
.badge-danger { background-color: #dc3545; }
.badge-warning { background-color: #fd7e14; }
.badge-info { background-color: #17a2b8; }
.badge-primary { background-color: #007bff; }
.badge-secondary { background-color: #6c757d; }
.filter-section {
margin-bottom: 20px;
padding: 10px;
background-color: #49505a;
border-radius: 4px;
}
.search-box {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border-radius: 4px;
border: 1px solid #ced4da;
}
.span-marker {
display: inline-block;
width: 12px;
height: 12px;
margin-right: 5px;
border-radius: 2px;
}
.span-container {
margin: 10px 0;
padding: 10px;
border-radius: 4px;
}
.chart-container {
height: 300px;
margin: 20px 0;
}
details {
margin: 5px 0;
}
summary {
cursor: pointer;
padding: 8px;
background-color: #f1f3f5;
border-radius: 4px;
}
.timestamp-label {
font-family: monospace;
font-size: 0.8em;
color: #6c757d;
margin-top: 5px;
}
.error-message {
color: #dc3545;
margin: 15px 0;
padding: 10px;
background-color: #f8d7da;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="container">
<div class="sidebar">
<h2>Neuron Traces</h2>
<div class="filter-section">
<input type="text" id="search-box" class="search-box" placeholder="Search traces...">
<div>
<label><input type="checkbox" id="filter-completed" checked> Completed</label>
<label><input type="checkbox" id="filter-running" checked> Running</label>
<label><input type="checkbox" id="filter-error" checked> Error</label>
</div>
</div>
<div id="trace-list">
<!-- Trace items will be inserted here -->
{trace_list_items}
</div>
</div>
<div class="content">
<div id="trace-details">
<h2 id="trace-title">Select a trace</h2>
<div id="trace-metadata"></div>
<div class="tabs">
<div class="tab active" data-tab="events">Events</div>
<div class="tab" data-tab="spans">Spans</div>
<div class="tab" data-tab="timeline">Timeline</div>
<div class="tab" data-tab="stats">Stats</div>
</div>
<div class="tab-content active" id="events-tab">
<div class="filter-section">
<input type="text" id="event-filter" class="search-box" placeholder="Filter events...">
<div>
<label><input type="checkbox" class="event-type-filter" data-type="agent_call" checked> Agent Calls</label>
<label><input type="checkbox" class="event-type-filter" data-type="memory_access" checked> Memory Access</label>
<label><input type="checkbox" class="event-type-filter" data-type="circuit_execution" checked> Circuit Execution</label>
<label><input type="checkbox" class="event-type-filter" data-type="error" checked> Errors</label>
<label><input type="checkbox" class="event-type-filter" data-type="span" checked> Spans</label>
</div>
</div>
<div id="event-timeline" class="timeline">
<div class="timeline-bar"></div>
<div class="timeline-events" id="timeline-events-container">
<!-- Timeline events will be inserted here -->
</div>
</div>
<div id="events-list">
<!-- Event items will be inserted here -->
<p>Select a trace to view events</p>
</div>
</div>
<div class="tab-content" id="spans-tab">
<div id="spans-visualization">
<!-- Spans visualization will be inserted here -->
<p>Select a trace to view spans</p>
</div>
</div>
<div class="tab-content" id="timeline-tab">
<div class="chart-container" id="timeline-chart">
<!-- Timeline chart will be inserted here -->
</div>
</div>
<div class="tab-content" id="stats-tab">
<div id="stats-content">
<!-- Stats content will be inserted here -->
<p>Select a trace to view stats</p>
</div>
</div>
</div>
<div id="event-details">
<h3>Event Details</h3>
<div id="event-content">
<!-- Event details will be inserted here -->
<p>Select an event to view details</p>
</div>
</div>
</div>
</div>
<script>
// Trace data
const traceData = {trace_data_json};
// Current selected trace and event
let selectedTraceId = null;
let selectedEventId = null;
// Initialize the page
document.addEventListener('DOMContentLoaded', () => {
initTabs();
initTraceList();
initEventFilters();
});
// Initialize tabs
function initTabs() {
const tabs = document.querySelectorAll('.tab');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
// Remove active class from all tabs
tabs.forEach(t => t.classList.remove('active'));
// Add active class to clicked tab
tab.classList.add('active');
// Hide all tab content
const tabContents = document.querySelectorAll('.tab-content');
tabContents.forEach(content => content.classList.remove('active'));
// Show selected tab content
const tabName = tab.getAttribute('data-tab');
document.getElementById(tabName + '-tab').classList.add('active');
});
});
}
// Initialize trace list
function initTraceList() {
const traceList = document.getElementById('trace-list');
const searchBox = document.getElementById('search-box');
const filterCompleted = document.getElementById('filter-completed');
const filterRunning = document.getElementById('filter-running');
const filterError = document.getElementById('filter-error');
// Apply filters when changed
searchBox.addEventListener('input', updateTraceList);
filterCompleted.addEventListener('change', updateTraceList);
filterRunning.addEventListener('change', updateTraceList);
filterError.addEventListener('change', updateTraceList);
// Initial trace list update
updateTraceList();
}
// Update trace list based on filters
function updateTraceList() {
const traceList = document.getElementById('trace-list');
const searchTerm = document.getElementById('search-box').value.toLowerCase();
const showCompleted = document.getElementById('filter-completed').checked;
const showRunning = document.getElementById('filter-running').checked;
const showError = document.getElementById('filter-error').checked;
// Clear trace list
traceList.innerHTML = '';
// Add traces that match filters
Object.values(traceData).forEach(trace => {
// Check status filter
let showByStatus = false;
if (trace.status === 'completed' && showCompleted) showByStatus = true;
if (trace.status === 'running' && showRunning) showByStatus = true;
if (trace.status === 'error' && showError) showByStatus = true;
// Check search filter
const traceText = JSON.stringify(trace).toLowerCase();
const matchesSearch = searchTerm === '' || traceText.includes(searchTerm);
if (showByStatus && matchesSearch) {
const traceItem = document.createElement('div');
traceItem.classList.add('trace-item');
traceItem.setAttribute('data-trace-id', trace.trace_id);
// Status badge
let statusBadge = '';
if (trace.status === 'completed') {
statusBadge = '<span class="badge badge-success">Completed</span>';
} else if (trace.status === 'running') {
statusBadge = '<span class="badge badge-info">Running</span>';
} else if (trace.status === 'error') {
statusBadge = '<span class="badge badge-danger">Error</span>';
}
// Format timestamp
const date = new Date(trace.start_time * 1000);
const timeString = date.toLocaleTimeString();
traceItem.innerHTML = `
<div><strong>${statusBadge} ${trace.metadata?.name || 'Trace ' + trace.trace_id.substr(0, 8)}</strong></div>
<div class="event-time">${timeString} · ${trace.event_count || 0} events</div>
`;
traceItem.addEventListener('click', () => selectTrace(trace.trace_id));
traceList.appendChild(traceItem);
}
});
if (traceList.children.length === 0) {
traceList.innerHTML = '<p>No traces match the filters</p>';
}
}
// Select a trace
function selectTrace(traceId) {
selectedTraceId = traceId;
// Update UI
const traceItems = document.querySelectorAll('.trace-item');
traceItems.forEach(item => {
item.classList.remove('selected');
if (item.getAttribute('data-trace-id') === traceId) {
item.classList.add('selected');
}
});
// Update trace details
updateTraceDetails(traceId);
}
// Update trace details
function updateTraceDetails(traceId) {
const trace = traceData[traceId];
if (!trace) return;
// Update title and metadata
document.getElementById('trace-title').textContent = trace.metadata?.name || 'Trace ' + trace.trace_id.substr(0, 8);
const metadataElement = document.getElementById('trace-metadata');
// Format timestamps
const startDate = new Date(trace.start_time * 1000);
const startTimeString = startDate.toLocaleString();
let durationStr = '';
if (trace.duration) {
const duration = trace.duration;
if (duration < 1) {
durationStr = `${Math.round(duration * 1000)}ms`;
} else if (duration < 60) {
durationStr = `${duration.toFixed(2)}s`;
} else {
const minutes = Math.floor(duration / 60);
const seconds = Math.round(duration % 60);
durationStr = `${minutes}m ${seconds}s`;
}
}
let statusBadge = '';
if (trace.status === 'completed') {
statusBadge = '<span class="badge badge-success">Completed</span>';
} else if (trace.status === 'running') {
statusBadge = '<span class="badge badge-info">Running</span>';
} else if (trace.status === 'error') {
statusBadge = '<span class="badge badge-danger">Error</span>';
}
// Create metadata HTML
metadataElement.innerHTML = `
<p>${statusBadge} Started: ${startTimeString}</p>
${trace.duration ? `<p>Duration: ${durationStr}</p>` : ''}
<p>Events: ${trace.events?.length || 0}</p>
<p>Spans: ${trace.spans?.length || 0}</p>
${trace.metadata ? `
<details>
<summary>Metadata</summary>
<pre>${JSON.stringify(trace.metadata, null, 2)}</pre>
</details>
` : ''}
`;
// Update events list
updateEventsList(trace);
// Update spans visualization
updateSpansVisualization(trace);
// Update timeline
updateTimeline(trace);
// Update stats
updateStats(trace);
}
// Initialize event filters
function initEventFilters() {
const eventFilter = document.getElementById('event-filter');
const typeFilters = document.querySelectorAll('.event-type-filter');
// Apply filters when changed
eventFilter.addEventListener('input', () => {
if (selectedTraceId) {
updateEventsList(traceData[selectedTraceId]);
}
});
typeFilters.forEach(filter => {
filter.addEventListener('change', () => {
if (selectedTraceId) {
updateEventsList(traceData[selectedTraceId]);
}
});
});
}
// Update events list
function updateEventsList(trace) {
const eventsList = document.getElementById('events-list');
const eventFilter = document.getElementById('event-filter').value.toLowerCase();
const timelineEvents = document.getElementById('timeline-events-container');
// Clear events list and timeline
eventsList.innerHTML = '';
timelineEvents.innerHTML = '';
if (!trace.events || trace.events.length === 0) {
eventsList.innerHTML = '<p>No events in this trace</p>';
return;
}
// Get enabled event types
const enabledTypes = {};
document.querySelectorAll('.event-type-filter').forEach(filter => {
enabledTypes[filter.getAttribute('data-type')] = filter.checked;
});
// Calculate timeline positioning
const startTime = trace.start_time;
const endTime = trace.end_time || (startTime + trace.duration) ||
(trace.events[trace.events.length - 1]?.timestamp || startTime + 1);
const timeRange = endTime - startTime;
// Add events that match filters
trace.events.forEach((event, index) => {
// Map event type to filter type
let filterType = 'other';
if (event.event_type.includes('agent')) filterType = 'agent_call';
if (event.event_type.includes('memory')) filterType = 'memory_access';
if (event.event_type.includes('circuit')) filterType = 'circuit_execution';
if (event.event_type.includes('error')) filterType = 'error';
if (event.event_type.includes('span')) filterType = 'span';
// Check if type is enabled
const typeEnabled = enabledTypes[filterType] || false;
// Check if matches text filter
const eventText = JSON.stringify(event).toLowerCase();
const matchesText = eventFilter === '' || eventText.includes(eventFilter);
if (typeEnabled && matchesText) {
// Create event item
const eventItem = document.createElement('div');
eventItem.classList.add('event-item');
eventItem.classList.add(`event-${event.event_type.replace(/[^a-zA-Z0-9]/g, '-')}`);
eventItem.setAttribute('data-event-id', index);
// Format timestamp
const timeOffset = (event.timestamp - startTime).toFixed(3);
eventItem.innerHTML = `
<div><strong>${event.event_type}</strong> - ${event.component_id}</div>
<div class="event-time">+${timeOffset}s</div>
`;
eventItem.addEventListener('click', () => selectEvent(trace.trace_id, index));
eventsList.appendChild(eventItem);
// Add to timeline
const position = ((event.timestamp - startTime) / timeRange) * 100;
const timelineEvent = document.createElement('div');
timelineEvent.classList.add('timeline-event');
timelineEvent.style.left = `${position}%`;
timelineEvent.setAttribute('data-event-id', index);
timelineEvent.setAttribute('title', `${event.event_type} - ${timeOffset}s`);
timelineEvent.addEventListener('click', () => selectEvent(trace.trace_id, index));
timelineEvents.appendChild(timelineEvent);
}
});
if (eventsList.children.length === 0) {
eventsList.innerHTML = '<p>No events match the filters</p>';
}
}
// Select an event
function selectEvent(traceId, eventIndex) {
selectedTraceId = traceId;
selectedEventId = eventIndex;
// Update UI
const eventItems = document.querySelectorAll('.event-item');
eventItems.forEach(item => {
item.classList.remove('selected');
if (parseInt(item.getAttribute('data-event-id')) === eventIndex) {
item.classList.add('selected');
item.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
});
const timelineEvents = document.querySelectorAll('.timeline-event');
timelineEvents.forEach(item => {
item.classList.remove('active');
if (parseInt(item.getAttribute('data-event-id')) === eventIndex) {
item.classList.add('active');
}
});
// Update event details
updateEventDetails(traceId, eventIndex);
}
// Update event details
function updateEventDetails(traceId, eventIndex) {
const trace = traceData[traceId];
if (!trace || !trace.events || eventIndex >= trace.events.length) return;
const event = trace.events[eventIndex];
const eventContent = document.getElementById('event-content');
// Format timestamp
const date = new Date(event.timestamp * 1000);
const timeString = date.toLocaleString();
const timeOffset = (event.timestamp - trace.start_time).toFixed(3);
// Create event details HTML
eventContent.innerHTML = `
<p><strong>Event Type:</strong> ${event.event_type}</p>
<p><strong>Component:</strong> ${event.component_id}</p>
<p><strong>Timestamp:</strong> ${timeString} (+${timeOffset}s)</p>
${event.span_id ? `<p><strong>Span ID:</strong> ${event.span_id}</p>` : ''}
${event.sequence ? `<p><strong>Sequence:</strong> ${event.sequence}</p>` : ''}
<details open>
<summary>Event Data</summary>
<pre>${JSON.stringify(event.data, null, 2)}</pre>
</details>
<div class="timestamp-label">Event ID: ${event.event_id}</div>
`;
}
// Update spans visualization
function updateSpansVisualization(trace) {
const spansContainer = document.getElementById('spans-visualization');
if (!trace.spans || trace.spans.length === 0) {
spansContainer.innerHTML = '<p>No spans in this trace</p>';
return;
}
// Clear spans container
spansContainer.innerHTML = '';
// Create spans HTML
const startTime = trace.start_time;
const endTime = trace.end_time || (startTime + trace.duration) ||
(trace.spans[trace.spans.length - 1]?.end_time || startTime + 1);
const timeRange = endTime - startTime;
// Sort spans by start time
const sortedSpans = [...trace.spans].sort((a, b) => a.start_time - b.start_time);
// Create spans visualization
sortedSpans.forEach(span => {
// Calculate time positions
const spanStart = (span.start_time - startTime) / timeRange * 100;
const spanEnd = span.end_time ?
((span.end_time - startTime) / timeRange * 100) : 100;
const spanWidth = spanEnd - spanStart;
// Format duration
let durationStr = '';
if (span.duration) {
const duration = span.duration;
if (duration < 1) {
durationStr = `${Math.round(duration * 1000)}ms`;
} else {
durationStr = `${duration.toFixed(2)}s`;
}
}
// Generate random color based on span type
const hash = span.span_type.split('').reduce((acc, char) => {
return char.charCodeAt(0) + ((acc << 5) - acc);
}, 0);
const hue = Math.abs(hash % 360);
const spanColor = `hsl(${hue}, 70%, 60%)`;
const spanElement = document.createElement('div');
spanElement.classList.add('span-container');
spanElement.style.marginLeft = `${spanStart}%`;
spanElement.style.width = `${spanWidth}%`;
spanElement.innerHTML = `
<div>
<span class="span-marker" style="background-color: ${spanColor}"></span>
<strong>${span.span_type}</strong> - ${span.component_id}
</div>
<div class="event-time">
+${(span.start_time - startTime).toFixed(3)}s
${span.duration ? `(${durationStr})` : ''}
</div>
`;
spansContainer.appendChild(spanElement);
});
}
// Update timeline visualization
function updateTimeline(trace) {
const timelineChart = document.getElementById('timeline-chart');
if (!trace.events || trace.events.length === 0) {
timelineChart.innerHTML = '<p>No events to display timeline</p>';
return;
}
// TODO: Implement more sophisticated timeline chart
timelineChart.innerHTML = '<p>Timeline visualization coming soon</p>';
}
// Update statistics
function updateStats(trace) {
const statsContent = document.getElementById('stats-content');
if (!trace.events || trace.events.length === 0) {
statsContent.innerHTML = '<p>No events to compute statistics</p>';
return;
}
// Analyze events
const eventTypeCount = {};
const componentCount = {};
trace.events.forEach(event => {
// Count event types
if (!eventTypeCount[event.event_type]) {
eventTypeCount[event.event_type] = 0;
}
eventTypeCount[event.event_type]++;
// Count components
if (!componentCount[event.component_id]) {
componentCount[event.component_id] = 0;
}
componentCount[event.component_id]++;
});
// Analyze spans
let avgSpanDuration = 0;
let totalSpanTime = 0;
let spanTypeCount = {};
if (trace.spans && trace.spans.length > 0) {
trace.spans.forEach(span => {
if (span.duration) {
totalSpanTime += span.duration;
}
// Count span types
if (!spanTypeCount[span.span_type]) {
spanTypeCount[span.span_type] = 0;
}
spanTypeCount[span.span_type]++;
});
avgSpanDuration = totalSpanTime / trace.spans.length;
}
// Create stats HTML
let statsHtml = `
<h3>Event Statistics</h3>
<p>Total Events: ${trace.events.length}</p>
<h4>Event Types</h4>
<ul>
${Object.entries(eventTypeCount).map(([type, count]) =>
`<li>${type}: ${count} events</li>`
).join('')}
</ul>
<h4>Active Components</h4>
<ul>
${Object.entries(componentCount).map(([component, count]) =>
`<li>${component}: ${count} events</li>`
).join('')}
</ul>
`;
if (trace.spans && trace.spans.length > 0) {
statsHtml += `
<h3>Span Statistics</h3>
<p>Total Spans: ${trace.spans.length}</p>
<p>Average Span Duration: ${avgSpanDuration.toFixed(3)}s</p>
<h4>Span Types</h4>
<ul>
${Object.entries(spanTypeCount).map(([type, count]) =>
`<li>${type}: ${count} spans</li>`
).join('')}
</ul>
`;
}
statsContent.innerHTML = statsHtml;
}
</script>
</body>
</html>
"""
class TraceViewer:
"""
Provides tools for visualizing and stepping through circuit execution traces
from trace_logger output.
"""
def __init__(self, config: Dict[str, Any]):
"""
Initialize the trace viewer with configuration parameters.
Args:
config: Configuration for trace viewer
"""
# Basic configuration
self.log_dir = Path(config.get("trace_log_dir", "./logs/traces"))
self.host = config.get("server_host", "localhost")
self.port = config.get("server_port", 8675)
self.max_traces = config.get("max_traces", 100)
self.debug = config.get("debug", False)
# Specialized configuration
self.auto_open_browser = config.get("auto_open_browser", True)
self.refresh_interval = config.get("refresh_interval", 5) # seconds
self.dark_mode = config.get("dark_mode", False)
# Server state
self.server = None
self.server_thread = None
self.temp_dir = None
# Initialize logging
self._setup_logging()
def _setup_logging(self) -> None:
"""Set up logging for the trace viewer."""
if not logger.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
if self.debug:
logger.setLevel(logging.DEBUG)
def list_traces(self, max_count: int = None,
filter_status: Optional[str] = None,
time_range: Optional[Tuple[float, float]] = None) -> List[Dict[str, Any]]:
"""
List available traces with filtering options.
Args:
max_count: Maximum number of traces to return
filter_status: Optional status to filter by ('completed', 'running', 'error')
time_range: Optional (start_time, end_time) tuple
Returns:
traces: List of trace metadata
"""
max_count = max_count or self.max_traces
traces = []
try:
# List all trace files
if not self.log_dir.exists():
logger.warning(f"Trace log directory does not exist: {self.log_dir}")
return []
trace_files = list(self.log_dir.glob("*.json"))
trace_files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
# Load trace data with filtering
for file_path in trace_files[:max_count * 2]: # Load more for filtering
try:
with open(file_path, 'r') as f:
trace_data = json.load(f)
# Apply status filter
if filter_status and trace_data.get("status") != filter_status:
continue
# Apply time range filter
if time_range:
start_time, end_time = time_range
trace_start = trace_data.get("start_time", 0)
if trace_start < start_time or trace_start > end_time:
continue
# Add to results
traces.append({
"trace_id": trace_data.get("trace_id"),
"status": trace_data.get("status"),
"start_time": trace_data.get("start_time"),
"end_time": trace_data.get("end_time", None),
"duration": trace_data.get("duration", None),
"event_count": len(trace_data.get("events", [])),
"metadata": trace_data.get("metadata", {})
})
# Stop if we have enough traces
if len(traces) >= max_count:
break
except Exception as e:
logger.warning(f"Error loading trace file {file_path}: {e}")
return traces
except Exception as e:
logger.error(f"Error listing traces: {e}")
return []
def get_trace(self, trace_id: str) -> Optional[Dict[str, Any]]:
"""
Get a specific trace by ID.
Args:
trace_id: ID of the trace to retrieve
Returns:
trace: The trace data or None if not found
"""
try:
trace_file = self.log_dir / f"{trace_id}.json"
if not trace_file.exists():
logger.warning(f"Trace file not found: {trace_id}")
return None
with open(trace_file, 'r') as f:
trace_data = json.load(f)
return trace_data
except Exception as e:
logger.error(f"Error loading trace {trace_id}: {e}")
return None
def get_trace_events(self, trace_id: str,
filter_type: Optional[str] = None,
component_id: Optional[str] = None,
limit: Optional[int] = None) -> List[Dict[str, Any]]:
"""
Get events from a specific trace with filtering.
Args:
trace_id: ID of the trace
filter_type: Optional event type filter
component_id: Optional component ID filter
limit: Maximum number of events to return
Returns:
events: List of filtered events
"""
trace = self.get_trace(trace_id)
if not trace or "events" not in trace:
return []
events = trace["events"]