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
|
import inspect
import os
import sentry_sdk
import sys
import threading
import time
import warnings
from collections import defaultdict
from unittest import mock
import pytest
from sentry_sdk import start_transaction
from sentry_sdk.profiler.transaction_profiler import (
GeventScheduler,
Profile,
Scheduler,
ThreadScheduler,
setup_profiler,
)
from sentry_sdk.profiler.utils import (
extract_frame,
extract_stack,
frame_id,
get_frame_name,
)
from sentry_sdk._lru_cache import LRUCache
try:
import gevent
except ImportError:
gevent = None
requires_gevent = pytest.mark.skipif(gevent is None, reason="gevent not enabled")
def process_test_sample(sample):
# insert a mock hashable for the stack
return [(tid, (stack, stack)) for tid, stack in sample]
def non_experimental_options(mode=None, sample_rate=None):
return {"profiler_mode": mode, "profiles_sample_rate": sample_rate}
def experimental_options(mode=None, sample_rate=None):
return {
"_experiments": {"profiler_mode": mode, "profiles_sample_rate": sample_rate}
}
@pytest.mark.parametrize(
"mode",
[pytest.param("foo")],
)
@pytest.mark.parametrize(
"make_options",
[
pytest.param(experimental_options, id="experiment"),
pytest.param(non_experimental_options, id="non experimental"),
],
)
def test_profiler_invalid_mode(mode, make_options, teardown_profiling):
with pytest.raises(ValueError):
setup_profiler(make_options(mode))
@pytest.mark.parametrize(
"mode",
[
pytest.param("thread"),
pytest.param("sleep"),
pytest.param("gevent", marks=requires_gevent),
],
)
@pytest.mark.parametrize(
"make_options",
[
pytest.param(experimental_options, id="experiment"),
pytest.param(non_experimental_options, id="non experimental"),
],
)
def test_profiler_valid_mode(mode, make_options, teardown_profiling):
# should not raise any exceptions
setup_profiler(make_options(mode))
@pytest.mark.parametrize(
"make_options",
[
pytest.param(experimental_options, id="experiment"),
pytest.param(non_experimental_options, id="non experimental"),
],
)
def test_profiler_setup_twice(make_options, teardown_profiling):
# setting up the first time should return True to indicate success
assert setup_profiler(make_options())
# setting up the second time should return False to indicate no-op
assert not setup_profiler(make_options())
@pytest.mark.parametrize(
"mode",
[
pytest.param("thread"),
pytest.param("gevent", marks=requires_gevent),
],
)
@pytest.mark.parametrize(
("profiles_sample_rate", "profile_count"),
[
pytest.param(1.00, 1, id="profiler sampled at 1.00"),
pytest.param(0.75, 1, id="profiler sampled at 0.75"),
pytest.param(0.25, 0, id="profiler sampled at 0.25"),
pytest.param(0.00, 0, id="profiler sampled at 0.00"),
pytest.param(None, 0, id="profiler not enabled"),
],
)
@pytest.mark.parametrize(
"make_options",
[
pytest.param(experimental_options, id="experiment"),
pytest.param(non_experimental_options, id="non experimental"),
],
)
@mock.patch("sentry_sdk.profiler.transaction_profiler.PROFILE_MINIMUM_SAMPLES", 0)
def test_profiles_sample_rate(
sentry_init,
capture_envelopes,
capture_record_lost_event_calls,
teardown_profiling,
profiles_sample_rate,
profile_count,
make_options,
mode,
):
options = make_options(mode=mode, sample_rate=profiles_sample_rate)
sentry_init(
traces_sample_rate=1.0,
profiler_mode=options.get("profiler_mode"),
profiles_sample_rate=options.get("profiles_sample_rate"),
_experiments=options.get("_experiments", {}),
)
envelopes = capture_envelopes()
record_lost_event_calls = capture_record_lost_event_calls()
with mock.patch(
"sentry_sdk.profiler.transaction_profiler.random.random", return_value=0.5
):
with start_transaction(name="profiling"):
pass
items = defaultdict(list)
for envelope in envelopes:
for item in envelope.items:
items[item.type].append(item)
assert len(items["transaction"]) == 1
assert len(items["profile"]) == profile_count
if profiles_sample_rate is None or profiles_sample_rate == 0:
assert record_lost_event_calls == []
elif profile_count:
assert record_lost_event_calls == []
else:
assert record_lost_event_calls == [("sample_rate", "profile", None, 1)]
@pytest.mark.parametrize(
"mode",
[
pytest.param("thread"),
pytest.param("gevent", marks=requires_gevent),
],
)
@pytest.mark.parametrize(
("profiles_sampler", "profile_count"),
[
pytest.param(lambda _: 1.00, 1, id="profiler sampled at 1.00"),
pytest.param(lambda _: 0.75, 1, id="profiler sampled at 0.75"),
pytest.param(lambda _: 0.25, 0, id="profiler sampled at 0.25"),
pytest.param(lambda _: 0.00, 0, id="profiler sampled at 0.00"),
pytest.param(lambda _: None, 0, id="profiler not enabled"),
pytest.param(
lambda ctx: 1 if ctx["transaction_context"]["name"] == "profiling" else 0,
1,
id="profiler sampled for transaction name",
),
pytest.param(
lambda ctx: 0 if ctx["transaction_context"]["name"] == "profiling" else 1,
0,
id="profiler not sampled for transaction name",
),
pytest.param(
lambda _: "1", 0, id="profiler not sampled because string sample rate"
),
pytest.param(lambda _: True, 1, id="profiler sampled at True"),
pytest.param(lambda _: False, 0, id="profiler sampled at False"),
],
)
@mock.patch("sentry_sdk.profiler.transaction_profiler.PROFILE_MINIMUM_SAMPLES", 0)
def test_profiles_sampler(
sentry_init,
capture_envelopes,
capture_record_lost_event_calls,
teardown_profiling,
profiles_sampler,
profile_count,
mode,
):
sentry_init(
traces_sample_rate=1.0,
profiles_sampler=profiles_sampler,
)
envelopes = capture_envelopes()
record_lost_event_calls = capture_record_lost_event_calls()
with mock.patch(
"sentry_sdk.profiler.transaction_profiler.random.random", return_value=0.5
):
with start_transaction(name="profiling"):
pass
items = defaultdict(list)
for envelope in envelopes:
for item in envelope.items:
items[item.type].append(item)
assert len(items["transaction"]) == 1
assert len(items["profile"]) == profile_count
if profile_count:
assert record_lost_event_calls == []
else:
assert record_lost_event_calls == [("sample_rate", "profile", None, 1)]
def test_minimum_unique_samples_required(
sentry_init,
capture_envelopes,
capture_record_lost_event_calls,
teardown_profiling,
):
sentry_init(
traces_sample_rate=1.0,
_experiments={"profiles_sample_rate": 1.0},
)
envelopes = capture_envelopes()
record_lost_event_calls = capture_record_lost_event_calls()
with start_transaction(name="profiling"):
pass
items = defaultdict(list)
for envelope in envelopes:
for item in envelope.items:
items[item.type].append(item)
assert len(items["transaction"]) == 1
# because we dont leave any time for the profiler to
# take any samples, it should be not be sent
assert len(items["profile"]) == 0
assert record_lost_event_calls == [("insufficient_data", "profile", None, 1)]
@pytest.mark.forked
def test_profile_captured(
sentry_init,
capture_envelopes,
teardown_profiling,
):
sentry_init(
traces_sample_rate=1.0,
_experiments={"profiles_sample_rate": 1.0},
)
envelopes = capture_envelopes()
with start_transaction(name="profiling"):
time.sleep(0.05)
items = defaultdict(list)
for envelope in envelopes:
for item in envelope.items:
items[item.type].append(item)
assert len(items["transaction"]) == 1
assert len(items["profile"]) == 1
def get_frame(depth=1):
"""
This function is not exactly true to its name. Depending on
how it is called, the true depth of the stack can be deeper
than the argument implies.
"""
if depth <= 0:
raise ValueError("only positive integers allowed")
if depth > 1:
return get_frame(depth=depth - 1)
return inspect.currentframe()
class GetFrameBase:
def inherited_instance_method(self):
return inspect.currentframe()
def inherited_instance_method_wrapped(self):
def wrapped():
return inspect.currentframe()
return wrapped
@classmethod
def inherited_class_method(cls):
return inspect.currentframe()
@classmethod
def inherited_class_method_wrapped(cls):
def wrapped():
return inspect.currentframe()
return wrapped
@staticmethod
def inherited_static_method():
return inspect.currentframe()
class GetFrame(GetFrameBase):
def instance_method(self):
return inspect.currentframe()
def instance_method_wrapped(self):
def wrapped():
return inspect.currentframe()
return wrapped
@classmethod
def class_method(cls):
return inspect.currentframe()
@classmethod
def class_method_wrapped(cls):
def wrapped():
return inspect.currentframe()
return wrapped
@staticmethod
def static_method():
return inspect.currentframe()
@pytest.mark.parametrize(
("frame", "frame_name"),
[
pytest.param(
get_frame(),
"get_frame",
id="function",
),
pytest.param(
(lambda: inspect.currentframe())(),
"<lambda>",
id="lambda",
),
pytest.param(
GetFrame().instance_method(),
"GetFrame.instance_method",
id="instance_method",
),
pytest.param(
GetFrame().instance_method_wrapped()(),
(
"wrapped"
if sys.version_info < (3, 11)
else "GetFrame.instance_method_wrapped.<locals>.wrapped"
),
id="instance_method_wrapped",
),
pytest.param(
GetFrame().class_method(),
"GetFrame.class_method",
id="class_method",
),
pytest.param(
GetFrame().class_method_wrapped()(),
(
"wrapped"
if sys.version_info < (3, 11)
else "GetFrame.class_method_wrapped.<locals>.wrapped"
),
id="class_method_wrapped",
),
pytest.param(
GetFrame().static_method(),
"static_method" if sys.version_info < (3, 11) else "GetFrame.static_method",
id="static_method",
),
pytest.param(
GetFrame().inherited_instance_method(),
"GetFrameBase.inherited_instance_method",
id="inherited_instance_method",
),
pytest.param(
GetFrame().inherited_instance_method_wrapped()(),
(
"wrapped"
if sys.version_info < (3, 11)
else "GetFrameBase.inherited_instance_method_wrapped.<locals>.wrapped"
),
id="instance_method_wrapped",
),
pytest.param(
GetFrame().inherited_class_method(),
"GetFrameBase.inherited_class_method",
id="inherited_class_method",
),
pytest.param(
GetFrame().inherited_class_method_wrapped()(),
(
"wrapped"
if sys.version_info < (3, 11)
else "GetFrameBase.inherited_class_method_wrapped.<locals>.wrapped"
),
id="inherited_class_method_wrapped",
),
pytest.param(
GetFrame().inherited_static_method(),
(
"inherited_static_method"
if sys.version_info < (3, 11)
else "GetFrameBase.inherited_static_method"
),
id="inherited_static_method",
),
],
)
def test_get_frame_name(frame, frame_name):
assert get_frame_name(frame) == frame_name
@pytest.mark.parametrize(
("get_frame", "function"),
[
pytest.param(lambda: get_frame(depth=1), "get_frame", id="simple"),
],
)
def test_extract_frame(get_frame, function):
cwd = os.getcwd()
frame = get_frame()
extracted_frame = extract_frame(frame_id(frame), frame, cwd)
# the abs_path should be equal toe the normalized path of the co_filename
assert extracted_frame["abs_path"] == os.path.normpath(frame.f_code.co_filename)
# the module should be pull from this test module
assert extracted_frame["module"] == __name__
# the filename should be the file starting after the cwd
assert extracted_frame["filename"] == __file__[len(cwd) + 1 :]
assert extracted_frame["function"] == function
# the lineno will shift over time as this file is modified so just check
# that it is an int
assert isinstance(extracted_frame["lineno"], int)
@pytest.mark.parametrize(
("depth", "max_stack_depth", "actual_depth"),
[
pytest.param(1, 128, 1, id="less than"),
pytest.param(256, 128, 128, id="greater than"),
pytest.param(128, 128, 128, id="equals"),
],
)
def test_extract_stack_with_max_depth(depth, max_stack_depth, actual_depth):
# introduce a lambda that we'll be looking for in the stack
frame = (lambda: get_frame(depth=depth))()
# plus 1 because we introduced a lambda intentionally that we'll
# look for in the final stack to make sure its in the right position
base_stack_depth = len(inspect.stack()) + 1
# increase the max_depth by the `base_stack_depth` to account
# for the extra frames pytest will add
_, frame_ids, frames = extract_stack(
frame,
LRUCache(max_size=1),
max_stack_depth=max_stack_depth + base_stack_depth,
cwd=os.getcwd(),
)
assert len(frame_ids) == base_stack_depth + actual_depth
assert len(frames) == base_stack_depth + actual_depth
for i in range(actual_depth):
assert frames[i]["function"] == "get_frame", i
# index 0 contains the inner most frame on the stack, so the lamdba
# should be at index `actual_depth`
if sys.version_info >= (3, 11):
assert (
frames[actual_depth]["function"]
== "test_extract_stack_with_max_depth.<locals>.<lambda>"
), actual_depth
else:
assert frames[actual_depth]["function"] == "<lambda>", actual_depth
@pytest.mark.parametrize(
("frame", "depth"),
[(get_frame(depth=1), len(inspect.stack()))],
)
def test_extract_stack_with_cache(frame, depth):
# make sure cache has enough room or this test will fail
cache = LRUCache(max_size=depth)
cwd = os.getcwd()
_, _, frames1 = extract_stack(frame, cache, cwd=cwd)
_, _, frames2 = extract_stack(frame, cache, cwd=cwd)
assert len(frames1) > 0
assert len(frames2) > 0
assert len(frames1) == len(frames2)
for i, (frame1, frame2) in enumerate(zip(frames1, frames2)):
# DO NOT use `==` for the assertion here since we are
# testing for identity, and using `==` would test for
# equality which would always pass since we're extract
# the same stack.
assert frame1 is frame2, i
def get_scheduler_threads(scheduler):
return [thread for thread in threading.enumerate() if thread.name == scheduler.name]
@pytest.mark.parametrize(
("scheduler_class",),
[
pytest.param(ThreadScheduler, id="thread scheduler"),
pytest.param(
GeventScheduler,
marks=[
requires_gevent,
pytest.mark.skip(
reason="cannot find this thread via threading.enumerate()"
),
],
id="gevent scheduler",
),
],
)
def test_thread_scheduler_single_background_thread(scheduler_class):
scheduler = scheduler_class(frequency=1000)
# not yet setup, no scheduler threads yet
assert len(get_scheduler_threads(scheduler)) == 0
scheduler.setup()
# setup but no profiles started so still no threads
assert len(get_scheduler_threads(scheduler)) == 0
scheduler.ensure_running()
# the scheduler will start always 1 thread
assert len(get_scheduler_threads(scheduler)) == 1
scheduler.ensure_running()
# the scheduler still only has 1 thread
assert len(get_scheduler_threads(scheduler)) == 1
scheduler.teardown()
# once finished, the thread should stop
assert len(get_scheduler_threads(scheduler)) == 0
@pytest.mark.parametrize(
("scheduler_class",),
[
pytest.param(ThreadScheduler, id="thread scheduler"),
pytest.param(
GeventScheduler,
marks=[
requires_gevent,
pytest.mark.skip(
reason="cannot find this thread via threading.enumerate()"
),
],
id="gevent scheduler",
),
],
)
def test_thread_scheduler_no_thread_on_shutdown(scheduler_class):
scheduler = scheduler_class(frequency=1000)
# not yet setup, no scheduler threads yet
assert len(get_scheduler_threads(scheduler)) == 0
scheduler.setup()
# setup but no profiles started so still no threads
assert len(get_scheduler_threads(scheduler)) == 0
# mock RuntimeError as if the 3.12 intepreter was shutting down
with mock.patch(
"threading.Thread.start",
side_effect=RuntimeError("can't create new thread at interpreter shutdown"),
):
scheduler.ensure_running()
assert scheduler.running is False
# still no thread
assert len(get_scheduler_threads(scheduler)) == 0
scheduler.teardown()
assert len(get_scheduler_threads(scheduler)) == 0
@pytest.mark.parametrize(
("scheduler_class",),
[
pytest.param(ThreadScheduler, id="thread scheduler"),
pytest.param(GeventScheduler, marks=requires_gevent, id="gevent scheduler"),
],
)
@mock.patch("sentry_sdk.profiler.transaction_profiler.MAX_PROFILE_DURATION_NS", 1)
def test_max_profile_duration_reached(scheduler_class):
sample = [
(
"1",
extract_stack(
get_frame(),
LRUCache(max_size=1),
cwd=os.getcwd(),
),
),
]
with scheduler_class(frequency=1000) as scheduler:
with Profile(True, 0, scheduler=scheduler) as profile:
# profile just started, it's active
assert profile.active
# write a sample at the start time, so still active
profile.write(profile.start_ns + 0, sample)
assert profile.active
# write a sample at max time, so still active
profile.write(profile.start_ns + 1, sample)
assert profile.active
# write a sample PAST the max time, so now inactive
profile.write(profile.start_ns + 2, sample)
assert not profile.active
class NoopScheduler(Scheduler):
def setup(self):
# type: () -> None
pass
def teardown(self):
# type: () -> None
pass
def ensure_running(self):
# type: () -> None
pass
current_thread = threading.current_thread()
thread_metadata = {
str(current_thread.ident): {
"name": str(current_thread.name),
},
}
sample_stacks = [
extract_stack(
get_frame(),
LRUCache(max_size=1),
max_stack_depth=1,
cwd=os.getcwd(),
),
extract_stack(
get_frame(),
LRUCache(max_size=1),
max_stack_depth=2,
cwd=os.getcwd(),
),
]
@pytest.mark.parametrize(
("samples", "expected"),
[
pytest.param(
[],
{
"frames": [],
"samples": [],
"stacks": [],
"thread_metadata": thread_metadata,
},
id="empty",
),
pytest.param(
[(6, [("1", sample_stacks[0])])],
{
"frames": [],
"samples": [],
"stacks": [],
"thread_metadata": thread_metadata,
},
id="single sample out of range",
),
pytest.param(
[(0, [("1", sample_stacks[0])])],
{
"frames": [sample_stacks[0][2][0]],
"samples": [
{
"elapsed_since_start_ns": "0",
"thread_id": "1",
"stack_id": 0,
},
],
"stacks": [[0]],
"thread_metadata": thread_metadata,
},
id="single sample in range",
),
pytest.param(
[
(0, [("1", sample_stacks[0])]),
(1, [("1", sample_stacks[0])]),
],
{
"frames": [sample_stacks[0][2][0]],
"samples": [
{
"elapsed_since_start_ns": "0",
"thread_id": "1",
"stack_id": 0,
},
{
"elapsed_since_start_ns": "1",
"thread_id": "1",
"stack_id": 0,
},
],
"stacks": [[0]],
"thread_metadata": thread_metadata,
},
id="two identical stacks",
),
pytest.param(
[
(0, [("1", sample_stacks[0])]),
(1, [("1", sample_stacks[1])]),
],
{
"frames": [
sample_stacks[0][2][0],
sample_stacks[1][2][0],
],
"samples": [
{
"elapsed_since_start_ns": "0",
"thread_id": "1",
"stack_id": 0,
},
{
"elapsed_since_start_ns": "1",
"thread_id": "1",
"stack_id": 1,
},
],
"stacks": [[0], [1, 0]],
"thread_metadata": thread_metadata,
},
id="two different stacks",
),
],
)
@mock.patch("sentry_sdk.profiler.transaction_profiler.MAX_PROFILE_DURATION_NS", 5)
def test_profile_processing(
DictionaryContaining, # noqa: N803
samples,
expected,
):
with NoopScheduler(frequency=1000) as scheduler:
with Profile(True, 0, scheduler=scheduler) as profile:
for ts, sample in samples:
# force the sample to be written at a time relative to the
# start of the profile
now = profile.start_ns + ts
profile.write(now, sample)
processed = profile.process()
assert processed["thread_metadata"] == DictionaryContaining(
expected["thread_metadata"]
)
assert processed["frames"] == expected["frames"]
assert processed["stacks"] == expected["stacks"]
assert processed["samples"] == expected["samples"]
def test_hub_backwards_compatibility(suppress_deprecation_warnings):
hub = sentry_sdk.Hub()
with pytest.warns(DeprecationWarning):
profile = Profile(True, 0, hub=hub)
with pytest.warns(DeprecationWarning):
assert profile.hub is hub
new_hub = sentry_sdk.Hub()
with pytest.warns(DeprecationWarning):
profile.hub = new_hub
with pytest.warns(DeprecationWarning):
assert profile.hub is new_hub
def test_no_warning_without_hub():
with warnings.catch_warnings():
warnings.simplefilter("error")
Profile(True, 0)
|