Skip to content

refactor(internal): use a single universal finder for module watchdogs - #19790

Open
P403n1x87 wants to merge 1 commit into
mainfrom
refactor/universal-module-watchdog
Open

refactor(internal): use a single universal finder for module watchdogs#19790
P403n1x87 wants to merge 1 commit into
mainfrom
refactor/universal-module-watchdog

Conversation

@P403n1x87

@P403n1x87 P403n1x87 commented Aug 20, 2026

Copy link
Copy Markdown
Collaborator

Description

BaseModuleWatchdog subclasses (ModuleWatchdog, DebuggerModuleWatchdog, ModuleCodeCollector, SymbolDatabaseUploader, and the errortracking watchdogs) each inserted themselves into sys.meta_path and, on every find_spec/find_module call, scanned the rest of sys.meta_path to find the real underlying finder. With N watchdogs installed simultaneously (realistic in production: debugger + coverage + symbol DB + error tracking can all be enabled on one service), this produced O(N^2) find_spec invocations per import.

A standalone benchmark against the unrefactored code confirmed the call count follows the exact triangular number N(N+1)/2 (e.g. 21 calls for N=6, where 1 would do), and wall-clock import time grew correspondingly (~1.95x baseline at N=6, unbounded as feature count grows). Module imports sit on every process-startup hot path, so this was worth fixing.

This introduces _UniversalModuleWatchdog: the single object ever inserted into sys.meta_path for watchdog purposes, mirroring the existing _UniversalWrappingContext/WrappingContext pattern in ddtrace/internal/wrapping/context.py. Concrete watchdog subclasses keep their own singleton instance and state (still read directly as production API, e.g. ModuleCodeCollector._instance), but register as participants with the one real finder instead of installing their own. The real find_spec/find_module lookup now happens once per import regardless of N; only the O(N) per-participant callback/ transformer registration remains.

Re-running the adapted benchmark against the refactored code confirms find_spec calls are now flat at 1 per import for N in {1..30}, versus the prior triangular growth.

As part of unifying hook resolution through the single participant list, _pre_exec_module_hooks/_import_exception_hooks resolution now uses first-registered-wins (iterating _participants in registration order) instead of the previous most-recently-installed-wins (an accident of meta_path insertion order). after_import/transform callbacks are unaffected: they already fired in registration order.

BaseModuleWatchdog subclasses (ModuleWatchdog, DebuggerModuleWatchdog,
ModuleCodeCollector, SymbolDatabaseUploader, and the errortracking
watchdogs) each inserted themselves into sys.meta_path and, on every
find_spec/find_module call, scanned the rest of sys.meta_path to find
the real underlying finder. With N watchdogs installed simultaneously
(realistic in production: debugger + coverage + symbol DB + error
tracking can all be enabled on one service), this produced O(N^2)
find_spec invocations per import.

A standalone benchmark against the unrefactored code confirmed the
call count follows the exact triangular number N(N+1)/2 (e.g. 21
calls for N=6, where 1 would do), and wall-clock import time grew
correspondingly (~1.95x baseline at N=6, unbounded as feature count
grows). Module imports sit on every process-startup hot path, so this
was worth fixing.

This introduces _UniversalModuleWatchdog: the single object ever
inserted into sys.meta_path for watchdog purposes, mirroring the
existing _UniversalWrappingContext/WrappingContext pattern in
ddtrace/internal/wrapping/context.py. Concrete watchdog subclasses
keep their own singleton instance and state (still read directly as
production API, e.g. ModuleCodeCollector._instance), but register as
participants with the one real finder instead of installing their
own. The real find_spec/find_module lookup now happens once per
import regardless of N; only the O(N) per-participant callback/
transformer registration remains.

Re-running the adapted benchmark against the refactored code confirms
find_spec calls are now flat at 1 per import for N in {1..30}, versus
the prior triangular growth.

As part of unifying hook resolution through the single participant
list, _pre_exec_module_hooks/_import_exception_hooks resolution now
uses first-registered-wins (iterating _participants in registration
order) instead of the previous most-recently-installed-wins (an
accident of meta_path insertion order). after_import/transform
callbacks are unaffected: they already fired in registration order.

Also wraps each after_import callback invocation in try/except so one
misbehaving hook can't prevent the rest from running, folding in a
fix that was previously written but unmerged on
chore/handle-after-import-exceptions.
@P403n1x87
P403n1x87 requested review from a team as code owners August 20, 2026 13:29
@P403n1x87
P403n1x87 requested a review from juanjux August 20, 2026 13:29
@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Circular import analysis

⚠️ Existing circular imports

There are 3 circular imports that already exist on the base branch and have not been changed by this PR.

ddtrace.llmobs -> ddtrace.llmobs._evaluators -> ddtrace.llmobs._evaluators.format -> ddtrace.llmobs._experiment -> ddtrace.llmobs
ddtrace.errortracking._handled_exceptions.bytecode_injector -> ddtrace.errortracking._handled_exceptions.callbacks -> ddtrace.errortracking._handled_exceptions.collector -> ddtrace.errortracking._handled_exceptions.bytecode_reporting -> ddtrace.errortracking._handled_exceptions.bytecode_injector
ddtrace.appsec._asm_request_context -> ddtrace.appsec._iast._iast_request_context_base -> ddtrace.appsec._iast._iast_env -> ddtrace.appsec._iast.reporter -> ddtrace.appsec._exploit_prevention.stack_traces -> ddtrace.appsec._asm_request_context

@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

There are 252 dependency direction violations that already exist on the base branch and have not been changed by this PR.

Show existing violations (showing 5 of 252 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=135)
ddtrace.llmobs._integrations.llama_index -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=133)
ddtrace.internal.opentelemetry.trace -×-> ddtrace.trace  (product:opentelemetry -> product:tracing, score=133)
ddtrace.llmobs._integrations.litellm -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=133)
ddtrace.llmobs._integrations.base -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=133)

To see all violations, download the layers-base.json and layers-pr.json artifacts from this CI job and run:

uv run --script scripts/import-analysis/layers.py compare layers-base.json layers-pr.json

@datadog-datadog-prod-us1-2

datadog-datadog-prod-us1-2 Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Pipelines  Tests

Unblock PR with BitsAI

⚠️ Warnings

🚦 32 Pipeline jobs failed

DataDog/apm-reliability/dd-trace-py | build linux serverless: [amd64, cp315-cp315, v126532274-233089d-musllinux_1_2_x86_64, 1] — 🔧 Needs a code fix, caused by this PR

View in Datadog · View in GitLab

DataDog/apm-reliability/dd-trace-py | build linux serverless: [arm64, cp315-cp315, v113741357-d2b8243-manylinux2014_aarch64, 1] — 🔧 Needs a code fix, caused by this PR

View in Datadog · View in GitLab

DataDog/apm-reliability/dd-trace-py | build linux: [amd64, cp315-cp315, v126532274-233089d-musllinux_1_2_x86_64] — 🔧 Needs a code fix, caused by this PR

View in Datadog · View in GitLab

View all 32 failed jobs.

❄️ 5 New flaky tests detected

test_universal_module_watchdog_first_registered_wins[py3.11] from test_module.py   View in Datadog
assert [] == ['first']
  
  Right contains one more item: 'first'
  
  Full diff:
  + []
  - [
  -     'first',
  - ]
test_universal_module_watchdog_first_registered_wins[py3.12] from test_module.py   View in Datadog
assert [] == ['first']
  
  Right contains one more item: 'first'
  
  Full diff:
  + []
  - [
  -     'first',
  - ]

View in Flaky Test Management

ℹ️ Info

No other issues found (see more)

🧪 All tests passed

Useful? React with 👍 / 👎

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 19ac065 | Docs | View more details | Give us feedback!

@P403n1x87 P403n1x87 added the changelog/no-changelog A changelog entry is not required for this PR. label Aug 20, 2026
@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against main using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

ddtrace/internal/module.py                                              @DataDog/debugger-python @DataDog/apm-core-python
tests/internal/test_module.py                                           @DataDog/debugger-python @DataDog/apm-core-python

@pr-commenter

pr-commenter Bot commented Aug 20, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-08-20 14:00:08

Comparing candidate commit 19ac065 in PR branch refactor/universal-module-watchdog with baseline commit db3cb3e in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 11 performance regressions! Performance is the same for 605 metrics, 11 unstable metrics.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

scenario:httppropagationextract-wsgi_valid_headers_all

  • 🟥 execution_time [+435.772ns; +486.369ns] or [+7.975%; +8.901%]

scenario:httppropagationinject-ids_only

  • 🟥 execution_time [+1.571µs; +1.747µs] or [+8.138%; +9.053%]

scenario:iastaspects-casefold_noaspect

  • 🟥 execution_time [+38.051µs; +47.791µs] or [+15.354%; +19.284%]

scenario:iastaspects-join_aspect

  • 🟥 execution_time [+17.435µs; +24.487µs] or [+8.420%; +11.826%]

scenario:iastaspects-ljust_noaspect

  • 🟥 execution_time [+31.937µs; +36.535µs] or [+10.892%; +12.460%]

scenario:iastaspects-swapcase_noaspect

  • 🟥 execution_time [+17.598µs; +23.819µs] or [+8.582%; +11.615%]

scenario:iastaspectsospath-ospathbasename_aspect

  • 🟥 execution_time [+103.235µs; +114.893µs] or [+24.462%; +27.224%]

scenario:iastaspectssplit-rsplit_aspect

  • 🟥 execution_time [+15.307µs; +20.812µs] or [+10.450%; +14.208%]

scenario:span-start

  • 🟥 execution_time [+1.258ms; +1.422ms] or [+8.427%; +9.524%]

scenario:telemetryaddmetric-1-count-metric-1-times

  • 🟥 execution_time [+531.864ns; +569.755ns] or [+19.658%; +21.058%]

scenario:tracer-small

  • 🟥 execution_time [+28.547µs; +30.643µs] or [+8.556%; +9.184%]

Unstable benchmarks

These benchmarks have a confidence interval too wide to call a change; treat them as noise rather than signal.

scenario:coreapiscenario-context_with_data_listeners

  • unstable execution_time [-722.367ns; +750.807ns] or [-6.568%; +6.827%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-34.815ns; +31.814ns] or [-5.692%; +5.201%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1700.753ns; +1587.825ns] or [-10.012%; +9.348%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1265.949ns; +1218.518ns] or [-9.728%; +9.364%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-346.355ns; +310.107ns] or [-9.402%; +8.418%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-250.305ns; +261.831ns] or [-8.578%; +8.973%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-70.508ns; +75.290ns] or [-6.185%; +6.605%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4080.328ns; +3901.227ns] or [-10.004%; +9.565%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-703.792ns; +825.523ns] or [-8.698%; +10.203%]

scenario:djangosimple-exception-replay-enabled

  • unstable execution_time [-55.625µs; +165.430µs] or [-3.990%; +11.866%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-56.335µs; +65.097µs] or [-8.813%; +10.183%]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

changelog/no-changelog A changelog entry is not required for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant