← Back to Pull requests

fix: stop `import ddtrace` from installing import hooks and OTel listeners #22201

Closed
unknown closed this pull request without merging on Dec 01, 2026 18:35 UTC
View on GitHub
unknown unknown commented on Nov 30, 2026 17:05 UTC
Author

Description

Goal: import ddtrace should 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 running ddtrace-run or import ddtrace.auto.

This PR removes two such side effects of import ddtrace.

Why this is needed

ddtrace is being split into multiple packages, so import-time, process-wide side effects become a cross-package problem:

  • Split packages load ddtrace internals under different module names (e.g. ddtrace-native loads _threads as _ddtrace_native._threads, #22137). An import hook installed by a plain import ddtrace leaks into every process that touches any of those packages, and its only real consumer, module cloning, is a ddtrace-run feature anyway.

  • ddtrace/__init__.py must stay a thin facade: products are discovered from package metadata and started by ddtrace-run / ddtrace.auto, never by an import. Import-time setup would be inherited by every split package whether it wants it or not.

  • The new otel-thread-context product pulls the tracer via core.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

    ModuleWatchdog is an import hook: it sits in sys.meta_path and intercepts every import the program makes from then on. Only ddtrace-run actually needs it, but three places installed it on import, and a plain import ddtrace loads all of them:

    | Where | What it did at import time | Now |
    |---|---|---|
    | ddtrace/internal/threads.py | Hook to follow the app's copy of threading | Registered only if the watchdog is already installed. ddtrace-run registers it when it sets up module cloning, which is the only case where the app gets its own copy of threading. |
    | ddtrace/vendor/__init__.py | Hook to swap the logger of the vendored dogstatsd | The logger is set directly in ddtrace/vendor/dogstatsd/__init__.py, when that module is first imported. |
    | ddtrace/__init__.py (with _DD_GLOBAL_TRACER_INIT=false) | Hook on ddtrace.trace to 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-context product, in ddtrace/internal/opentelemetry/thread_context_product.py. Products are started by ddtrace-run and ddtrace.auto, never by a plain import.

  • The product gets the tracer from 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.

  • It starts before integrations are patched. This matters because asyncio, anyio and trio decide when they are patched whether they need a fallback to report context switches, and they only install it if a listener already exists.

  • One case breaks that ordering: non-lazy uWSGI runs integration patching in the master while product startup is deferred to the workers (ddtrace.internal.uwsgi.check_uwsgi). Registering the listeners now dispatches a python.context.switch.listeners_changed core 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.
  • [!IMPORTANT]

    This reverses a choice made in #21277, which kept this setup in ddtrace/__init__.py so that apps using a plain import ddtrace would also publish thread context records. Keeping it there contradicts the goal above, so this PR picks the goal. The cost is described under "Customer impact".

    Customer impact

  • Apps that run with ddtrace-run or import ddtrace.auto: nothing changes.

  • Apps that only import ddtrace:

  • - ddtrace no longer installs ModuleWatchdog, so their imports are no longer intercepted. (Release note in the fixes section.)
    - On Linux, they no longer publish OpenTelemetry thread context records. To keep them, switch to ddtrace-run or import ddtrace.auto. (Release note in the upgrade section; the DD_TRACE_OTEL_CTX_ENABLED docs are updated too.)

    Testing

    New tests:

  • Under real non-lazy uWSGI (master, no fork hooks, --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 the tracer-uwsgi suite.

  • Listener registration after patching installs the skipped fallbacks: per-integration retry tests (asyncio, anyio, trio), a deliberate-unpatch test proving the retry does not re-patch, and a product-level subprocess test in tests/tracer/test_otel_thread_context.py covering the ≤3.13 install and the 3.14+ native-watcher no-op.

  • import ddtrace doesn't install ModuleWatchdog, with the default setting and with _DD_GLOBAL_TRACER_INIT=false, including after an explicit import ddtrace.trace.

  • Under ddtrace-run, ddtrace.internal.threads still follows the app's copy of threading.

  • The vendored dogstatsd still uses ddtrace's rate-limited logger.

  • OpenTelemetry thread context:

  • - A plain import ddtrace publishes nothing.
    - ddtrace-run publishes the active span and clears the record when the span ends, including after process-exit product shutdown.
    - DD_TRACE_OTEL_CTX_ENABLED=false disables 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 in tests/opentelemetry/test_context.py). They now use a new otel_thread_context fixture 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 read ModuleWatchdog._instance._pre_exec_module_hooks before 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_hook calls install() itself, so IAST patching is unaffected).

    Checked locally in the Linux test container:

  • Suites: internal, asyncio, anyio, trio, fastapi, OpenTelemetry on 3.14, and the crashtracker OpenTelemetry test.

  • Under real ddtrace-run and ddtrace.auto: the product is discovered from the package metadata, publishes, and can be disabled.

  • On Python 3.13, the asyncio context-switch fallback is installed when the setting is on and absent when it's off. This proves the product starts before patching.

  • scripts/import-analysis cycles.py and layers.py: no cycles, no new layering violations.
  • Risks

  • Apps that only import ddtrace stop 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 to ddtrace-run or ddtrace.auto.

  • Start order. All patching happens after the products start, except non-lazy uWSGI, which patches in the master and starts the products in the workers; that case is covered by the listeners-changed retry above and the uWSGI test. A product that patched asyncio, anyio or trio inside its own start() before this product starts would still skip its fallback; no product does that today.

  • Telemetry. The product manager reports every product, so otel_thread_context shows up as a new product name in telemetry events, like other internal products already do.

  • Startup. A plain import ddtrace now does less work. ddtrace-run loads one more small product module. Measured with scripts/run-benchmarks --scenario startup against the merge base (60 samples per config per side): no config regresses; plain import ddtrace -3.3%, import_ddtrace_deferred_tracer -4.1%, ddtrace_run -6.3%, import_ddtrace_auto -7.3%, ddtrace_run_send_span unchanged (not significant). The uninstrumented baseline config 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.ini now sets platform = linux, so local type checks evaluate sys.platform as 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.
  • This PR is stacked on #22181 (test-only).

  • One import hook is still left on the default path: import ddtrace still installs wrapt's ImportHookFinder, through the _when_imported subscriber registration in ddtrace/__init__.py. Removing it raises the same question of what plain-import users should keep, so it's left for a follow-up.

  • The commits add a temporary ddtrace/_otel.py and then remove it. Please squash-merge.
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: gnufede Review duration: 1530m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%