Skip to content

fix(internal): transform each module imported through a shared loader - #22131

Open
gnufede wants to merge 4 commits into
mainfrom
gnufede/fix-shared-loader-get-code
Open

gnufede wants to merge 4 commits into
mainfrom
gnufede/fix-shared-loader-get-code

Conversation

@gnufede

@gnufede gnufede commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Description

Part of replacing #22018 with smaller PRs on main. Split out at the reviewer's request:
#22018 (comment)

A loader shared by several modules (e.g. a zipimporter) had get_code wrapped once, capturing the first module and its transformers. The guard against re-wrapping then kept later imports bound to them, so transforms received the wrong module. exec_module now re-wraps the original get_code on every call, so the wrapper is bound to the module being executed, and wrappers still do not stack on importlib.reload().

Release note: yes. ModuleWatchdog backs every import hook, and zip applications or bundled deployments can hit this, so it is a customer-visible fix(internal).

Also freezes ddtrace/internal/module.py in frozen-paths.txt (it moves to ddtrace-internal). It is frozen here, not in the utils prep PR, so that PR does not depend on this one. The hash equals the one frozen in #22018.

Testing

New tests/internal/test_module_shared_loader.py; ran tests/internal (3.12, internal suite): 3357 passed. Commit hooks passed.

CODEOWNERS pulled in: @DataDog/debugger-python, @DataDog/apm-core-python (module.py, tests/internal), @DataDog/apm-python (releasenotes), @DataDog/apm-core-python (frozen-paths.txt).

Risks

Low: only the get_code wrapping in _ImportHookChainedLoader.exec_module.

🤖 Generated with Claude Code

gnufede and others added 3 commits November 26, 2026 16:43
A loader shared by several modules (e.g. a zipimporter) had get_code
wrapped once, capturing the first module and its transformers; the guard
against re-wrapping then kept later imports bound to them, so transforms
received the wrong module. Re-wrap the original get_code on every
exec_module so the wrapper is bound to the module being executed, which
still prevents wrappers from stacking on reloads.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Modules imported through a loader shared by several modules (for example a
zipimporter) could be transformed with the wrong module, which users of
zip applications or bundled deployments can hit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
module.py moves to ddtrace-internal in the package split. Freezing it
once the shared loader fix landed keeps the ported copy from drifting.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@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
frozen-paths.txt                                                        @DataDog/apm-core-python
releasenotes/notes/fix-shared-loader-module-transform-7c1d3e9a5b2f4d60.yaml  @DataDog/apm-python
tests/internal/test_module_shared_loader.py                             @DataDog/apm-core-python

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

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

Show existing violations (showing 5 of 22 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=103)
ddtrace.llmobs._integrations.bedrock_agents -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.llmobs._integrations.base -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.internal.span_bus -×-> ddtrace._trace.span  (internal-core -> product:tracing, score=35)
ddtrace.llmobs._llmobs -×-> ddtrace._trace.span  (product:llmobs -> product:tracing, score=33)

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

@pr-commenter

pr-commenter Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-26 17:40:24

Comparing candidate commit 3745405 in PR branch gnufede/fix-shared-loader-get-code with baseline commit 257b955 in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 604 metrics, 10 unstable metrics, 1 flaky benchmarks without significant changes.

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 ----------------------------------'

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 [-769.247ns; +707.912ns] or [-7.178%; +6.606%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-41.932ns; +37.241ns] or [-6.554%; +5.820%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1922.360ns; +1912.607ns] or [-9.628%; +9.579%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1924.983ns; +1767.204ns] or [-9.963%; +9.146%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-384.757ns; +374.671ns] or [-9.056%; +8.819%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-231.398ns; +225.032ns] or [-8.696%; +8.457%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-98.294ns; +80.601ns] or [-7.258%; +5.951%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-5216.356ns; +4118.445ns] or [-10.643%; +8.403%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-917.901ns; +984.535ns] or [-8.946%; +9.596%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-57.340µs; +54.711µs] or [-9.774%; +9.326%]

Known flaky benchmarks

These benchmarks are marked as flaky and will not trigger a failure. Modify FLAKY_BENCHMARKS_REGEX to control which benchmarks are marked as flaky.

Known flaky benchmarks without significant changes:

  • scenario:packagespackageforrootmodulemapping-cache_off

@gnufede
gnufede requested a review from P403n1x87 November 26, 2026 17:12
@gnufede
gnufede marked this pull request as ready for review November 26, 2026 17:12
@gnufede
gnufede requested review from a team as code owners November 26, 2026 17:12
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-26T17:15:55.828793Z 3745405 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3745405a21

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +260 to +261
_get_code = getattr(_get_code, "_dd_original_get_code", _get_code)
if _get_code is not None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add the required startup benchmark coverage

This changes the watched-import startup path and allocates and binds a fresh wrapper whenever a loader is reused, but the supplied validation reports correctness tests and commit hooks without benchmark results. The repository explicitly requires benchmarks for startup-sensitive changes. Run the run-benchmarks skill comparing the parent and this commit for startup and shared-loader imports, and record the results before accepting the additional import-time work.

AGENTS.md reference: AGENTS.md:L16-L18

Useful? React with 👍 / 👎.

@datadog-prod-us1-5 datadog-prod-us1-5 Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: PASS

More details

Saving and rewrapping the original get_code binds transformations to each imported module while preventing wrappers from accumulating across reloads. The specialist’s static review returned no actionable findings.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 3745405

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant