Skip to content

feat(instrumentations): rewrite ES modules loaded through require() - #11396

Closed
pabloerhard wants to merge 1 commit into
masterfrom
pabloerhard/support-esm-rewrites-require
Closed

pabloerhard wants to merge 1 commit into
masterfrom
pabloerhard/support-esm-rewrites-require

Conversation

@pabloerhard

Copy link
Copy Markdown
Collaborator

What does this PR do?

CommonJS apps started with only -r dd-trace/init now rewrite ES modules loaded through require(), including the files those modules import, which Module._compile never sees.

  • On Node.js releases with working sync hooks (22.22.3+, 24.11.1+, 25.1+, 26+), init() registers a small module.registerHooks load hook that rewrites ES modules only. CommonJS stays with the Module._compile shim.
  • When register.js or initialize.mjs registers dd-trace's loader, the loader takes over and the tracer's hook is deregistered. With sync hooks, the loader's combined hook runs the rewriter outside import-in-the-middle; on the async fallback, the sync hook is removed first, so sync and async rewriting never run side by side. If the loader registered first, init() adds nothing.
  • Module._compile no longer rewrites an ES module that a sync hook already rewrote. Before, it was instrumented twice under --import dd-trace/register.js.

Motivation

Rewrite targets that ship as ESM and get require()d, such as postgres 4, were only partially instrumented without a loader flag.

Why CommonJS rewrites stay in Module._compile instead of moving to sync hooks: when an async (module.register) loader is also in the chain, whether dd-trace's fallback or another vendor's like tsx or OpenTelemetry, Node.js hands sync hooks imported CommonJS with source: undefined and compiles the file later. A sync hook can't rewrite it. Module._compile always sees the final source, so it stays the CommonJS path, and the sync hook only handles ESM.

Why there is no async rewriter hook on releases without working sync hooks: registering one from -r dd-trace/init starts a loader thread that also runs -r preloads, so it needs a guard to keep a second tracer out of that thread. Next to dd-trace's own async loader, it also needs both hooks to coordinate so files aren't rewritten twice. That complexity isn't worth it for older release lines; there, --import dd-trace/register.js remains the way to get these rewrites.

Additional Notes

  • The hand-over is about hook order: -r preloads run before --import, so without it the tracer's hook sits inside import-in-the-middle's, and import-in-the-middle's read of a module's exports triggers a full rewrite that is thrown away.
  • isSyncLoaderHookVersionSupported() moved to packages/dd-trace/src/sync-loader-hooks.js so loader.js can share it. Without the check, the hook crashes on 22.15 (context.conditions isn't an array) and next to another async loader before module: handle null source from async loader hooks in sync hooks nodejs/node#59929.
  • module-hooks.spec.js covers each startup combination. A preload counts rewrites per file, so a rewrite whose output is thrown away fails the test. Passing on Node.js 22.12, 22.15, 22.19 and 24.10 (sync-hook cases skipped) and on 24.15 and 26.5.

@dd-octo-sts

dd-octo-sts Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Overall package size

Self size: 9.56 MB
Deduped: 10.32 MB
No deduping: 10.32 MB

Dependency sizes | name | version | self size | total size | |------|---------|-----------|------------| | import-in-the-middle | 3.5.3 | 131.25 kB | 531.9 kB | | opentracing | 0.14.7 | 194.81 kB | 194.81 kB | | dc-polyfill | 0.1.11 | 25.74 kB | 25.74 kB |

🤖 This report was automatically generated by heaviest-objects-in-the-universe

@pabloerhard pabloerhard changed the title feat(instrumentations): rewrite ES modules loaded through require() with -r dd-trace/init feat(instrumentations): rewrite ES modules loaded through require() Nov 23, 2026
@datadog-prod-us1-4

datadog-prod-us1-4 Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

❌ Errors

Your PR has failed checks. Please review the issues below and take necessary action before merging.

🚦 5 Pipeline jobs failed

APM Integrations | electron — 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

Instrumentation | instrumentations-misc — 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

All Green | all-green

View more details · View in GitHub Actions

View all 5 failed jobs.

ℹ️ Info

No other issues found (see more)

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
• Patch Coverage: 100.00%
• Overall Coverage: 81.32% (-8.26%)

Useful? React with 👍 / 👎

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

@codecov

codecov Bot commented Nov 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.36%. Comparing base (830b83d) to head (fd24816).
⚠️ Report is 8 commits behind head on master.

❗ There is a different number of reports uploaded between BASE (830b83d) and HEAD (fd24816). Click for more details.

HEAD has 3 uploads less than BASE
Flag BASE (830b83d) HEAD (fd24816)
instrumentation 1 0
apm-integrations 1 0
test-optimization 1 0
Additional details and impacted files
@@             Coverage Diff             @@
##           master   #11396       +/-   ##
===========================================
- Coverage   99.15%   81.36%   -17.80%     
===========================================
  Files        1136     1114       -22     
  Lines      188287   181888     -6399     
  Branches       86       81        -5     
===========================================
- Hits       186698   147991    -38707     
- Misses       1589    33897    +32308     
Flag Coverage Δ
ai-guard 63.40% <91.97%> (+0.08%) ⬆️
apm-capabilities 55.19% <97.38%> (+0.04%) ⬆️
apm-integrations ?
appsec 59.38% <100.00%> (+0.15%) ⬆️
debugger 70.96% <98.02%> (+0.08%) ⬆️
instrumentation ?
llmobs 82.54% <99.34%> (+0.02%) ⬆️
master-coverage 81.36% <100.00%> (?)
openfeature 68.13% <91.97%> (+0.08%) ⬆️
platform 68.23% <100.00%> (+0.10%) ⬆️
profiling 66.58% <91.97%> (+0.11%) ⬆️
serverless 66.72% <99.34%> (+0.08%) ⬆️
test-optimization ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pr-commenter

pr-commenter Bot commented Nov 24, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-24 00:00:39

Comparing candidate commit fd24816 in PR branch pabloerhard/support-esm-rewrites-require with baseline commit 830b83d in branch master.

📊 Benchmarking dashboard

Found 0 performance improvements and 1 performance regressions! Performance is the same for 2469 metrics, 17 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:startup-with-tracer-everything-24

  • 🟥 max_rss_usage [+4.955MB; +10.737MB] or [+2.474%; +5.362%]

Unstable benchmarks

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

scenario:appsec-appsec-enabled-20

  • unstable max_rss_usage [-70.257MB; +49.819MB] or [-28.409%; +20.145%]

scenario:appsec-iast-with-vulnerability-iast-enabled-default-config-20

  • unstable max_rss_usage [-10.325MB; +33.781MB] or [-2.814%; +9.205%]

scenario:appsec-iast-with-vulnerability-iast-enabled-default-config-26

  • unstable max_rss_usage [-22.769MB; +10.260MB] or [-7.396%; +3.333%]

scenario:debugger-line-probe-with-snapshot-default-26

  • unstable max_rss_usage [-9903.375KB; +11161.375KB] or [-5.272%; +5.941%]

scenario:encoders-0.4-immediate-flush-20

  • unstable max_rss_usage [-16.526MB; +7.323MB] or [-19.921%; +8.828%]

scenario:openfeature-initialization-configuration-20

  • unstable max_rss_usage [-5440.713KB; +4133.076KB] or [-7.112%; +5.402%]

scenario:openfeature-initialization-configuration-26

  • unstable cpu_user_time [-114.459ms; +97.079ms] or [-6.698%; +5.681%]
  • unstable execution_time [-118.623ms; +99.132ms] or [-6.686%; +5.587%]
  • unstable throughput [-32126.310op/s; +36216.459op/s] or [-5.592%; +6.304%]

scenario:openfeature-initialization-error-20

  • unstable max_rss_usage [-4757.523KB; +5368.914KB] or [-6.319%; +7.131%]

scenario:openfeature-initialization-error-26

  • unstable cpu_user_time [-79.582ms; +192.533ms] or [-3.126%; +7.563%]
  • unstable execution_time [-80.645ms; +191.779ms] or [-3.087%; +7.342%]

scenario:openfeature-scale-full-26

  • unstable max_rss_usage [-25.077MB; +31.170MB] or [-10.603%; +13.180%]

scenario:plugin-graphql-long-with-depth-off-26

  • unstable max_rss_usage [-19.631MB; +31.551MB] or [-10.399%; +16.713%]

scenario:plugin-graphql-long-with-depth-on-max-26

  • unstable max_rss_usage [-35.746MB; +4.920MB] or [-18.405%; +2.533%]

scenario:sampling-rate-limited-26

  • unstable cpu_user_time [-86.455ms; +138.787ms] or [-4.728%; +7.589%]
  • unstable execution_time [-86.897ms; +139.442ms] or [-4.738%; +7.603%]

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant