-
-
Notifications
You must be signed in to change notification settings - Fork 34.4k
Expand file tree
/
Copy pathtest_collectors.py
More file actions
2628 lines (2243 loc) · 98.2 KB
/
test_collectors.py
File metadata and controls
2628 lines (2243 loc) · 98.2 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
"""Tests for sampling profiler collector components."""
import json
import marshal
import opcode
import os
import tempfile
import unittest
from test.support import is_emscripten
try:
import _remote_debugging # noqa: F401
from profiling.sampling.pstats_collector import PstatsCollector
from profiling.sampling.stack_collector import (
CollapsedStackCollector,
FlamegraphCollector,
)
from profiling.sampling.jsonl_collector import JsonlCollector
from profiling.sampling.gecko_collector import GeckoCollector
from profiling.sampling.collector import extract_lineno, normalize_location
from profiling.sampling.opcode_utils import get_opcode_info, format_opcode
from profiling.sampling.constants import (
PROFILING_MODE_WALL,
PROFILING_MODE_CPU,
DEFAULT_LOCATION,
)
from _remote_debugging import (
THREAD_STATUS_HAS_GIL,
THREAD_STATUS_ON_CPU,
THREAD_STATUS_GIL_REQUESTED,
THREAD_STATUS_MAIN_THREAD,
)
except ImportError:
raise unittest.SkipTest(
"Test only runs when _remote_debugging is available"
)
from test.support import captured_stdout, captured_stderr
from .mocks import MockFrameInfo, MockThreadInfo, MockInterpreterInfo, LocationInfo, make_diff_collector_with_mock_baseline
from .helpers import close_and_unlink
def resolve_name(node, strings):
"""Resolve a flamegraph node's name from the string table."""
idx = node.get("name", 0)
if isinstance(idx, int) and 0 <= idx < len(strings):
return strings[idx]
return str(idx)
def find_child_by_name(children, strings, substr):
"""Find a child node whose resolved name contains substr."""
for child in children:
if substr in resolve_name(child, strings):
return child
return None
class TestSampleProfilerComponents(unittest.TestCase):
"""Unit tests for individual profiler components."""
def test_mock_frame_info_with_empty_and_unicode_values(self):
"""Test MockFrameInfo handles empty strings, unicode characters, and very long names correctly."""
# Test with empty strings
frame = MockFrameInfo("", 0, "")
self.assertEqual(frame.filename, "")
self.assertEqual(frame.location.lineno, 0)
self.assertEqual(frame.funcname, "")
# Test with unicode characters
frame = MockFrameInfo("文件.py", 42, "函数名")
self.assertEqual(frame.filename, "文件.py")
self.assertEqual(frame.funcname, "函数名")
# Test with very long names
long_filename = "x" * 1000 + ".py"
long_funcname = "func_" + "x" * 1000
frame = MockFrameInfo(long_filename, 999999, long_funcname)
self.assertEqual(frame.filename, long_filename)
self.assertEqual(frame.location.lineno, 999999)
self.assertEqual(frame.funcname, long_funcname)
def test_pstats_collector_with_extreme_intervals_and_empty_data(self):
"""Test PstatsCollector handles zero/large intervals, empty frames, None thread IDs, and duplicate frames."""
# Test with zero interval
collector = PstatsCollector(sample_interval_usec=0)
self.assertEqual(collector.sample_interval_usec, 0)
# Test with very large interval
collector = PstatsCollector(sample_interval_usec=1000000000)
self.assertEqual(collector.sample_interval_usec, 1000000000)
# Test collecting empty frames list
collector = PstatsCollector(sample_interval_usec=1000)
collector.collect([])
self.assertEqual(len(collector.result), 0)
# Test collecting frames with None thread id
test_frames = [
MockInterpreterInfo(
0,
[MockThreadInfo(None, [MockFrameInfo("file.py", 10, "func", None)])],
)
]
collector.collect(test_frames)
# Should still process the frames
self.assertEqual(len(collector.result), 1)
# Test collecting duplicate frames in same sample (recursive function)
test_frames = [
MockInterpreterInfo(
0, # interpreter_id
[
MockThreadInfo(
1,
[
MockFrameInfo("file.py", 10, "func1"),
MockFrameInfo("file.py", 10, "func1"), # Duplicate (recursion)
],
)
],
)
]
collector = PstatsCollector(sample_interval_usec=1000)
collector.collect(test_frames)
# Should count only once per sample to avoid over-counting recursive functions
self.assertEqual(
collector.result[("file.py", 10, "func1")]["cumulative_calls"], 1
)
def test_pstats_collector_single_frame_stacks(self):
"""Test PstatsCollector with single-frame call stacks to trigger len(frames) <= 1 branch."""
collector = PstatsCollector(sample_interval_usec=1000)
# Test with exactly one frame (should trigger the <= 1 condition)
single_frame = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1, [MockFrameInfo("single.py", 10, "single_func")]
)
],
)
]
collector.collect(single_frame)
# Should record the single frame with inline call
self.assertEqual(len(collector.result), 1)
single_key = ("single.py", 10, "single_func")
self.assertIn(single_key, collector.result)
self.assertEqual(collector.result[single_key]["direct_calls"], 1)
self.assertEqual(collector.result[single_key]["cumulative_calls"], 1)
# Test with empty frames (should also trigger <= 1 condition)
empty_frames = [MockInterpreterInfo(0, [MockThreadInfo(1, [])])]
collector.collect(empty_frames)
# Should not add any new entries
self.assertEqual(
len(collector.result), 1
) # Still just the single frame
# Test mixed single and multi-frame stacks
mixed_frames = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1,
[MockFrameInfo("single2.py", 20, "single_func2")],
), # Single frame
MockThreadInfo(
2,
[ # Multi-frame stack
MockFrameInfo("multi.py", 30, "multi_func1"),
MockFrameInfo("multi.py", 40, "multi_func2"),
],
),
],
),
]
collector.collect(mixed_frames)
# Should have recorded all functions
self.assertEqual(
len(collector.result), 4
) # single + single2 + multi1 + multi2
# Verify single frame handling
single2_key = ("single2.py", 20, "single_func2")
self.assertIn(single2_key, collector.result)
self.assertEqual(collector.result[single2_key]["direct_calls"], 1)
self.assertEqual(collector.result[single2_key]["cumulative_calls"], 1)
# Verify multi-frame handling still works
multi1_key = ("multi.py", 30, "multi_func1")
multi2_key = ("multi.py", 40, "multi_func2")
self.assertIn(multi1_key, collector.result)
self.assertIn(multi2_key, collector.result)
self.assertEqual(collector.result[multi1_key]["direct_calls"], 1)
self.assertEqual(
collector.result[multi2_key]["cumulative_calls"], 1
) # Called from multi1
def test_collapsed_stack_collector_with_empty_and_deep_stacks(self):
"""Test CollapsedStackCollector handles empty frames, single-frame stacks, and very deep call stacks."""
collector = CollapsedStackCollector(1000)
# Test with empty frames
collector.collect([])
self.assertEqual(len(collector.stack_counter), 0)
# Test with single frame stack
test_frames = [
MockInterpreterInfo(
0, [MockThreadInfo(1, [MockFrameInfo("file.py", 10, "func")])]
)
]
collector.collect(test_frames)
self.assertEqual(len(collector.stack_counter), 1)
(((path, thread_id), count),) = collector.stack_counter.items()
self.assertEqual(path, (("file.py", 10, "func"),))
self.assertEqual(thread_id, 1)
self.assertEqual(count, 1)
# Test with very deep stack
deep_stack = [MockFrameInfo(f"file{i}.py", i, f"func{i}") for i in range(100)]
test_frames = [MockInterpreterInfo(0, [MockThreadInfo(1, deep_stack)])]
collector = CollapsedStackCollector(1000)
collector.collect(test_frames)
# One aggregated path with 100 frames (reversed)
(((path_tuple, thread_id),),) = (collector.stack_counter.keys(),)
self.assertEqual(len(path_tuple), 100)
self.assertEqual(path_tuple[0], ("file99.py", 99, "func99"))
self.assertEqual(path_tuple[-1], ("file0.py", 0, "func0"))
self.assertEqual(thread_id, 1)
def test_pstats_collector_basic(self):
"""Test basic PstatsCollector functionality."""
collector = PstatsCollector(sample_interval_usec=1000)
# Test empty state
self.assertEqual(len(collector.result), 0)
self.assertEqual(len(collector.stats), 0)
# Test collecting sample data
test_frames = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1,
[
MockFrameInfo("file.py", 10, "func1"),
MockFrameInfo("file.py", 20, "func2"),
],
)
],
)
]
collector.collect(test_frames)
# Should have recorded calls for both functions
self.assertEqual(len(collector.result), 2)
self.assertIn(("file.py", 10, "func1"), collector.result)
self.assertIn(("file.py", 20, "func2"), collector.result)
# Top-level function should have direct call
self.assertEqual(
collector.result[("file.py", 10, "func1")]["direct_calls"], 1
)
self.assertEqual(
collector.result[("file.py", 10, "func1")]["cumulative_calls"], 1
)
# Calling function should have cumulative call but no direct calls
self.assertEqual(
collector.result[("file.py", 20, "func2")]["cumulative_calls"], 1
)
self.assertEqual(
collector.result[("file.py", 20, "func2")]["direct_calls"], 0
)
def test_pstats_collector_create_stats(self):
"""Test PstatsCollector stats creation."""
collector = PstatsCollector(
sample_interval_usec=1000000
) # 1 second intervals
test_frames = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1,
[
MockFrameInfo("file.py", 10, "func1"),
MockFrameInfo("file.py", 20, "func2"),
],
)
],
)
]
collector.collect(test_frames)
collector.collect(test_frames) # Collect twice
collector.create_stats()
# Check stats format: (direct_calls, cumulative_calls, tt, ct, callers)
func1_stats = collector.stats[("file.py", 10, "func1")]
self.assertEqual(func1_stats[0], 2) # direct_calls (top of stack)
self.assertEqual(func1_stats[1], 2) # cumulative_calls
self.assertEqual(
func1_stats[2], 2.0
) # tt (total time - 2 samples * 1 sec)
self.assertEqual(func1_stats[3], 2.0) # ct (cumulative time)
func2_stats = collector.stats[("file.py", 20, "func2")]
self.assertEqual(
func2_stats[0], 0
) # direct_calls (never top of stack)
self.assertEqual(
func2_stats[1], 2
) # cumulative_calls (appears in stack)
self.assertEqual(func2_stats[2], 0.0) # tt (no direct calls)
self.assertEqual(func2_stats[3], 2.0) # ct (cumulative time)
def test_collapsed_stack_collector_basic(self):
collector = CollapsedStackCollector(1000)
# Test empty state
self.assertEqual(len(collector.stack_counter), 0)
# Test collecting sample data
test_frames = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")]
)
],
)
]
collector.collect(test_frames)
# Should store one reversed path
self.assertEqual(len(collector.stack_counter), 1)
(((path, thread_id), count),) = collector.stack_counter.items()
expected_tree = (("file.py", 20, "func2"), ("file.py", 10, "func1"))
self.assertEqual(path, expected_tree)
self.assertEqual(thread_id, 1)
self.assertEqual(count, 1)
def test_collapsed_stack_collector_export(self):
collapsed_out = tempfile.NamedTemporaryFile(delete=False)
self.addCleanup(close_and_unlink, collapsed_out)
collector = CollapsedStackCollector(1000)
test_frames1 = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")]
)
],
)
]
test_frames2 = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")]
)
],
)
] # Same stack
test_frames3 = [
MockInterpreterInfo(
0, [MockThreadInfo(1, [MockFrameInfo("other.py", 5, "other_func")])]
)
]
collector.collect(test_frames1)
collector.collect(test_frames2)
collector.collect(test_frames3)
with captured_stdout(), captured_stderr():
collector.export(collapsed_out.name)
# Check file contents
with open(collapsed_out.name, "r") as f:
content = f.read()
lines = content.strip().split("\n")
self.assertEqual(len(lines), 2) # Two unique stacks
# Check collapsed format: tid:X;file:func:line;file:func:line count
stack1_expected = "tid:1;file.py:func2:20;file.py:func1:10 2"
stack2_expected = "tid:1;other.py:other_func:5 1"
self.assertIn(stack1_expected, lines)
self.assertIn(stack2_expected, lines)
def test_flamegraph_collector_basic(self):
"""Test basic FlamegraphCollector functionality."""
collector = FlamegraphCollector(1000)
# Empty collector should produce 'No Data'
data = collector._convert_to_flamegraph_format()
# With string table, name is now an index - resolve it using the strings array
strings = data.get("strings", [])
self.assertIn(resolve_name(data, strings), ("No Data", "No significant data"))
# Test collecting sample data
test_frames = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")]
)
],
)
]
collector.collect(test_frames)
# Convert and verify structure: func2 -> func1 with counts = 1
data = collector._convert_to_flamegraph_format()
# Expect promotion: root is the single child (func2), with func1 as its only child
strings = data.get("strings", [])
name = resolve_name(data, strings)
self.assertTrue(name.startswith("Program Root: "))
self.assertIn("func2 (file.py:20)", name) # formatted name
children = data.get("children", [])
self.assertEqual(len(children), 1)
child = children[0]
self.assertIn("func1 (file.py:10)", resolve_name(child, strings))
self.assertEqual(child["value"], 1)
def test_flamegraph_collector_export(self):
"""Test flamegraph HTML export functionality."""
flamegraph_out = tempfile.NamedTemporaryFile(
suffix=".html", delete=False
)
self.addCleanup(close_and_unlink, flamegraph_out)
collector = FlamegraphCollector(1000)
# Create some test data (use Interpreter/Thread objects like runtime)
test_frames1 = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")]
)
],
)
]
test_frames2 = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")]
)
],
)
] # Same stack
test_frames3 = [
MockInterpreterInfo(
0, [MockThreadInfo(1, [MockFrameInfo("other.py", 5, "other_func")])]
)
]
collector.collect(test_frames1)
collector.collect(test_frames2)
collector.collect(test_frames3)
# Export flamegraph
with captured_stdout(), captured_stderr():
collector.export(flamegraph_out.name)
# Verify file was created and contains valid data
self.assertTrue(os.path.exists(flamegraph_out.name))
self.assertGreater(os.path.getsize(flamegraph_out.name), 0)
# Check file contains HTML content
with open(flamegraph_out.name, "r", encoding="utf-8") as f:
content = f.read()
# Should be valid HTML
self.assertIn("<!doctype html>", content.lower())
self.assertIn("<html", content)
self.assertIn("Tachyon Profiler - Flamegraph", content)
self.assertIn("d3-flame-graph", content)
# Should contain the data
self.assertIn('"name":', content)
self.assertIn('"value":', content)
self.assertIn('"children":', content)
def test_gecko_collector_basic(self):
"""Test basic GeckoCollector functionality."""
collector = GeckoCollector(1000)
# Test empty state
self.assertEqual(len(collector.threads), 0)
self.assertEqual(collector.sample_count, 0)
self.assertEqual(len(collector.global_strings), 1) # "(root)"
# Test collecting sample data
test_frames = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1,
[MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")],
status=THREAD_STATUS_MAIN_THREAD,
)
],
)
]
collector.collect(test_frames)
# Should have recorded one thread and one sample
self.assertEqual(len(collector.threads), 1)
self.assertEqual(collector.sample_count, 1)
self.assertIn(1, collector.threads)
profile_data = collector._build_profile()
# Verify profile structure
self.assertIn("meta", profile_data)
self.assertIn("threads", profile_data)
self.assertIn("shared", profile_data)
# Check shared string table
shared = profile_data["shared"]
self.assertIn("stringArray", shared)
string_array = shared["stringArray"]
self.assertGreater(len(string_array), 0)
# Should contain our functions in the string array
self.assertIn("func1", string_array)
self.assertIn("func2", string_array)
# Check thread data structure
threads = profile_data["threads"]
self.assertEqual(len(threads), 1)
thread_data = threads[0]
self.assertTrue(thread_data["isMainThread"])
# Verify thread structure
self.assertIn("samples", thread_data)
self.assertIn("funcTable", thread_data)
self.assertIn("frameTable", thread_data)
self.assertIn("stackTable", thread_data)
# Verify samples
samples = thread_data["samples"]
self.assertEqual(len(samples["stack"]), 1)
self.assertEqual(len(samples["time"]), 1)
self.assertEqual(samples["length"], 1)
# Verify function table structure and content
func_table = thread_data["funcTable"]
self.assertIn("name", func_table)
self.assertIn("fileName", func_table)
self.assertIn("lineNumber", func_table)
self.assertEqual(func_table["length"], 2) # Should have 2 functions
# Verify actual function content through string array indices
func_names = []
for idx in func_table["name"]:
func_name = (
string_array[idx]
if isinstance(idx, int) and 0 <= idx < len(string_array)
else str(idx)
)
func_names.append(func_name)
self.assertIn("func1", func_names, f"func1 not found in {func_names}")
self.assertIn("func2", func_names, f"func2 not found in {func_names}")
# Verify frame table
frame_table = thread_data["frameTable"]
self.assertEqual(
frame_table["length"], 2
) # Should have frames for both functions
self.assertEqual(len(frame_table["func"]), 2)
# Verify stack structure
stack_table = thread_data["stackTable"]
self.assertGreater(stack_table["length"], 0)
self.assertGreater(len(stack_table["frame"]), 0)
@unittest.skipIf(is_emscripten, "threads not available")
def test_gecko_collector_export(self):
"""Test Gecko profile export functionality."""
gecko_out = tempfile.NamedTemporaryFile(suffix=".json", delete=False)
self.addCleanup(close_and_unlink, gecko_out)
collector = GeckoCollector(1000)
test_frames1 = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")]
)
],
)
]
test_frames2 = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")]
)
],
)
] # Same stack
test_frames3 = [
MockInterpreterInfo(
0, [MockThreadInfo(1, [MockFrameInfo("other.py", 5, "other_func")])]
)
]
collector.collect(test_frames1)
collector.collect(test_frames2)
collector.collect(test_frames3)
# Export gecko profile
with captured_stdout(), captured_stderr():
collector.export(gecko_out.name)
# Verify file was created and contains valid data
self.assertTrue(os.path.exists(gecko_out.name))
self.assertGreater(os.path.getsize(gecko_out.name), 0)
# Check file contains valid JSON
with open(gecko_out.name, "r") as f:
profile_data = json.load(f)
# Should be valid Gecko profile format
self.assertIn("meta", profile_data)
self.assertIn("threads", profile_data)
self.assertIn("shared", profile_data)
# Check meta information
self.assertIn("categories", profile_data["meta"])
self.assertIn("interval", profile_data["meta"])
# Check shared string table
self.assertIn("stringArray", profile_data["shared"])
self.assertGreater(len(profile_data["shared"]["stringArray"]), 0)
# Should contain our functions
string_array = profile_data["shared"]["stringArray"]
self.assertIn("func1", string_array)
self.assertIn("func2", string_array)
self.assertIn("other_func", string_array)
def test_gecko_collector_markers(self):
"""Test Gecko profile markers for GIL and CPU state tracking."""
collector = GeckoCollector(1000)
# Status combinations for different thread states
HAS_GIL_ON_CPU = (
THREAD_STATUS_HAS_GIL | THREAD_STATUS_ON_CPU
) # Running Python code
NO_GIL_ON_CPU = THREAD_STATUS_ON_CPU # Running native code
WAITING_FOR_GIL = THREAD_STATUS_GIL_REQUESTED # Waiting for GIL
# Simulate thread state transitions
collector.collect(
[
MockInterpreterInfo(
0,
[
MockThreadInfo(
1,
[MockFrameInfo("test.py", 10, "python_func")],
status=HAS_GIL_ON_CPU,
)
],
)
]
)
collector.collect(
[
MockInterpreterInfo(
0,
[
MockThreadInfo(
1,
[MockFrameInfo("test.py", 15, "wait_func")],
status=WAITING_FOR_GIL,
)
],
)
]
)
collector.collect(
[
MockInterpreterInfo(
0,
[
MockThreadInfo(
1,
[MockFrameInfo("test.py", 20, "python_func2")],
status=HAS_GIL_ON_CPU,
)
],
)
]
)
collector.collect(
[
MockInterpreterInfo(
0,
[
MockThreadInfo(
1,
[MockFrameInfo("native.c", 100, "native_func")],
status=NO_GIL_ON_CPU,
)
],
)
]
)
profile_data = collector._build_profile()
# Verify we have threads with markers
self.assertIn("threads", profile_data)
self.assertEqual(len(profile_data["threads"]), 1)
thread_data = profile_data["threads"][0]
# Check markers exist
self.assertIn("markers", thread_data)
markers = thread_data["markers"]
# Should have marker arrays
self.assertIn("name", markers)
self.assertIn("startTime", markers)
self.assertIn("endTime", markers)
self.assertIn("category", markers)
self.assertGreater(
markers["length"], 0, "Should have generated markers"
)
# Get marker names from string table
string_array = profile_data["shared"]["stringArray"]
marker_names = [string_array[idx] for idx in markers["name"]]
# Verify we have different marker types
marker_name_set = set(marker_names)
# Should have "Has GIL" markers (when thread had GIL)
self.assertIn(
"Has GIL", marker_name_set, "Should have 'Has GIL' markers"
)
# Should have "No GIL" markers (when thread didn't have GIL)
self.assertIn(
"No GIL", marker_name_set, "Should have 'No GIL' markers"
)
# Should have "On CPU" markers (when thread was on CPU)
self.assertIn(
"On CPU", marker_name_set, "Should have 'On CPU' markers"
)
# Should have "Waiting for GIL" markers (when thread was waiting)
self.assertIn(
"Waiting for GIL",
marker_name_set,
"Should have 'Waiting for GIL' markers",
)
# Verify marker structure
for i in range(markers["length"]):
# All markers should be interval markers (phase = 1)
self.assertEqual(
markers["phase"][i], 1, f"Marker {i} should be interval marker"
)
# All markers should have valid time range
start_time = markers["startTime"][i]
end_time = markers["endTime"][i]
self.assertLessEqual(
start_time,
end_time,
f"Marker {i} should have valid time range",
)
# All markers should have valid category
self.assertGreaterEqual(
markers["category"][i],
0,
f"Marker {i} should have valid category",
)
def test_pstats_collector_export(self):
collector = PstatsCollector(
sample_interval_usec=1000000
) # 1 second intervals
test_frames1 = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1,
[
MockFrameInfo("file.py", 10, "func1"),
MockFrameInfo("file.py", 20, "func2"),
],
)
],
)
]
test_frames2 = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1,
[
MockFrameInfo("file.py", 10, "func1"),
MockFrameInfo("file.py", 20, "func2"),
],
)
],
)
] # Same stack
test_frames3 = [
MockInterpreterInfo(
0,
[
MockThreadInfo(
1, [MockFrameInfo("other.py", 5, "other_func")]
)
],
)
]
collector.collect(test_frames1)
collector.collect(test_frames2)
collector.collect(test_frames3)
pstats_out = tempfile.NamedTemporaryFile(
suffix=".pstats", delete=False
)
self.addCleanup(close_and_unlink, pstats_out)
collector.export(pstats_out.name)
# Check file can be loaded with marshal
with open(pstats_out.name, "rb") as f:
stats_data = marshal.load(f)
# Should be a dictionary with the sampled marker
self.assertIsInstance(stats_data, dict)
self.assertIn(("__sampled__",), stats_data)
self.assertTrue(stats_data[("__sampled__",)])
# Should have function data
function_entries = [
k for k in stats_data.keys() if k != ("__sampled__",)
]
self.assertGreater(len(function_entries), 0)
# Check specific function stats format: (cc, nc, tt, ct, callers)
func1_key = ("file.py", 10, "func1")
func2_key = ("file.py", 20, "func2")
other_key = ("other.py", 5, "other_func")
self.assertIn(func1_key, stats_data)
self.assertIn(func2_key, stats_data)
self.assertIn(other_key, stats_data)
# Check func1 stats (should have 2 samples)
func1_stats = stats_data[func1_key]
self.assertEqual(func1_stats[0], 2) # total_calls
self.assertEqual(func1_stats[1], 2) # nc (non-recursive calls)
self.assertEqual(func1_stats[2], 2.0) # tt (total time)
self.assertEqual(func1_stats[3], 2.0) # ct (cumulative time)
def test_flamegraph_collector_stats_accumulation(self):
"""Test that FlamegraphCollector accumulates stats across samples."""
collector = FlamegraphCollector(sample_interval_usec=1000)
# First sample
stack_frames_1 = [
MockInterpreterInfo(
0,
[
MockThreadInfo(1, [MockFrameInfo("a.py", 1, "func_a")], status=THREAD_STATUS_HAS_GIL),
MockThreadInfo(2, [MockFrameInfo("b.py", 2, "func_b")], status=THREAD_STATUS_ON_CPU),
],
)
]
collector.collect(stack_frames_1)
self.assertEqual(collector.thread_status_counts["has_gil"], 1)
self.assertEqual(collector.thread_status_counts["on_cpu"], 1)
self.assertEqual(collector.thread_status_counts["total"], 2)
# Second sample
stack_frames_2 = [
MockInterpreterInfo(
0,
[
MockThreadInfo(1, [MockFrameInfo("a.py", 1, "func_a")], status=THREAD_STATUS_GIL_REQUESTED),
MockThreadInfo(2, [MockFrameInfo("b.py", 2, "func_b")], status=THREAD_STATUS_HAS_GIL),
MockThreadInfo(3, [MockFrameInfo("c.py", 3, "func_c")], status=THREAD_STATUS_ON_CPU),
],
)
]
collector.collect(stack_frames_2)
# Should accumulate
self.assertEqual(collector.thread_status_counts["has_gil"], 2) # 1 + 1
self.assertEqual(collector.thread_status_counts["on_cpu"], 2) # 1 + 1
self.assertEqual(collector.thread_status_counts["gil_requested"], 1) # 0 + 1
self.assertEqual(collector.thread_status_counts["total"], 5) # 2 + 3
# Test GC sample tracking
stack_frames_gc = [
MockInterpreterInfo(
0,
[
MockThreadInfo(1, [MockFrameInfo("~", 0, "<GC>")], status=THREAD_STATUS_HAS_GIL),
],
)
]
collector.collect(stack_frames_gc)
self.assertEqual(collector.samples_with_gc_frames, 1)
# Another sample without GC
collector.collect(stack_frames_1)
self.assertEqual(collector.samples_with_gc_frames, 1) # Still 1
# Another GC sample
collector.collect(stack_frames_gc)
self.assertEqual(collector.samples_with_gc_frames, 2)
def test_flamegraph_collector_per_thread_stats(self):
"""Test per-thread statistics tracking in FlamegraphCollector."""
collector = FlamegraphCollector(sample_interval_usec=1000)
# Multiple threads with different states
stack_frames = [
MockInterpreterInfo(
0,
[
MockThreadInfo(1, [MockFrameInfo("a.py", 1, "func_a")], status=THREAD_STATUS_HAS_GIL),
MockThreadInfo(2, [MockFrameInfo("b.py", 2, "func_b")], status=THREAD_STATUS_ON_CPU),
MockThreadInfo(3, [MockFrameInfo("c.py", 3, "func_c")], status=THREAD_STATUS_GIL_REQUESTED),
],
)
]
collector.collect(stack_frames)
# Check per-thread stats
self.assertIn(1, collector.per_thread_stats)
self.assertIn(2, collector.per_thread_stats)
self.assertIn(3, collector.per_thread_stats)
# Thread 1: has GIL
self.assertEqual(collector.per_thread_stats[1]["has_gil"], 1)
self.assertEqual(collector.per_thread_stats[1]["on_cpu"], 0)
self.assertEqual(collector.per_thread_stats[1]["total"], 1)
# Thread 2: on CPU
self.assertEqual(collector.per_thread_stats[2]["has_gil"], 0)
self.assertEqual(collector.per_thread_stats[2]["on_cpu"], 1)
self.assertEqual(collector.per_thread_stats[2]["total"], 1)
# Thread 3: waiting
self.assertEqual(collector.per_thread_stats[3]["gil_requested"], 1)
self.assertEqual(collector.per_thread_stats[3]["total"], 1)
# Test accumulation across samples
stack_frames_2 = [
MockInterpreterInfo(
0,