-
Notifications
You must be signed in to change notification settings - Fork 536
Expand file tree
/
Copy pathtest_stack.py
More file actions
1321 lines (1079 loc) · 45.3 KB
/
Copy pathtest_stack.py
File metadata and controls
1321 lines (1079 loc) · 45.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
import _thread
import os
from pathlib import Path
import sys
import threading
import time
from typing import TYPE_CHECKING
from typing import Generator
from unittest.mock import patch
import uuid
import pytest
from pytest import FixtureRequest
from pytest import MonkeyPatch
from ddtrace import ext
from ddtrace.internal.datadog.profiling import ddup
from ddtrace.profiling.collector import stack
from ddtrace.trace import Tracer
from tests.conftest import get_original_test_name
from tests.profiling.collector import pprof_utils
from tests.profiling.collector import test_collector
if TYPE_CHECKING:
from tests.profiling.collector.pprof_pb2 import Sample # pyright: ignore[reportMissingModuleSource]
# Python 3.11.9 is not compatible with gevent, https://github.com/gevent/gevent/issues/2040
# https://github.com/python/cpython/issues/117983
# The fix was not backported to 3.11. The fix was first released in 3.12.5 for
# Python 3.12. Tested with Python 3.11.8 and 3.12.5 to confirm the issue.
GEVENT_COMPATIBLE_WITH_PYTHON_VERSION = os.getenv("DD_PROFILE_TEST_GEVENT", False) and (
sys.version_info < (3, 11, 9) or sys.version_info >= (3, 12, 5)
)
def _main_thread_has_native_id() -> bool:
"""True if main thread has native_id (False for _DummyThread which lacks _native_id)."""
return getattr(threading.main_thread(), "native_id", None) is not None
def func1() -> None:
return func2()
def func2() -> None:
return func3()
def func3() -> None:
return func4()
def func4() -> None:
return func5()
def func5() -> None:
return time.sleep(1)
# Use subprocess as ddup config persists across tests.
@pytest.mark.subprocess(
env=dict(
DD_PROFILING_MAX_FRAMES="5",
DD_PROFILING_OUTPUT_PPROF="/tmp/test_collect_truncate",
)
)
def test_collect_truncate() -> None:
import os
from ddtrace.profiling import profiler
from tests.profiling.collector import pprof_utils
from tests.profiling.collector.test_stack import func1
pprof_prefix = os.environ["DD_PROFILING_OUTPUT_PPROF"]
output_filename = pprof_prefix + "." + str(os.getpid())
max_nframes = int(os.environ["DD_PROFILING_MAX_FRAMES"])
p = profiler.Profiler()
p.start()
func1()
p.stop()
profile = pprof_utils.parse_newest_profile(output_filename)
samples = pprof_utils.get_samples_with_value_type(profile, "wall-time")
assert len(samples) > 0
for sample in samples:
# stack adds one extra frame for "%d frames omitted" message
assert len(sample.location_id) <= max_nframes + 1, len(sample.location_id)
def test_stack_locations(tmp_path: Path) -> None:
test_name = "test_stack_locations"
pprof_prefix = str(tmp_path / test_name)
output_filename = pprof_prefix + "." + str(os.getpid())
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
def baz() -> None:
time.sleep(0.1)
def bar() -> None:
baz()
def foo() -> None:
bar()
with stack.StackCollector():
for _ in range(10):
foo()
ddup.upload()
profile = pprof_utils.parse_newest_profile(output_filename)
samples = pprof_utils.get_samples_with_value_type(profile, "wall-time")
assert len(samples) > 0
# thread_name correlation is unreliable when main thread is _DummyThread (no native_id)
expected_thread_name = "MainThread" if _main_thread_has_native_id() else None
expected_sample = pprof_utils.StackEvent(
thread_id=_thread.get_ident(),
thread_name=expected_thread_name,
locations=[
pprof_utils.StackLocation(
function_name="baz",
filename="test_stack.py",
line_no=baz.__code__.co_firstlineno + 1,
),
pprof_utils.StackLocation(
function_name="bar",
filename="test_stack.py",
line_no=bar.__code__.co_firstlineno + 1,
),
pprof_utils.StackLocation(
function_name="foo",
filename="test_stack.py",
line_no=foo.__code__.co_firstlineno + 1,
),
],
)
pprof_utils.assert_profile_has_sample(profile, samples=samples, expected_sample=expected_sample)
def test_push_span(tmp_path: Path, tracer: Tracer) -> None:
test_name = "test_push_span"
pprof_prefix = str(tmp_path / test_name)
output_filename = pprof_prefix + "." + str(os.getpid())
tracer._endpoint_call_counter_span_processor.enable()
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
resource = str(uuid.uuid4())
span_type = ext.SpanTypes.WEB
with stack.StackCollector(
tracer=tracer,
):
with tracer.trace("foobar", resource=resource, span_type=span_type) as span:
span_id = span.span_id
local_root_span_id = span._local_root.span_id
for _ in range(10):
time.sleep(0.1)
ddup.upload(tracer=tracer)
profile = pprof_utils.parse_newest_profile(output_filename)
samples_with_span_id = pprof_utils.get_samples_with_label_key(profile, "span id")
samples: list[Sample] = []
for sample in samples_with_span_id:
locations = [pprof_utils.get_location_from_id(profile, location_id) for location_id in sample.location_id]
if any(location.filename.endswith("test_stack.py") for location in locations):
samples.append(sample)
assert samples, "No sample found with locations in test_stack.py"
pprof_utils.assert_profile_has_sample(
profile,
samples=samples,
expected_sample=pprof_utils.StackEvent(
span_id=span_id,
local_root_span_id=local_root_span_id,
trace_type=span_type,
trace_endpoint=resource,
),
print_samples_on_failure=True,
)
def test_push_span_unregister_thread(tmp_path: Path, monkeypatch: MonkeyPatch, tracer: Tracer) -> None:
with patch("ddtrace.internal.datadog.profiling.stack.unregister_thread") as unregister_thread:
tracer._endpoint_call_counter_span_processor.enable()
test_name = "test_push_span_unregister_thread"
pprof_prefix = str(tmp_path / test_name)
output_filename = pprof_prefix + "." + str(os.getpid())
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
resource = str(uuid.uuid4())
span_type = ext.SpanTypes.WEB
def target_fun() -> None:
for _ in range(10):
time.sleep(0.1)
with stack.StackCollector(
tracer=tracer,
):
with tracer.trace("foobar", resource=resource, span_type=span_type) as span:
span_id = span.span_id
local_root_span_id = span._local_root.span_id
t = threading.Thread(target=target_fun)
t.start()
t.join()
thread_id = t.ident
ddup.upload(tracer=tracer)
profile = pprof_utils.parse_newest_profile(output_filename)
samples_with_span_id = pprof_utils.get_samples_with_label_key(profile, "span id")
samples: list[Sample] = []
for sample in samples_with_span_id:
locations = [pprof_utils.get_location_from_id(profile, location_id) for location_id in sample.location_id]
if any(location.filename.endswith("test_stack.py") for location in locations):
samples.append(sample)
assert samples, "No sample found with locations in test_stack.py"
pprof_utils.assert_profile_has_sample(
profile,
samples=samples,
expected_sample=pprof_utils.StackEvent(
span_id=span_id,
local_root_span_id=local_root_span_id,
trace_type=span_type,
trace_endpoint=resource,
),
print_samples_on_failure=True,
)
unregister_thread.assert_called_with(thread_id)
def test_push_non_web_span(tmp_path: Path, tracer: Tracer) -> None:
tracer._endpoint_call_counter_span_processor.enable()
test_name = "test_push_non_web_span"
pprof_prefix = str(tmp_path / test_name)
output_filename = pprof_prefix + "." + str(os.getpid())
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
resource = str(uuid.uuid4())
span_type = ext.SpanTypes.SQL
with stack.StackCollector(
tracer=tracer,
):
with tracer.trace("foobar", resource=resource, span_type=span_type) as span:
span_id = span.span_id
local_root_span_id = span._local_root.span_id
for _ in range(10):
time.sleep(0.1)
ddup.upload(tracer=tracer)
profile = pprof_utils.parse_newest_profile(output_filename)
samples_with_span_id = pprof_utils.get_samples_with_label_key(profile, "span id")
samples: list[Sample] = []
for sample in samples_with_span_id:
locations = [pprof_utils.get_location_from_id(profile, location_id) for location_id in sample.location_id]
if any(location.filename.endswith("test_stack.py") for location in locations):
samples.append(sample)
assert samples, "No sample found with locations in test_stack.py"
pprof_utils.assert_profile_has_sample(
profile,
samples=samples,
expected_sample=pprof_utils.StackEvent(
span_id=span_id,
local_root_span_id=local_root_span_id,
trace_type=span_type,
# trace_endpoint is not set for non-web spans
),
print_samples_on_failure=True,
)
def test_push_span_none_span_type(tmp_path: Path, tracer: Tracer) -> None:
# Test for https://github.com/DataDog/dd-trace-py/issues/11141
test_name = "test_push_span_none_span_type"
pprof_prefix = str(tmp_path / test_name)
output_filename = pprof_prefix + "." + str(os.getpid())
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
tracer._endpoint_call_counter_span_processor.enable()
resource = str(uuid.uuid4())
with stack.StackCollector(
tracer=tracer,
):
# Explicitly set None span_type as the default could change in the
# future.
with tracer.trace("foobar", resource=resource, span_type=None) as span:
span_id = span.span_id
local_root_span_id = span._local_root.span_id
for _ in range(10):
time.sleep(0.1)
ddup.upload(tracer=tracer)
profile = pprof_utils.parse_newest_profile(output_filename)
samples_with_span_id = pprof_utils.get_samples_with_label_key(profile, "span id")
samples: list[Sample] = []
for sample in samples_with_span_id:
locations = [pprof_utils.get_location_from_id(profile, location_id) for location_id in sample.location_id]
if any(location.filename.endswith("test_stack.py") for location in locations):
samples.append(sample)
assert samples, "No sample found with locations in test_stack.py"
pprof_utils.assert_profile_has_sample(
profile,
samples=samples,
expected_sample=pprof_utils.StackEvent(
span_id=span_id,
local_root_span_id=local_root_span_id,
# span_type is None
# trace_endpoint is not set for non-web spans
),
print_samples_on_failure=True,
)
def test_collect_once_with_class(tmp_path: Path) -> None:
class SomeClass(object):
@classmethod
def sleep_class(cls) -> None:
return cls().sleep_instance()
def sleep_instance(self) -> None:
for _ in range(10):
time.sleep(0.1)
test_name = "test_collect_once_with_class"
pprof_prefix = str(tmp_path / test_name)
output_filename = pprof_prefix + "." + str(os.getpid())
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
with stack.StackCollector():
SomeClass.sleep_class()
ddup.upload()
profile = pprof_utils.parse_newest_profile(output_filename)
samples = pprof_utils.get_samples_with_value_type(profile, "wall-time")
assert len(samples) > 0
pprof_utils.assert_profile_has_sample(
profile,
samples=samples,
expected_sample=pprof_utils.StackEvent(
thread_id=_thread.get_ident(),
thread_name="MainThread",
locations=[
pprof_utils.StackLocation(
function_name="sleep_instance",
filename="test_stack.py",
line_no=SomeClass.sleep_instance.__code__.co_firstlineno + 2,
),
pprof_utils.StackLocation(
function_name="sleep_class",
filename="test_stack.py",
line_no=SomeClass.sleep_class.__code__.co_firstlineno + 2,
),
pprof_utils.StackLocation(
function_name="test_collect_once_with_class",
filename="test_stack.py",
line_no=test_collect_once_with_class.__code__.co_firstlineno + 20,
),
],
),
print_samples_on_failure=True,
)
def test_collect_once_with_class_not_right_type(tmp_path: Path) -> None:
"""Test that the stack collector profiles methods with non-conventional parameter names.
Verifies the profiler handles methods where parameters don't follow standard conventions
(e.g., using 'foobar' instead of 'self' or 'cls').
"""
class SomeClass(object):
@classmethod
def sleep_class(foobar, cls) -> None: # pyright: ignore[reportSelfClsParameterName]
return foobar().sleep_instance(cls)
def sleep_instance(foobar, self) -> None: # pyright: ignore[reportUnusedParameter, reportSelfClsParameterName]
for _ in range(10):
time.sleep(0.1)
test_name = "test_collect_once_with_class"
pprof_prefix = str(tmp_path / test_name)
output_filename = pprof_prefix + "." + str(os.getpid())
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
with stack.StackCollector():
SomeClass.sleep_class(123)
ddup.upload()
profile = pprof_utils.parse_newest_profile(output_filename)
samples = pprof_utils.get_samples_with_value_type(profile, "wall-time")
assert len(samples) > 0
pprof_utils.assert_profile_has_sample(
profile,
samples=samples,
expected_sample=pprof_utils.StackEvent(
thread_id=_thread.get_ident(),
thread_name="MainThread",
locations=[
pprof_utils.StackLocation(
function_name="sleep_instance",
filename="test_stack.py",
line_no=SomeClass.sleep_instance.__code__.co_firstlineno + 2,
),
pprof_utils.StackLocation(
function_name="sleep_class",
filename="test_stack.py",
line_no=SomeClass.sleep_class.__code__.co_firstlineno + 2,
),
pprof_utils.StackLocation(
function_name="test_collect_once_with_class_not_right_type",
filename="test_stack.py",
line_no=test_collect_once_with_class_not_right_type.__code__.co_firstlineno + 26,
),
],
),
print_samples_on_failure=True,
)
def _fib(n: int) -> int:
if n == 1:
return 1
elif n == 0:
return 0
else:
return _fib(n - 1) + _fib(n - 2)
@pytest.mark.skipif(
not GEVENT_COMPATIBLE_WITH_PYTHON_VERSION,
reason=f"gevent is not compatible with Python {'.'.join(map(str, tuple(sys.version_info)[:3]))}",
)
@pytest.mark.subprocess(ddtrace_run=True)
def test_collect_gevent_thread_task() -> None:
from gevent import monkey
monkey.patch_all()
import os
import threading
import time
from ddtrace.internal.datadog.profiling import ddup
from ddtrace.profiling.collector import stack
from tests.profiling.collector import pprof_utils
from tests.profiling.collector.test_stack import _fib
from tests.profiling.collector.test_stack import _main_thread_has_native_id
test_name = "test_collect_gevent_thread_task"
pprof_prefix = "/tmp/" + test_name
output_filename = pprof_prefix + "." + str(os.getpid())
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
# Start some (green)threads
def _do_fib() -> None:
for _ in range(5):
# spend some time in CPU so the profiler can catch something
# On a Mac w/ Apple M3 MAX with Python 3.11 it takes about 200ms to calculate _fib(32)
# And _fib() is called 5 times so it should take about 1 second
# We use 5 threads below so it should take about 5 seconds
_fib(32)
# Just make sure gevent switches threads/greenlets
time.sleep(0)
threads = []
with stack.StackCollector():
for i in range(5):
t = threading.Thread(target=_do_fib, name=f"TestThread {i}")
t.start()
threads.append(t)
for t in threads:
t.join()
ddup.upload()
profile = pprof_utils.parse_newest_profile(output_filename)
samples = pprof_utils.get_samples_with_label_key(profile, "task name")
assert len(samples) > 0
# thread_name correlation is unreliable when main thread is _DummyThread (no native_id)
expected_thread_name = "MainThread" if _main_thread_has_native_id() else None
pprof_utils.assert_profile_has_sample(
profile,
samples,
expected_sample=pprof_utils.StackEvent(
thread_name=expected_thread_name,
task_name=r"Greenlet-\d+$",
locations=[
# Since we're using recursive function _fib(), we expect to have
# multiple locations for _fib(n) = _fib(n-1) + _fib(n-2)
pprof_utils.StackLocation(
filename="test_stack.py",
function_name="_fib",
line_no=_fib.__code__.co_firstlineno + 6,
),
pprof_utils.StackLocation(
filename="test_stack.py",
function_name="_fib",
line_no=_fib.__code__.co_firstlineno + 6,
),
pprof_utils.StackLocation(
filename="test_stack.py",
function_name="_fib",
line_no=_fib.__code__.co_firstlineno + 6,
),
],
),
print_samples_on_failure=True,
)
@pytest.mark.skipif(
not GEVENT_COMPATIBLE_WITH_PYTHON_VERSION,
reason=f"gevent is not compatible with Python {'.'.join(map(str, tuple(sys.version_info)[:3]))}",
)
@pytest.mark.subprocess(ddtrace_run=True)
def test_gevent_greenlets_emit_task_labels() -> None:
"""Gevent greenlet wall-time samples must carry task_name and task_id labels."""
import os
import gevent
from gevent import monkey
monkey.patch_all()
from ddtrace.internal.datadog.profiling import ddup
from ddtrace.profiling.collector import stack
from tests.profiling.collector import pprof_utils
from tests.profiling.collector.test_stack import _fib
from tests.profiling.collector.test_stack import _main_thread_has_native_id
test_name = "test_gevent_greenlets_emit_task_labels"
pprof_prefix = "/tmp/" + test_name
output_filename = pprof_prefix + "." + str(os.getpid())
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
def cpu_work() -> None:
for _ in range(3):
_fib(28)
gevent.sleep(0)
with stack.StackCollector():
named_greenlets: list[gevent.Greenlet] = []
for i in range(3):
g = gevent.spawn(cpu_work)
g.name = f"Greenlet-{i}"
named_greenlets.append(g)
gevent.joinall(named_greenlets, timeout=30)
ddup.upload()
profile = pprof_utils.parse_newest_profile(output_filename)
samples = pprof_utils.get_samples_with_label_key(profile, "task name")
assert len(samples) > 0
st = profile.string_table
# check Greenlet-X is in the task name for each sample
greenlet_samples_with_task_name = [s for s in samples if any("Greenlet" in st[label.str] for label in s.label)]
assert len(greenlet_samples_with_task_name) > 0, "No greenlet samples with task name found"
# check sample with task info also has task id
for sample in greenlet_samples_with_task_name:
assert any(st[label.key] == "task id" for label in sample.label), (
f"No task id found in greenlet sample, labels: {sample.label}"
)
# Greenlet samples must still carry the real OS thread identity (MainThread),
expected_thread_name = "MainThread" if _main_thread_has_native_id() else None
pprof_utils.assert_profile_has_sample(
profile,
samples,
expected_sample=pprof_utils.StackEvent(
thread_name=expected_thread_name,
task_name=r"Greenlet-\d+$",
locations=[
pprof_utils.StackLocation(
filename="test_stack.py",
function_name="_fib",
line_no=_fib.__code__.co_firstlineno + 6,
),
],
),
print_samples_on_failure=True,
)
@pytest.mark.skipif(
not GEVENT_COMPATIBLE_WITH_PYTHON_VERSION,
reason=f"gevent is not compatible with Python {'.'.join(map(str, tuple(sys.version_info)[:3]))}",
)
@pytest.mark.subprocess(
env=dict(
DD_PROFILING_OUTPUT_PPROF="/tmp/test_collect_gevent_task_started_before_profiler",
),
err=None,
)
def test_collect_gevent_task_started_before_profiler() -> None:
from gevent import monkey
monkey.patch_all()
import os
import threading
import time
import gevent
should_stop = threading.Event()
def pre_started_greenlet_task() -> None:
# Keep this greenlet alive long enough to be sampled after profiler start.
while not should_stop.is_set():
start = time.time()
while time.time() - start < 0.01:
pass
gevent.sleep(0)
# Start a named greenlet before profiler startup (remote-enable scenario).
pre_started_greenlet_name = "pre-started-before-profiler"
pre_started_greenlet = gevent.spawn(pre_started_greenlet_task)
pre_started_greenlet.name = pre_started_greenlet_name
gevent.sleep(0.05)
# Import profiler modules after gevent patching and greenlet creation
from ddtrace.profiling import profiler
from tests.profiling.collector import pprof_utils
from tests.profiling.collector.test_stack import _main_thread_has_native_id
p = profiler.Profiler()
p.start()
try:
gevent.sleep(1.0)
finally:
should_stop.set()
pre_started_greenlet.join(timeout=2)
p.stop()
output_filename = os.environ["DD_PROFILING_OUTPUT_PPROF"] + "." + str(os.getpid())
profile = pprof_utils.parse_newest_profile(output_filename)
samples = pprof_utils.get_samples_with_label_key(profile, "task name")
assert len(samples) > 0
# thread_name correlation is unreliable when main thread is _DummyThread (no native_id)
expected_thread_name = "MainThread" if _main_thread_has_native_id() else None
pprof_utils.assert_profile_has_sample(
profile,
samples,
expected_sample=pprof_utils.StackEvent(
thread_name=expected_thread_name,
task_name=pre_started_greenlet_name,
locations=[
pprof_utils.StackLocation(
function_name=pre_started_greenlet_task.__name__,
filename="test_stack.py",
line_no=-1,
)
],
),
print_samples_on_failure=True,
)
@pytest.mark.skipif(
not GEVENT_COMPATIBLE_WITH_PYTHON_VERSION,
reason=f"gevent is not compatible with Python {'.'.join(map(str, tuple(sys.version_info)[:3]))}",
)
@pytest.mark.subprocess(
env=dict(
DD_PROFILING_OUTPUT_PPROF="/tmp/test_gevent_cpu_time_total_accuracy",
_DD_PROFILING_STACK_ADAPTIVE_SAMPLING_ENABLED="0",
),
err=None,
)
def test_gevent_cpu_time_total_accuracy() -> None:
"""Verify that the sum of cpu-time across all profile samples roughly matches
the actual process CPU time consumed by gevent workers.
Without the on-CPU swap in unwind_greenlets, when the running greenlet is
not the first entry in current_greenlets, render_task_begin starts a new
sample for it and pushes thread_state.cpu_time_ns a second time (the first
push already happened on the sample inherited from render_thread_begin).
For M=4 workers, the over-count converges to ~1.5-1.6x of the real CPU
consumed by the process. With the swap in place, the on-CPU greenlet
always reuses the first sample and the duplicate push is avoided.
Adaptive sampling is disabled to mirror the experimental measurement cell
that gave the cleanest 1.6x signal; this also keeps the sample interval
deterministic across the timed region.
"""
from gevent import monkey
monkey.patch_all()
import os
import time
import gevent
from ddtrace.profiling import profiler
from tests.profiling.collector import pprof_utils
DURATION_S = 3.0
CPU_BURN_S = 0.01
SLEEP_S = 0.05
NUM_WORKERS = 4
def worker() -> None:
deadline = time.monotonic() + DURATION_S
while time.monotonic() < deadline:
burn_until = time.process_time_ns() + int(CPU_BURN_S * 1e9)
while time.process_time_ns() < burn_until:
pass
gevent.sleep(SLEEP_S)
p = profiler.Profiler()
p.start()
try:
# Stagger workers by CPU_BURN_S so their CPU bursts interleave with
# each other's sleep, which spreads the on-CPU greenlet across the
# unordered_map iteration order. Without staggering, the same greenlet
# tends to win the on-CPU position each sample, masking the bug.
workers = []
cpu_start_ns = time.process_time_ns()
for i in range(NUM_WORKERS):
if i > 0:
gevent.sleep(CPU_BURN_S)
workers.append(gevent.spawn(worker))
gevent.joinall(workers, timeout=DURATION_S + 10)
cpu_end_ns = time.process_time_ns()
finally:
p.stop()
assert all(g.dead for g in workers), "gevent workers did not finish within timeout"
actual_cpu_ns = cpu_end_ns - cpu_start_ns
assert actual_cpu_ns > 0, "process_time_ns did not advance"
output_filename = os.environ["DD_PROFILING_OUTPUT_PPROF"] + "." + str(os.getpid())
profile = pprof_utils.parse_newest_profile(output_filename)
cpu_time_index = pprof_utils.get_sample_type_index(profile, "cpu-time")
profile_cpu_ns = sum(sample.value[cpu_time_index] for sample in profile.sample)
ratio = profile_cpu_ns / actual_cpu_ns
# Bounds picked from measured ratios across local Mac (n=10) and CI Linux
# py3.9-3.14 (n=6). With the fix applied: observed range was 0.975 - 1.058.
# Without the fix (bug): observed range was 1.61 - 1.63 (CI, n=5).
#
# Upper bound 1.20:
# - ~14% above the worst observed fixed value (1.058)
# - ~25% below the smallest observed bug value (1.61)
# Lower bound 0.85:
# - ~13% below the worst observed fixed value (0.975)
# - rejects a regression that drops real CPU (e.g. reintroducing the
# is_running() gate removed in PR #16273) which would push the ratio
# toward 0.
#
# These bounds exist to catch regressions while staying flake-safe across
# CI runners. They are NOT a claim about the profiler's CPU attribution
# accuracy.
assert 0.85 <= ratio <= 1.20, (
f"profile cpu-time total ({profile_cpu_ns / 1e9:.3f}s) does not match "
f"actual process CPU time ({actual_cpu_ns / 1e9:.3f}s); ratio={ratio:.2f} "
f"(expected ~1.0, bug produces ~1.6)"
)
def test_repr() -> None:
test_collector._test_repr(
stack.StackCollector,
"StackCollector(status=<ServiceStatus.STOPPED: 'stopped'>, nframes=64, tracer=None)",
)
# Tests from tests/profiling/collector/test_stack.py
# Function to use for stress-test of polling
MAX_FN_NUM = 30
FN_TEMPLATE = """def _f{num}():
return _f{nump1}()"""
for num in range(MAX_FN_NUM):
exec(FN_TEMPLATE.format(num=num, nump1=num + 1))
exec(
"""def _f{MAX_FN_NUM}():
try:
raise ValueError('test')
except Exception:
time.sleep(2)""".format(MAX_FN_NUM=MAX_FN_NUM)
)
def test_stress_threads_run_as_thread(tmp_path: Path) -> None:
test_name = "test_stress_threads_run_as_thread"
pprof_prefix = str(tmp_path / test_name)
output_filename = pprof_prefix + "." + str(os.getpid())
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
quit_thread = threading.Event()
def wait_for_quit() -> None:
quit_thread.wait()
with stack.StackCollector():
NB_THREADS = 40
threads = []
for _ in range(NB_THREADS):
t = threading.Thread(target=wait_for_quit)
t.start()
threads.append(t)
time.sleep(3)
quit_thread.set()
for t in threads:
t.join()
ddup.upload()
profile = pprof_utils.parse_newest_profile(output_filename)
samples = pprof_utils.get_samples_with_value_type(profile, "wall-time")
assert len(samples) > 0
# if you don't need to check the output profile, you can use this fixture
@pytest.fixture
def tracer_and_collector(
tracer: Tracer, request: FixtureRequest, tmp_path: Path
) -> Generator[tuple[Tracer, stack.StackCollector], None, None]:
test_name = get_original_test_name(request)
pprof_prefix = str(tmp_path / test_name)
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
c = stack.StackCollector(tracer=tracer)
c.start()
try:
yield tracer, c
finally:
c.stop()
ddup.upload(tracer=tracer)
def test_collect_span_id(tracer: Tracer, tmp_path: Path) -> None:
test_name = "test_collect_span_id"
pprof_prefix = str(tmp_path / test_name)
output_filename = pprof_prefix + "." + str(os.getpid())
assert ddup.is_available
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
tracer._endpoint_call_counter_span_processor.enable()
with stack.StackCollector(tracer=tracer):
resource = str(uuid.uuid4())
span_type = ext.SpanTypes.WEB
with tracer.start_span("foobar", activate=True, resource=resource, span_type=span_type) as span:
for _ in range(10):
time.sleep(0.1)
span_id = span.span_id
local_root_span_id = span._local_root.span_id
ddup.upload(tracer=tracer)
profile = pprof_utils.parse_newest_profile(output_filename)
samples = pprof_utils.get_samples_with_label_key(profile, "trace endpoint")
pprof_utils.assert_profile_has_sample(
profile,
samples,
expected_sample=pprof_utils.StackEvent(
thread_id=_thread.get_ident(),
span_id=span_id,
trace_type=span_type,
local_root_span_id=local_root_span_id,
trace_endpoint=resource,
locations=[
pprof_utils.StackLocation(
filename=os.path.basename(__file__),
function_name=test_name,
line_no=test_collect_span_id.__code__.co_firstlineno + 16,
)
],
),
print_samples_on_failure=True,
)
def test_collect_span_resource_after_finish(tracer: Tracer, tmp_path: Path, request: FixtureRequest) -> None:
test_name = get_original_test_name(request)
pprof_prefix = str(tmp_path / test_name)
output_filename = pprof_prefix + "." + str(os.getpid())
ddup.config(env="test", service=test_name, version="my_version", output_filename=pprof_prefix)
ddup.start()
ddup.upload()
tracer._endpoint_call_counter_span_processor.enable()
with stack.StackCollector(tracer=tracer):
resource = str(uuid.uuid4())
span_type = ext.SpanTypes.WEB
span = tracer.start_span("foobar", activate=True, span_type=span_type, resource=resource)
for _ in range(10):
time.sleep(0.1)
ddup.upload(tracer=tracer)
span.finish()
profile = pprof_utils.parse_newest_profile(output_filename)
samples = profile.sample
pprof_utils.assert_profile_has_sample(
profile,
samples,
expected_sample=pprof_utils.StackEvent(
thread_id=_thread.get_ident(),
span_id=span.span_id,
trace_type=span_type,
# Looks like the endpoint is not collected if the span is not finished
# trace_endpoint=resource,
locations=[
pprof_utils.StackLocation(
filename=os.path.basename(__file__),
function_name=test_name,
line_no=test_collect_span_resource_after_finish.__code__.co_firstlineno + 15,
)
],
),
print_samples_on_failure=True,
)