fix: stop `import ddtrace` from installing import hooks and OTel listeners #22201
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #22201"
general
weight: 0.35
gnufede
Description
Goal:
import ddtraceshould not change how the rest of the program runs. Setup that has process-wide effects should only happen when the user asks for it, by runningddtrace-runorimport ddtrace.auto.This PR removes two such side effects of
import ddtrace.Why this is needed
ddtraceis being split into multiple packages, so import-time, process-wide side effects become a cross-package problem:ddtrace-nativeloads_threadsas_ddtrace_native._threads, #22137). An import hook installed by a plainimport ddtraceleaks into every process that touches any of those packages, and its only real consumer, module cloning, is addtrace-runfeature anyway.ddtrace/__init__.pymust stay a thin facade: products are discovered from package metadata and started byddtrace-run/ddtrace.auto, never by an import. Import-time setup would be inherited by every split package whether it wants it or not.otel-thread-contextproduct pulls the tracer viacore.root.get_item("tracer")instead of a static import, so no new import cycles or layering violations are introduced — a hard requirement for extraction.1. Importing ddtrace no longer installs an import hook
ModuleWatchdogis an import hook: it sits insys.meta_pathand intercepts every import the program makes from then on. Onlyddtrace-runactually needs it, but three places installed it on import, and a plainimport ddtraceloads all of them:| Where | What it did at import time | Now |
|---|---|---|
|
ddtrace/internal/threads.py| Hook to follow the app's copy ofthreading| Registered only if the watchdog is already installed.ddtrace-runregisters it when it sets up module cloning, which is the only case where the app gets its own copy ofthreading. ||
ddtrace/vendor/__init__.py| Hook to swap the logger of the vendored dogstatsd | The logger is set directly inddtrace/vendor/dogstatsd/__init__.py, when that module is first imported. ||
ddtrace/__init__.py(with_DD_GLOBAL_TRACER_INIT=false) | Hook onddtrace.traceto set up the OpenTelemetry thread context later | Removed. See point 2. |2. OpenTelemetry thread context is set up by a product, not by the import
On Linux, ddtrace publishes the active trace and span IDs in an OpenTelemetry thread context record, which external tools such as the OpenTelemetry eBPF Profiler can read. The listeners that keep that record up to date were registered as a side effect of
import ddtrace.They are now registered by a new
otel-thread-contextproduct, inddtrace/internal/opentelemetry/thread_context_product.py. Products are started byddtrace-runandddtrace.auto, never by a plain import.core.root.get_item("tracer"), so the OpenTelemetry code doesn't import the tracing code. Import-analysis results don't change: still no cycles, and no new layering violations.ddtrace.internal.uwsgi.check_uwsgi). Registering the listeners now dispatches apython.context.switch.listeners_changedcore event; the asyncio, anyio and trio integrations subscribe to it and retry the install or patch they skipped, gated on the integration having been asked to patch in the first place. On Python 3.14+ the native context watcher covers the switches, so the retry stays a no-op there.stop()removes the listeners. At process exit they are kept, so spans that finish during shutdown still clear their record.Customer impact
ddtrace-runorimport ddtrace.auto: nothing changes.import ddtrace:- ddtrace no longer installs
ModuleWatchdog, so their imports are no longer intercepted. (Release note in thefixessection.)- On Linux, they no longer publish OpenTelemetry thread context records. To keep them, switch to
ddtrace-runorimport ddtrace.auto. (Release note in theupgradesection; theDD_TRACE_OTEL_CTX_ENABLEDdocs are updated too.)Testing
New tests:
--import=ddtrace.auto), each worker runs two interleaved traced asyncio tasks and asserts the OpenTelemetry thread context holds the resuming task's span, not the other task's (tests/tracer/test_uwsgi_preload_otel_context.py; verified to fail without the event dispatch). Added to thetracer-uwsgisuite.tests/tracer/test_otel_thread_context.pycovering the ≤3.13 install and the 3.14+ native-watcher no-op.import ddtracedoesn't installModuleWatchdog, with the default setting and with_DD_GLOBAL_TRACER_INIT=false, including after an explicitimport ddtrace.trace.ddtrace-run,ddtrace.internal.threadsstill follows the app's copy ofthreading.- A plain
import ddtracepublishes nothing.-
ddtrace-runpublishes the active span and clears the record when the span ends, including after process-exit product shutdown.-
DD_TRACE_OTEL_CTX_ENABLED=falsedisables the product.- The product lifecycle: no global tracer yet, repeated
start(),stop().-
enabled()across platforms and settings.Updated tests: two tests relied on the old import-time setup (
tests/contrib/fastapi/test_fastapi.py, and the Python 3.14 test intests/opentelemetry/test_context.py). They now use a newotel_thread_contextfixture that starts and stops the product.The IAST Flask entrypoint scenarios (
tests/appsec/integrations/flask_tests/test_iast_flask_entrypoint_iast_patches.py) also relied on the old setup: their watchdog-cleanup helper readModuleWatchdog._instance._pre_exec_module_hooksbefore any IAST override, which crashed when a plain import no longer installs the watchdog. The helper now no-ops when no watchdog is installed (with one installed,register_pre_exec_module_hookcallsinstall()itself, so IAST patching is unaffected).Checked locally in the Linux test container:
ddtrace-runandddtrace.auto: the product is discovered from the package metadata, publishes, and can be disabled.scripts/import-analysiscycles.pyandlayers.py: no cycles, no new layering violations.Risks
import ddtracestop publishing OTel thread context records on Linux. This is intended and covered by the upgrade note. Anyone relying on it with a plain import has to switch toddtrace-runorddtrace.auto.start()before this product starts would still skip its fallback; no product does that today.otel_thread_contextshows up as a new product name in telemetry events, like other internal products already do.import ddtracenow does less work.ddtrace-runloads one more small product module. Measured withscripts/run-benchmarks --scenario startupagainst the merge base (60 samples per config per side): no config regresses; plainimport ddtrace-3.3%,import_ddtrace_deferred_tracer-4.1%,ddtrace_run-6.3%,import_ddtrace_auto-7.3%,ddtrace_run_send_spanunchanged (not significant). The uninstrumentedbaselineconfig also drifted -7.3%, so single-digit deltas are partly run noise; the direction is uniformly non-regressing. The CI benchmark jobs remain the authoritative measurement.Additional Notes
mypy.ininow setsplatform = linux, so local type checks evaluatesys.platformas Linux. This matches what the mypy CI job (Linux) already checks and was needed because this PR's tests import the Linux-only native OTel thread context API under a platform guard, which no formulation type-checks on another host. Note for contributors on other hosts: darwin/win32-gated branches are no longer type-checked locally.import ddtracestill installs wrapt'sImportHookFinder, through the_when_importedsubscriber registration inddtrace/__init__.py. Removing it raises the same question of what plain-import users should keep, so it's left for a follow-up.ddtrace/_otel.pyand then remove it. Please squash-merge.