← Back to Pull requests

fix(internal): resolve shared loader get_code via active exec context #22131

Open
unknown opened this pull request with 464 lines diff across 5 files
View on GitHub
unknown unknown commented on Nov 26, 2026 16:10 UTC
Author

Description

_ImportHookChainedLoader._exec_module wraps the imported module's loader get_code so registered transformers (code transformations / bytecode instrumentation) run on the code that gets executed. When a loader is shared by several modules — e.g. a zipimporter serving every module of a zip application or bundled deployment — that wrapper was bound to the module of whichever import happened to install it. As a result:

  • subsequent (and concurrent) imports through the same shared loader were transformed using the wrong module;

  • any later get_code() caller (e.g. runpy, inspect, linecache) received transformed code;

  • a failed importlib.reload() left the wrapper in a state that kept transforming code fetched afterwards.
  • This PR replaces the captured-module design with a context-local active-exec marker:

  • The wrapper is installed on the exact loader that owns get_code, resolved via the bound method's __self__. This works even when self.loader is a proxy (e.g. wrapt's _ImportHookChainedLoader wrapping the shared loader) and when get_code was already wrapped by a previous import.

  • While a chained loader executes a module, _exec_module records (loader, chained_loader, module) in a contextvars.ContextVar. The wrapper transforms the code only when the fetch is for that exact loader/module during that execution (consuming the marker once, so a get_code() call made from the module body itself returns untransformed code), and returns untransformed code to every other caller.

  • The marker is set around the execution (including pre-exec hooks) and restored in a finally, so failures (e.g. a module raising during reload) cannot poison later get_code() calls, and after-import callbacks run after it is reset.
  • After-import hooks (after_import) are unaffected: only code transformations / bytecode instrumentation were impacted.

    Changelog

  • fix(internal): resolve shared loader get_code via active exec context
  • Tests / Validation

    New tests/internal/test_module_shared_loader.py (subprocess tests, skipped below Python 3.10 where zipimporter has no exec_module):

  • each module imported through a shared loader is transformed with its own module (incl. two concurrent imports interleaving on the same loader, with a pre-exec hook holding one import mid-flight);

  • get_code() for other modules — and from the module's own body, and after a failed reload — returns untransformed code;

  • modules executed via module_from_spec/spec.loader.exec_module without entering sys.modules are still transformed;

  • with a pending wrapt post-import hook, both sys.meta_path orderings (watchdog loader wrapping wrapt(zipimporter), and wrapt's chained loader wrapping dd(zipimporter)) transform on first import and on a later importlib.reload() (with explicit sys.meta_path.index(...) assertions so each variant proves which chain ran).
  • Validation performed:

  • scripts/lint fmt, scripts/lint typing, scripts/lint type-comments-check --base-ref origin/main, scripts/lint checks — all pass;

  • full tests/internal/ suite (Python 3.14): 3391 passed, 38 skipped, 14 xfailed, 15 xpassed (xpasses pre-existing in test_native_logger.py);

  • focused tests/internal/test_module.py + tests/internal/test_module_shared_loader.py on Python 3.14 (wrapt 2.x) and Python 3.13 (wrapt 1.x) — all pass;

  • mutation check: against main, 5 of the 8 new tests fail, confirming they cover the regressions.
  • Risks

    Low: the change is confined to the get_code wrapping path in ddtrace/internal/module.py; loaders without get_code are untouched, and the wrapper's behavior for non-shared loaders is unchanged.

    Diff: 464 lines (+348 / -116) across 5 files Reviewer: gnufede Review duration: 6662m
    All Vouch review confidence checks passed
    Residual risk 0.24 = Change Risk (0.46) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.46 · 464 lines diff across 5 files
    0.46
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    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.367
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #22131"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% 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: 45.6% (MEDIUM) · Higher = larger blast radius
    45.6%
    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: 46.7% · Lower = rushed or shallow review
    46.7%
    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: 24.3% · Safe to merge
    24.3%