|
| 1 | +import contextvars |
| 2 | +import sys |
| 3 | +import threading |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from ddtrace.internal import core |
| 8 | + |
| 9 | + |
| 10 | +pytestmark = pytest.mark.skipif( |
| 11 | + sys.implementation.name != "cpython" or sys.version_info < (3, 14), |
| 12 | + reason="requires the CPython 3.14 context watcher", |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +@pytest.fixture(autouse=True) |
| 17 | +def _register_context_watcher(): |
| 18 | + from ddtrace.internal.native._native import is_context_watcher_registered |
| 19 | + from ddtrace.internal.native._native import register_context_watcher |
| 20 | + |
| 21 | + assert register_context_watcher() |
| 22 | + assert is_context_watcher_registered() |
| 23 | + |
| 24 | + |
| 25 | +def test_context_watcher_dispatches_events_and_releases_listener_snapshot(): |
| 26 | + value = contextvars.ContextVar("value", default="outer") |
| 27 | + inner_context = contextvars.copy_context() |
| 28 | + inner_context.run(value.set, "inner") |
| 29 | + observed = [] |
| 30 | + test_thread_id = threading.get_ident() |
| 31 | + |
| 32 | + def record_context_switch(): |
| 33 | + if threading.get_ident() == test_thread_id: |
| 34 | + observed.append(value.get()) |
| 35 | + |
| 36 | + core.on("python.context.switch", record_context_switch) |
| 37 | + try: |
| 38 | + reference_count = sys.getrefcount(record_context_switch) |
| 39 | + inner_context.run(lambda: None) |
| 40 | + assert sys.getrefcount(record_context_switch) == reference_count |
| 41 | + finally: |
| 42 | + core.reset_listeners("python.context.switch", record_context_switch) |
| 43 | + |
| 44 | + assert observed == ["inner", "outer"] |
| 45 | + |
| 46 | + |
| 47 | +def test_context_watcher_preserves_pending_exception_over_listener_failure(): |
| 48 | + inner_context = contextvars.copy_context() |
| 49 | + observed = [] |
| 50 | + unraisable = [] |
| 51 | + test_thread_id = threading.get_ident() |
| 52 | + |
| 53 | + class ExpectedError(Exception): |
| 54 | + pass |
| 55 | + |
| 56 | + class ListenerError(BaseException): |
| 57 | + pass |
| 58 | + |
| 59 | + def record_context_switch(): |
| 60 | + if threading.get_ident() != test_thread_id: |
| 61 | + return |
| 62 | + observed.append(contextvars.copy_context()) |
| 63 | + if len(observed) == 2: |
| 64 | + raise ListenerError |
| 65 | + |
| 66 | + def raise_expected_error(): |
| 67 | + raise ExpectedError |
| 68 | + |
| 69 | + original_unraisablehook = sys.unraisablehook |
| 70 | + sys.unraisablehook = lambda args: unraisable.append(args.exc_value) |
| 71 | + core.on("python.context.switch", record_context_switch) |
| 72 | + try: |
| 73 | + with pytest.raises(ExpectedError): |
| 74 | + inner_context.run(raise_expected_error) |
| 75 | + finally: |
| 76 | + core.reset_listeners("python.context.switch", record_context_switch) |
| 77 | + sys.unraisablehook = original_unraisablehook |
| 78 | + |
| 79 | + assert len(observed) == 2 |
| 80 | + assert len(unraisable) == 1 |
| 81 | + assert isinstance(unraisable[0], ListenerError) |
| 82 | + |
| 83 | + |
| 84 | +@pytest.mark.subprocess(env={"_DD_GLOBAL_TRACER_INIT": "false"}) |
| 85 | +def test_context_watcher_slot_exhaustion_disables_watcher(): |
| 86 | + """Registration failure is non-fatal and remains cached after watcher slots are freed.""" |
| 87 | + import ctypes |
| 88 | + import sys |
| 89 | + |
| 90 | + assert "ddtrace.internal.native._native" not in sys.modules |
| 91 | + |
| 92 | + callback_type = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_uint, ctypes.py_object) |
| 93 | + callback = callback_type(lambda event, obj: 0) |
| 94 | + add_watcher = ctypes.pythonapi.PyContext_AddWatcher |
| 95 | + add_watcher.argtypes = [callback_type] |
| 96 | + add_watcher.restype = ctypes.c_int |
| 97 | + clear_watcher = ctypes.pythonapi.PyContext_ClearWatcher |
| 98 | + clear_watcher.argtypes = [ctypes.c_int] |
| 99 | + clear_watcher.restype = ctypes.c_int |
| 100 | + |
| 101 | + watcher_ids = [] |
| 102 | + for _ in range(64): |
| 103 | + try: |
| 104 | + watcher_ids.append(add_watcher(callback)) |
| 105 | + except RuntimeError: |
| 106 | + break |
| 107 | + else: |
| 108 | + raise AssertionError("context watcher slots were not exhausted") |
| 109 | + |
| 110 | + try: |
| 111 | + from ddtrace.internal.native._native import is_context_watcher_registered |
| 112 | + from ddtrace.internal.native._native import register_context_watcher |
| 113 | + |
| 114 | + assert register_context_watcher() is False |
| 115 | + assert is_context_watcher_registered() is False |
| 116 | + finally: |
| 117 | + for watcher_id in watcher_ids: |
| 118 | + assert clear_watcher(watcher_id) == 0 |
| 119 | + |
| 120 | + assert register_context_watcher() is False |
| 121 | + assert is_context_watcher_registered() is False |
| 122 | + |
| 123 | + |
| 124 | +@pytest.mark.subprocess(env={"_DD_GLOBAL_TRACER_INIT": "false"}) |
| 125 | +def test_context_watcher_registration_is_idempotent(): |
| 126 | + """Repeated registration uses one watcher; tracer startup is disabled so this test owns the first call.""" |
| 127 | + from contextvars import Context |
| 128 | + |
| 129 | + from ddtrace.internal import core |
| 130 | + from ddtrace.internal.native._native import is_context_watcher_registered |
| 131 | + from ddtrace.internal.native._native import register_context_watcher |
| 132 | + |
| 133 | + assert is_context_watcher_registered() is False |
| 134 | + |
| 135 | + for _ in range(16): |
| 136 | + assert register_context_watcher() is True |
| 137 | + |
| 138 | + assert is_context_watcher_registered() is True |
| 139 | + |
| 140 | + observed = [] |
| 141 | + core.on("python.context.switch", lambda: observed.append(None)) |
| 142 | + Context().run(lambda: None) |
| 143 | + assert observed == [None, None] |
0 commit comments