Skip to content

fix(undici): prevent context retention after requests - #9406

Merged
bengl merged 3 commits into
masterfrom
BridgeAR/2026-07-16-fix-undici-context-retention
Sep 3, 2026
Merged

bengl merged 3 commits into
masterfrom
BridgeAR/2026-07-16-fix-undici-context-retention

Conversation

@BridgeAR

@BridgeAR BridgeAR commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Native Undici diagnostic callbacks entered request spans into the caller's async context. The context outlived finished requests, retained downstream resources, and made later work inherit the wrong span.

Keep native diagnostics for normal request lifecycles. For accepted upgrades, inspect the loaded Request method and install the fallback only when that method does not publish terminal diagnostics. Patched and backported Undici implementations remain untouched.

Activate the request span only while a configured request hook runs.

The request-create hot path no longer copies the async store or switches context twice. Two fresh one-million-iteration runs improved from 43.1-43.5 ns to 10.1-10.2 ns per operation.

The native Undici fix is tracked in nodejs/undici#5761.

@dd-octo-sts

dd-octo-sts Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Overall package size

Self size: 8.74 MB
Deduped: 9.41 MB
No deduping: 9.41 MB

Dependency sizes | name | version | self size | total size | |------|---------|-----------|------------| | import-in-the-middle | 3.4.0 | 127.33 kB | 447.04 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

@datadog-prod-us1-3

datadog-prod-us1-3 Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
• Patch Coverage: 100.00%
• Overall Coverage: 98.63% (+0.00%)

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

@pr-commenter

pr-commenter Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-09-03 19:36:49

Comparing candidate commit e92c153 in PR branch BridgeAR/2026-07-16-fix-undici-context-retention with baseline commit 773dd93 in branch master.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 2316 metrics, 12 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 ----------------------------------'

Unstable benchmarks

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

scenario:appsec-iast-no-vulnerability-iast-enabled-default-config-24

  • unstable max_rss_usage [-28.425MB; +43.535MB] or [-8.546%; +13.089%]

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

  • unstable max_rss_usage [-22.590MB; +17.851MB] or [-6.122%; +4.838%]

scenario:debugger-line-probe-with-snapshot-minimal-24

  • unstable max_rss_usage [-16495.325KB; +14836.125KB] or [-6.471%; +5.820%]

scenario:debugger-line-probe-without-snapshot-24

  • unstable max_rss_usage [-14.122MB; +18.175MB] or [-4.802%; +6.180%]

scenario:dogstatsd-with-tags-20

  • unstable cpu_user_time [-431.244ms; +174.410ms] or [-8.958%; +3.623%]
  • unstable execution_time [-426.017ms; +177.097ms] or [-8.704%; +3.618%]
  • unstable throughput [-61023.159op/s; +143459.409op/s] or [-3.561%; +8.373%]

scenario:encoders-0.4-immediate-flush-20

  • unstable max_rss_usage [-10.937MB; +5.589MB] or [-14.319%; +7.317%]

scenario:fs-subscribed-26

  • unstable execution_time [-66.313ms; +98.638ms] or [-5.241%; +7.796%]

scenario:llmobs-encode-unicode-mixed-20

  • unstable max_rss_usage [-14.682MB; +1.671MB] or [-19.189%; +2.184%]

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

  • unstable max_rss_usage [-8.604MB; +14.786MB] or [-6.052%; +10.401%]

scenario:test-optimization-large-suite-20

  • unstable max_rss_usage [-5311.167KB; +6964.167KB] or [-6.510%; +8.536%]

@codecov

codecov Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.63%. Comparing base (773dd93) to head (e92c153).
⚠️ Report is 4 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff            @@
##           master    #9406    +/-   ##
========================================
  Coverage   98.63%   98.63%            
========================================
  Files        1003     1003            
  Lines      154854   154931    +77     
  Branches    13109    13815   +706     
========================================
+ Hits       152737   152814    +77     
  Misses       2117     2117            
Flag Coverage Δ
aiguard 63.81% <ø> (-0.04%) ⬇️
aiguard-integration 58.87% <ø> (-0.05%) ⬇️
apm-capabilities-tracing 62.91% <33.33%> (+0.04%) ⬆️
apm-integrations-aerospike 61.12% <ø> (-0.13%) ⬇️
apm-integrations-aerospike-_integrat-1d185c06 63.09% <ø> (-0.13%) ⬇️
apm-integrations-confluentinc-kafka--d0bf0045 67.32% <ø> (+0.02%) ⬆️
apm-integrations-couchbase 61.62% <ø> (-0.14%) ⬇️
apm-integrations-elasticsearch_integ-31b69669 68.63% <73.75%> (+0.05%) ⬆️
apm-integrations-http 66.88% <ø> (+0.02%) ⬆️
apm-integrations-http2_integrations--9aea12f5 68.21% <ø> (+0.02%) ⬆️
apm-integrations-kafkajs 67.93% <ø> (+0.02%) ⬆️
apm-integrations-next 64.79% <ø> (-0.13%) ⬇️
apm-integrations-prisma 62.40% <ø> (-0.11%) ⬇️
apm-integrations-restify_integration-b312dd16 64.91% <ø> (-0.13%) ⬇️
appsec 77.33% <ø> (+<0.01%) ⬆️
appsec-express_fastify_graphql 72.72% <ø> (+0.01%) ⬆️
appsec-integration 49.51% <35.84%> (-0.03%) ⬇️
appsec-kafka_ldapjs_lodash 68.01% <ø> (+0.01%) ⬆️
appsec-mongodb-core_mongoose_mysql 71.15% <ø> (+0.01%) ⬆️
appsec-next 57.61% <ø> (-0.09%) ⬇️
appsec-node-serialize_passport_postgres 70.64% <ø> (+0.01%) ⬆️
appsec-sourcing_stripe_template 69.08% <ø> (+0.01%) ⬆️
debugger 69.66% <ø> (-0.16%) ⬇️
instr-ai_instrumentation-anthropic-l-e862da55 56.48% <ø> (-0.13%) ⬇️
instr-bluebird_instrumentation-body--02ae4b41 64.73% <ø> (-0.13%) ⬇️
instr-confluentinc-kafka-javascript 55.88% <ø> (-0.13%) ⬇️
instr-connect_instrumentation-cookie-0bbb44d9 57.59% <ø> (-0.12%) ⬇️
instr-couchbase 55.10% <ø> (-0.13%) ⬇️
instr-cypress-config_instrumentation-4db1de46 57.91% <ø> (-0.12%) ⬇️
instr-express-multi-version_instrume-f5caf487 64.19% <ø> (-0.13%) ⬇️
instr-fetch_instrumentation-fs_instr-43dfe6a2 50.46% <ø> (-0.10%) ⬇️
instr-hono_instrumentation-http_inst-026a5d4d 66.20% <ø> (+0.02%) ⬆️
instr-kafkajs_instrumentation-knex_i-ca6f5b19 56.54% <ø> (-0.13%) ⬇️
instr-light-my-request_instrumentati-8c9fceca 63.51% <ø> (-0.12%) ⬇️
instr-mysql_instrumentation-mysql2_i-05f94c42 59.01% <ø> (-0.11%) ⬇️
instr-openai-lifecycle_instrumentati-783580bd 65.87% <ø> (-0.12%) ⬇️
instr-passport-http_instrumentation--2b6c8eb6 66.48% <ø> (-0.12%) ⬇️
instr-promise_instrumentation-promis-8479bae3 56.32% <ø> (-0.13%) ⬇️
instr-restify_instrumentation-router-5641467c 56.47% <ø> (-0.12%) ⬇️
instr-url_instrumentation-when_instr-22ca7078 56.34% <ø> (-0.13%) ⬇️
instrumentations-integration-esbuild 34.64% <35.84%> (-0.03%) ⬇️
llmobs-ai_anthropic_bedrock 66.84% <ø> (+0.03%) ⬆️
llmobs-claude-agent-sdk_google-genai-da2c851e 65.03% <ø> (+0.03%) ⬆️
llmobs-openai 66.85% <ø> (+0.03%) ⬆️
llmobs-openai-agents_vertex-ai 64.07% <ø> (-0.10%) ⬇️
llmobs-sdk 76.62% <ø> (+0.01%) ⬆️
master-coverage 98.63% <100.00%> (?)
openfeature 60.05% <ø> (-0.06%) ⬇️
openfeature-unit 58.74% <ø> (-0.13%) ⬇️
platform-core_esbuild_instrumentations-misc 41.29% <35.84%> (-0.06%) ⬇️
platform-integration 65.39% <ø> (-0.06%) ⬇️
platform-shimmer_unit-guardrails_webpack 39.05% <35.84%> (-0.06%) ⬇️
plugins-aws-durable-execution-sdk-js-2bc88c07 61.17% <ø> (+0.02%) ⬆️
plugins-azure-event-hubs_azure-servi-50d5b0fc 58.46% <ø> (-0.07%) ⬇️
plugins-browser-bunyan_bullmq_cassandra 66.41% <ø> (+0.02%) ⬆️
plugins-cookie_cookie-parser_crypto 56.08% <ø> (-0.14%) ⬇️
plugins-dd-trace-api_express-mongo-s-83827a5c 61.67% <ø> (-0.14%) ⬇️
plugins-fastify_fetch_fs 66.02% <ø> (-0.01%) ⬇️
plugins-generic-pool_google-cloud-pubsub_grpc 69.58% <ø> (+0.01%) ⬆️
plugins-handlebars_hapi_hono 64.16% <ø> (-0.13%) ⬇️
plugins-ioredis_knex_langgraph 61.86% <ø> (-0.13%) ⬇️
plugins-ldapjs_light-my-request_limitd-client 63.87% <ø> (-0.14%) ⬇️
plugins-lodash_mariadb_memcached 64.25% <ø> (-0.22%) ⬇️
plugins-mercurius_microgateway-core_-b9bd83c4 67.87% <ø> (+0.01%) ⬆️
plugins-moleculer_mongodb_mongodb-core 66.75% <ø> (+0.02%) ⬆️
plugins-mongoose_multer_mysql 64.45% <ø> (-0.13%) ⬇️
plugins-mysql2_nats_node-serialize 66.84% <ø> (+0.02%) ⬆️
plugins-opensearch_passport-http_pino 64.74% <ø> (+0.02%) ⬆️
plugins-postgres_process_pug 63.63% <ø> (-0.13%) ⬇️
plugins-redis_router_sequelize 67.32% <ø> (+0.02%) ⬆️
plugins-test-and-upstream-amqp10_tes-914101e2 65.54% <ø> (+0.02%) ⬆️
plugins-test-and-upstream-avsc_test--408e8d3a 65.51% <ø> (-0.13%) ⬇️
plugins-test-and-upstream-graphql_te-59dd94de 68.74% <ø> (-0.12%) ⬇️
plugins-test-and-upstream-rhea_undici_url 66.66% <100.00%> (+0.04%) ⬆️
plugins-valkey_vm_winston 62.95% <ø> (-0.13%) ⬇️
plugins-ws 65.17% <ø> (+0.02%) ⬆️
profiling 66.58% <ø> (-0.13%) ⬇️
serverless-aws-sdk-aws-sdk 55.99% <ø> (+0.02%) ⬆️
serverless-aws-sdk-base-inject-field 55.65% <ø> (-0.13%) ⬇️
serverless-aws-sdk-bedrockruntime 59.21% <ø> (-0.12%) ⬇️
serverless-aws-sdk-client 60.71% <ø> (+0.02%) ⬆️
serverless-aws-sdk-dynamodb 59.64% <ø> (-0.12%) ⬇️
serverless-aws-sdk-eventbridge 58.17% <ø> (+0.02%) ⬆️
serverless-aws-sdk-kinesis 63.72% <ø> (+0.02%) ⬆️
serverless-aws-sdk-lambda 61.71% <ø> (+0.02%) ⬆️
serverless-aws-sdk-s3 59.69% <ø> (-0.12%) ⬇️
serverless-aws-sdk-serverless-peer-service 64.29% <ø> (+0.02%) ⬆️
serverless-aws-sdk-sns 64.61% <ø> (+0.02%) ⬆️
serverless-aws-sdk-sqs 65.07% <ø> (+0.02%) ⬆️
serverless-aws-sdk-stepfunctions 59.69% <ø> (+0.02%) ⬆️
serverless-aws-sdk-util 56.28% <ø> (-0.14%) ⬇️
serverless-azure-durable-functions_a-776237ee 57.66% <65.00%> (-0.01%) ⬇️
serverless-azure-functions-eventhubs-61ee6313 64.31% <57.50%> (-0.03%) ⬇️
test-optimization-cucumber 70.39% <ø> (-0.04%) ⬇️
test-optimization-cypress 64.76% <ø> (-0.02%) ⬇️
test-optimization-jest 71.87% <ø> (-0.04%) ⬇️
test-optimization-mocha 71.86% <ø> (+<0.01%) ⬆️
test-optimization-playwright-playwri-363e40a6 59.66% <ø> (-0.04%) ⬇️
test-optimization-playwright-playwri-5141d36d 61.17% <ø> (-0.11%) ⬇️
test-optimization-playwright-playwri-5b35813b 59.54% <ø> (-0.11%) ⬇️
test-optimization-playwright-playwri-924f4516 60.83% <ø> (-0.11%) ⬇️
test-optimization-playwright-playwri-d6f5a99b 59.42% <ø> (-0.06%) ⬇️
test-optimization-playwright-playwright-atr 59.15% <ø> (-0.11%) ⬇️
test-optimization-playwright-playwright-efd 60.07% <ø> (-0.11%) ⬇️
test-optimization-selenium 58.76% <ø> (-0.12%) ⬇️
test-optimization-testopt 61.44% <ø> (-0.02%) ⬇️
test-optimization-vitest 72.55% <65.00%> (+0.12%) ⬆️
test-optimization-vitest-browser 58.86% <65.00%> (-0.04%) ⬇️
test-optimization-webdriverio 65.88% <65.00%> (+0.03%) ⬆️

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.

@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-07-16-fix-undici-context-retention branch 2 times, most recently from 0f9df13 to 70c86a7 Compare August 5, 2026 23:54
@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-07-16-fix-undici-context-retention branch from 70c86a7 to b83ebdc Compare August 8, 2026 18:26
@BridgeAR
BridgeAR marked this pull request as ready for review August 12, 2026 13:01
@BridgeAR
BridgeAR requested a review from a team as a code owner August 12, 2026 13:01
@BridgeAR
BridgeAR requested review from bojbrook and removed request for a team August 12, 2026 13:01

@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: 6ffd458e4e

ℹ️ 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 thread packages/datadog-plugin-undici/src/index.js Outdated
Comment thread packages/datadog-plugin-undici/src/index.js Outdated
Comment thread packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/undici.js Outdated
@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-07-16-fix-undici-context-retention branch from 6ffd458 to 6067da7 Compare September 3, 2026 14:33
@BridgeAR
BridgeAR requested a review from a team as a code owner September 3, 2026 14:33
@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-07-16-fix-undici-context-retention branch from 6067da7 to 5da6c72 Compare September 3, 2026 15:52
@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-07-16-fix-undici-context-retention branch from 5da6c72 to 9acf1d8 Compare September 3, 2026 16:09

@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: 9acf1d87a3

ℹ️ 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 thread packages/datadog-plugin-undici/src/index.js Outdated
Native diagnostic callbacks entered request spans into the caller's async context. The context outlived finished requests, retained downstream resources, and made later work inherit the wrong span.

Keep native diagnostics for normal request lifecycles and instrument only Undici's accepted-upgrade callback, which has no terminal diagnostic event. Activate the request span only while a configured request hook runs.

The request-create hot path no longer copies the async store or switches context twice. In two fresh one-million-iteration runs it improved from 43.1-43.5 ns to 10.1-10.2 ns per operation.

Refs: nodejs/undici#5761
Released Undici versions omit terminal diagnostics for accepted upgrades, but patched and backported implementations can share those versions. Inspecting the loaded Request method avoids wrapping implementations that already publish terminal trailers.
@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-07-16-fix-undici-context-retention branch from 9acf1d8 to 6b46468 Compare September 3, 2026 18:09
Accepted upgrade handlers can throw after Undici removes the request from its queue. Affected versions then destroy the socket without a terminal diagnostic event, which retains the span.

Publish one fallback error event and rethrow the original error. Scope the hook-context assertion to native diagnostics versions so Node 26 does not format unrelated cyclic span graphs.
@bengl
bengl merged commit 8283eb7 into master Sep 3, 2026
821 of 822 checks passed
@bengl
bengl deleted the BridgeAR/2026-07-16-fix-undici-context-retention branch September 3, 2026 20:17
dd-octo-sts Bot pushed a commit that referenced this pull request Sep 3, 2026
* fix(undici): prevent context retention after requests

Native diagnostic callbacks entered request spans into the caller's async context. The context outlived finished requests, retained downstream resources, and made later work inherit the wrong span.

Keep native diagnostics for normal request lifecycles and instrument only Undici's accepted-upgrade callback, which has no terminal diagnostic event. Activate the request span only while a configured request hook runs.

The request-create hot path no longer copies the async store or switches context twice. In two fresh one-million-iteration runs it improved from 43.1-43.5 ns to 10.1-10.2 ns per operation.

Refs: nodejs/undici#5761

* fix(undici): gate upgrade fallback by source

Released Undici versions omit terminal diagnostics for accepted upgrades, but patched and backported implementations can share those versions. Inspecting the loaded Request method avoids wrapping implementations that already publish terminal trailers.

* fix(undici): finish spans after upgrade handler errors

Accepted upgrade handlers can throw after Undici removes the request from its queue. Affected versions then destroy the socket without a terminal diagnostic event, which retains the span.

Publish one fallback error event and rethrow the original error. Scope the hook-context assertion to native diagnostics versions so Node 26 does not format unrelated cyclic span graphs.
This was referenced Sep 3, 2026
dd-octo-sts Bot pushed a commit that referenced this pull request Sep 3, 2026
* fix(undici): prevent context retention after requests

Native diagnostic callbacks entered request spans into the caller's async context. The context outlived finished requests, retained downstream resources, and made later work inherit the wrong span.

Keep native diagnostics for normal request lifecycles and instrument only Undici's accepted-upgrade callback, which has no terminal diagnostic event. Activate the request span only while a configured request hook runs.

The request-create hot path no longer copies the async store or switches context twice. In two fresh one-million-iteration runs it improved from 43.1-43.5 ns to 10.1-10.2 ns per operation.

Refs: nodejs/undici#5761

* fix(undici): gate upgrade fallback by source

Released Undici versions omit terminal diagnostics for accepted upgrades, but patched and backported implementations can share those versions. Inspecting the loaded Request method avoids wrapping implementations that already publish terminal trailers.

* fix(undici): finish spans after upgrade handler errors

Accepted upgrade handlers can throw after Undici removes the request from its queue. Affected versions then destroy the socket without a terminal diagnostic event, which retains the span.

Publish one fallback error event and rethrow the original error. Scope the hook-context assertion to native diagnostics versions so Node 26 does not format unrelated cyclic span graphs.
BridgeAR added a commit that referenced this pull request Sep 4, 2026
* fix(undici): prevent context retention after requests

Native diagnostic callbacks entered request spans into the caller's async context. The context outlived finished requests, retained downstream resources, and made later work inherit the wrong span.

Keep native diagnostics for normal request lifecycles and instrument only Undici's accepted-upgrade callback, which has no terminal diagnostic event. Activate the request span only while a configured request hook runs.

The request-create hot path no longer copies the async store or switches context twice. In two fresh one-million-iteration runs it improved from 43.1-43.5 ns to 10.1-10.2 ns per operation.

Refs: nodejs/undici#5761

* fix(undici): gate upgrade fallback by source

Released Undici versions omit terminal diagnostics for accepted upgrades, but patched and backported implementations can share those versions. Inspecting the loaded Request method avoids wrapping implementations that already publish terminal trailers.

* fix(undici): finish spans after upgrade handler errors

Accepted upgrade handlers can throw after Undici removes the request from its queue. Affected versions then destroy the socket without a terminal diagnostic event, which retains the span.

Publish one fallback error event and rethrow the original error. Scope the hook-context assertion to native diagnostics versions so Node 26 does not format unrelated cyclic span graphs.
BridgeAR added a commit that referenced this pull request Sep 4, 2026
* fix(undici): prevent context retention after requests

Native diagnostic callbacks entered request spans into the caller's async context. The context outlived finished requests, retained downstream resources, and made later work inherit the wrong span.

Keep native diagnostics for normal request lifecycles and instrument only Undici's accepted-upgrade callback, which has no terminal diagnostic event. Activate the request span only while a configured request hook runs.

The request-create hot path no longer copies the async store or switches context twice. In two fresh one-million-iteration runs it improved from 43.1-43.5 ns to 10.1-10.2 ns per operation.

Refs: nodejs/undici#5761

* fix(undici): gate upgrade fallback by source

Released Undici versions omit terminal diagnostics for accepted upgrades, but patched and backported implementations can share those versions. Inspecting the loaded Request method avoids wrapping implementations that already publish terminal trailers.

* fix(undici): finish spans after upgrade handler errors

Accepted upgrade handlers can throw after Undici removes the request from its queue. Affected versions then destroy the socket without a terminal diagnostic event, which retains the span.

Publish one fallback error event and rethrow the original error. Scope the hook-context assertion to native diagnostics versions so Node 26 does not format unrelated cyclic span graphs.
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.

2 participants