Skip to content

fix(fastify): bound error-channel recursion and stop swallowing async hook rejections#9118

Merged
BridgeAR merged 5 commits into
masterfrom
BridgeAR/2026-06-27-fastify-error-recursion
Jul 6, 2026
Merged

fix(fastify): bound error-channel recursion and stop swallowing async hook rejections#9118
BridgeAR merged 5 commits into
masterfrom
BridgeAR/2026-06-27-fastify-error-recursion

Conversation

@BridgeAR

Copy link
Copy Markdown
Member

Summary

Fastify boots through avvio, whose _encapsulateThreeParam re-invokes an encapsulated hook after it throws. The same error object rides every re-drive, and the wrapped hook republishes it on apm:fastify:middleware:error each time. The in-flight boolean added in #8788 only blocks a publish nested inside another publish; a sequential re-drive runs after the publish returned and its finally cleared the flag, so every re-drive publishes again, the channel subscriber recurses, and boot dies with RangeError: Maximum call stack size exceeded. A persistent DatadogRaspAbortError (appsec RASP) or the boot deprecation warning is the error that rides the loop.

  1. createErrorPublisher keeps the boolean for nested re-entry and adds a WeakSet keyed on the error object, so the same error publishes at most once per channel — bounding the sequential re-drive a boolean cannot. A genuinely distinct error still reaches subscribers; the entry frees once the error object is unreachable.
  2. invokeHookWithContext's async branch returned publishError(ctx) (i.e. ctx.error) from the .catch handler, which resolves the promise with the error and silently swallows the rejection. It now publishes and re-throws so the rejection keeps propagating. The synchronous branch is decoupled the same way: publish, then throw the original error rather than the publisher's return value.

Why

The error channel's two subscribers — the router plugin's web.addError (tag the request span once) and appsec RASP's block (block the response once) — both want once-per-error cardinality, so keying the guard on the error object matches what they need. The residual trade-off is that the same error object reaching the channel through two genuinely distinct contexts publishes once; that is exactly the recursion being bounded, and once-per-error is the correct cardinality for both subscribers.

The real avvio re-drive needs a specific plugin/encapsulation arrangement from the reporter's app that I could not reconstruct, so the regression pins the precise invariant at the real seam instead: the real wrapped hook, driven the way avvio drives a re-thrown hook, publishes a persistent error exactly once across thousands of re-drives (fails on master with one publish per re-drive), a distinct error still publishes each time, and a rejecting async hook re-rejects instead of resolving-with-error.

Test plan

  • packages/datadog-instrumentations/test/fastify.spec.js (exercised by the instrumentation-fastify CI job): the three added/changed cases fail on master and pass here.
  • Sibling frameworks that share createErrorPublisher (koa, connect, restify, router) — instrumentation specs stay green.

Fixes: #9099
Refs: #8783

@dd-octo-sts

dd-octo-sts Bot commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

Overall package size

Self size: 6.53 MB
Deduped: 7.59 MB
No deduping: 7.59 MB

Dependency sizes | name | version | self size | total size | |------|---------|-----------|------------| | import-in-the-middle | 3.2.0 | 104.26 kB | 843.44 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-datadog-prod-us1

datadog-datadog-prod-us1 Bot commented Jun 27, 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: 87.86% (-0.13%)

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: a7a0b06 | Docs | Datadog PR Page | Give us feedback!

@codecov

codecov Bot commented Jun 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.64%. Comparing base (27dcc31) to head (a7a0b06).
⚠️ Report is 39 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9118      +/-   ##
==========================================
- Coverage   93.69%   93.64%   -0.05%     
==========================================
  Files         889      898       +9     
  Lines       50856    52370    +1514     
  Branches    11830    12325     +495     
==========================================
+ Hits        47647    49042    +1395     
- Misses       3209     3328     +119     
Flag Coverage Δ
aiguard 34.88% <ø> (-0.08%) ⬇️
aiguard-integration 41.96% <ø> (+0.17%) ⬆️
apm-bucket-0 34.84% <ø> (-0.08%) ⬇️
apm-bucket-1 40.51% <ø> (+0.09%) ⬆️
apm-bucket-2 37.50% <ø> (+0.08%) ⬆️
apm-capabilities-tracing 48.88% <ø> (+0.59%) ⬆️
apm-integrations-aerospike 33.13% <ø> (-0.08%) ⬇️
apm-integrations-confluentinc-kafka-javascript 40.12% <ø> (+0.01%) ⬆️
apm-integrations-couchbase 33.41% <ø> (-0.19%) ⬇️
apm-integrations-http 42.05% <ø> (-0.06%) ⬇️
apm-integrations-kafkajs 40.27% <ø> (-0.08%) ⬇️
apm-integrations-next 29.63% <ø> (+0.05%) ⬆️
apm-integrations-prisma 35.18% <ø> (+0.07%) ⬆️
apm-integrations-tedious 34.05% <ø> (+0.07%) ⬆️
appsec 57.90% <ø> (+0.46%) ⬆️
appsec-express_fastify_graphql 53.87% <63.63%> (+0.06%) ⬆️
appsec-integration 35.68% <0.00%> (-0.58%) ⬇️
appsec-kafka_ldapjs_lodash 43.83% <ø> (+0.17%) ⬆️
appsec-mongodb-core_mongoose_mysql 48.93% <ø> (+0.05%) ⬆️
appsec-next 28.11% <ø> (+0.04%) ⬆️
appsec-node-serialize_passport_postgres 48.08% <ø> (+0.02%) ⬆️
appsec-sourcing_stripe_template 45.64% <ø> (+0.01%) ⬆️
debugger 44.62% <0.00%> (+0.20%) ⬆️
instrumentations-bucket-0 28.17% <ø> (-0.07%) ⬇️
instrumentations-bucket-1 37.57% <ø> (+0.08%) ⬆️
instrumentations-bucket-10 40.52% <ø> (+0.01%) ⬆️
instrumentations-bucket-11 27.96% <ø> (-0.07%) ⬇️
instrumentations-bucket-12 28.79% <ø> (+0.04%) ⬆️
instrumentations-bucket-13 27.79% <ø> (-0.07%) ⬇️
instrumentations-bucket-2 30.36% <ø> (+0.05%) ⬆️
instrumentations-bucket-3 36.06% <ø> (+0.07%) ⬆️
instrumentations-bucket-4 28.60% <100.00%> (+0.45%) ⬆️
instrumentations-bucket-5 36.42% <ø> (+0.07%) ⬆️
instrumentations-bucket-6 38.43% <ø> (+0.09%) ⬆️
instrumentations-bucket-7 36.15% <0.00%> (+0.07%) ⬆️
instrumentations-bucket-8 37.11% <ø> (+0.08%) ⬆️
instrumentations-bucket-9 39.62% <ø> (+0.01%) ⬆️
instrumentations-instrumentation-couchbase 46.48% <ø> (-0.07%) ⬇️
instrumentations-integration-esbuild 24.51% <0.00%> (-0.37%) ⬇️
llmobs-ai_anthropic_bedrock 39.68% <ø> (+0.08%) ⬆️
llmobs-google-genai_langchain_vertex-ai 37.10% <ø> (+0.06%) ⬆️
llmobs-openai 39.74% <ø> (+0.09%) ⬆️
llmobs-sdk 43.59% <ø> (-0.10%) ⬇️
master-coverage 93.64% <100.00%> (?)
openfeature 37.94% <ø> (+0.17%) ⬆️
openfeature-unit 50.47% <ø> (+0.07%) ⬆️
platform-core_esbuild_instrumentations-misc 22.96% <0.00%> (-0.41%) ⬇️
platform-integration 47.58% <0.00%> (+0.15%) ⬆️
platform-shimmer_unit-guardrails_webpack 18.47% <0.00%> (-0.42%) ⬇️
plugins-bucket-0 36.52% <ø> (+0.12%) ⬆️
plugins-bucket-1 39.78% <ø> (+0.17%) ⬆️
plugins-bucket-11 38.63% <ø> (+0.09%) ⬆️
plugins-bucket-17 39.22% <ø> (-0.01%) ⬇️
plugins-bucket-18 42.17% <ø> (+0.09%) ⬆️
plugins-bucket-19 39.73% <ø> (+0.09%) ⬆️
plugins-bucket-20 43.44% <ø> (+0.07%) ⬆️
plugins-bucket-4 37.90% <81.81%> (+0.10%) ⬆️
plugins-bullmq_cassandra_cookie 39.93% <ø> (+0.09%) ⬆️
plugins-cookie-parser_crypto_dd-trace-api 33.23% <ø> (-0.08%) ⬇️
plugins-fetch_fs_generic-pool 36.21% <ø> (+0.08%) ⬆️
plugins-google-cloud-pubsub_grpc_handlebars 43.09% <ø> (-0.10%) ⬇️
plugins-hapi_hono_ioredis 37.95% <ø> (+0.08%) ⬆️
plugins-jest_knex_langgraph 32.61% <ø> (-0.08%) ⬇️
plugins-ldapjs_light-my-request_limitd-client 27.86% <ø> (-0.07%) ⬇️
plugins-lodash_mariadb_memcached 35.18% <ø> (-0.08%) ⬇️
plugins-mongodb_mongodb-core_mongoose 36.46% <ø> (+0.08%) ⬆️
plugins-multer_mysql_mysql2 35.15% <ø> (-0.08%) ⬇️
plugins-nats_node-serialize_opensearch 37.31% <ø> (+0.08%) ⬆️
plugins-passport-http_pino_postgres 35.53% <ø> (-0.08%) ⬇️
plugins-process_pug_redis 34.27% <ø> (-0.08%) ⬇️
plugins-undici_url_valkey 36.04% <ø> (+0.08%) ⬆️
plugins-vm_winston_ws 37.72% <ø> (+0.08%) ⬆️
profiling 43.81% <ø> (+0.12%) ⬆️
serverless-aws-sdk-aws-sdk 33.32% <ø> (-0.05%) ⬇️
serverless-aws-sdk-bedrockruntime 32.19% <ø> (-0.04%) ⬇️
serverless-aws-sdk-client 37.16% <ø> (-0.05%) ⬇️
serverless-aws-sdk-dynamodb 34.14% <ø> (-0.09%) ⬇️
serverless-aws-sdk-eventbridge 27.36% <ø> (+0.04%) ⬆️
serverless-aws-sdk-kinesis 37.55% <ø> (+0.07%) ⬆️
serverless-aws-sdk-lambda 34.64% <ø> (-0.03%) ⬇️
serverless-aws-sdk-s3 32.63% <ø> (-0.04%) ⬇️
serverless-aws-sdk-serverless-peer-service 39.74% <ø> (+0.19%) ⬆️
serverless-aws-sdk-sns 38.40% <ø> (-0.05%) ⬇️
serverless-aws-sdk-sqs 38.14% <ø> (+0.07%) ⬆️
serverless-aws-sdk-stepfunctions 33.22% <ø> (-0.04%) ⬇️
serverless-aws-sdk-util 47.95% <ø> (ø)
serverless-bucket-0 39.64% <ø> (+0.17%) ⬆️
serverless-lambda 34.34% <ø> (-0.08%) ⬇️
test-optimization-cucumber 52.54% <ø> (+0.08%) ⬆️
test-optimization-cypress 49.63% <ø> (+0.07%) ⬆️
test-optimization-jest 55.61% <ø> (+0.04%) ⬆️
test-optimization-mocha 53.65% <ø> (+0.07%) ⬆️
test-optimization-playwright-playwright-atr 43.53% <ø> (+0.03%) ⬆️
test-optimization-playwright-playwright-efd 43.81% <ø> (+0.02%) ⬆️
test-optimization-playwright-playwright-final-status 43.94% <ø> (+0.09%) ⬆️
test-optimization-playwright-playwright-impacted-tests 43.36% <ø> (-0.06%) ⬇️
test-optimization-playwright-playwright-reporting 43.47% <ø> (+0.06%) ⬆️
test-optimization-playwright-playwright-test-management 44.93% <ø> (+0.08%) ⬆️
test-optimization-playwright-playwright-test-span 44.71% <ø> (+<0.01%) ⬆️
test-optimization-selenium 45.44% <ø> (-0.02%) ⬇️
test-optimization-testopt 46.82% <ø> (-1.38%) ⬇️
test-optimization-vitest 52.71% <ø> (+1.88%) ⬆️

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 Jun 27, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-07-02 16:48:28

Comparing candidate commit a7a0b06 in PR branch BridgeAR/2026-06-27-fastify-error-recursion with baseline commit 27dcc31 in branch master.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 2255 metrics, 31 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-appsec-enabled-24

  • unstable execution_time [-180.721ms; +177.575ms] or [-6.875%; +6.755%]

scenario:appsec-appsec-enabled-26

  • unstable execution_time [-207094.281µs; +208003.914µs] or [-8.228%; +8.264%]

scenario:appsec-appsec-enabled-with-attacks-26

  • unstable execution_time [-160908.933µs; +159687.733µs] or [-5.589%; +5.546%]

scenario:appsec-control-20

  • unstable execution_time [-162478.433µs; +161457.733µs] or [-9.302%; +9.243%]

scenario:appsec-control-24

  • unstable execution_time [-93.059ms; +109.544ms] or [-7.697%; +9.061%]

scenario:appsec-control-26

  • unstable execution_time [-112078.223µs; +111239.023µs] or [-9.283%; +9.214%]

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

  • unstable cpu_user_time [-2747.596ms; +2665.536ms] or [-32.304%; +31.340%]
  • unstable execution_time [-2746.021ms; +2700.315ms] or [-29.864%; +29.367%]
  • unstable instructions [-23019.1M instructions; +22709.8M instructions] or [-33.176%; +32.731%]
  • unstable max_rss_usage [-9735.510KB; +9230.710KB] or [-6.065%; +5.751%]
  • unstable throughput [-786.657op/s; +804.991op/s] or [-21.456%; +21.956%]

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

  • unstable cpu_user_time [-2975.823ms; +3020.942ms] or [-29.679%; +30.129%]
  • unstable execution_time [-3060.975ms; +3090.904ms] or [-28.553%; +28.832%]
  • unstable instructions [-26096.2M instructions; +26253.8M instructions] or [-31.173%; +31.361%]
  • unstable max_rss_usage [-9026.207KB; +9452.607KB] or [-5.620%; +5.886%]
  • unstable throughput [-663.566op/s; +651.885op/s] or [-21.208%; +20.835%]

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

  • unstable cpu_user_time [-2981.413ms; +2853.203ms] or [-29.947%; +28.659%]
  • unstable execution_time [-3018.477ms; +2875.880ms] or [-28.338%; +26.999%]
  • unstable instructions [-26567.1M instructions; +25709.9M instructions] or [-31.856%; +30.828%]
  • unstable max_rss_usage [-8549.277KB; +9955.677KB] or [-5.336%; +6.214%]
  • unstable throughput [-630.092op/s; +676.626op/s] or [-20.062%; +21.544%]

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

  • unstable cpu_user_time [-3.253s; +0.429s] or [-32.318%; +4.262%]
  • unstable execution_time [-3.288s; +0.436s] or [-30.553%; +4.048%]
  • unstable instructions [-29.2G instructions; +3.6G instructions] or [-34.607%; +4.221%]
  • unstable throughput [-90.562op/s; +697.746op/s] or [-2.886%; +22.239%]

scenario:dogstatsd-with-tags-20

  • unstable cpu_user_time [-302.240ms; +379.983ms] or [-6.038%; +7.591%]
  • unstable execution_time [-305.728ms; +378.548ms] or [-6.017%; +7.451%]
  • unstable throughput [-129971.856op/s; +104517.820op/s] or [-7.865%; +6.325%]

scenario:plugin-graphql-long-with-depth-and-collapse-off-20

  • unstable max_rss_usage [-16.716MB; +29.830MB] or [-4.530%; +8.085%]

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

  • unstable max_rss_usage [-59.440MB; +79.340MB] or [-25.525%; +34.071%]

scenario:test-optimization-large-suite-20

  • unstable max_rss_usage [-6.130MB; +2.816MB] or [-7.572%; +3.479%]

… hook rejections

Fastify boots through avvio, whose `_encapsulateThreeParam` re-invokes an
encapsulated hook after it throws. The same error object rides every re-drive,
and the wrapped hook republishes it on `apm:fastify:middleware:error` each time.
The in-flight boolean added in #8788 only blocks a publish nested inside another
publish; a sequential re-drive runs after the publish returned and its `finally`
cleared the flag, so every re-drive publishes again, the channel subscriber
recurses, and boot dies with `RangeError: Maximum call stack size exceeded`. A
persistent `DatadogRaspAbortError` (appsec RASP) or the boot deprecation warning
is the error that rides the loop.

1. `createErrorPublisher` keeps the boolean for nested re-entry and remembers the
   last published error. The re-drive re-throws the one caught error on every
   hop, so a single reference compare against the previous publish terminates the
   loop where the boolean cannot. This costs one comparison per publish rather
   than a per-publish set lookup, and it does not mutate the error. A distinct
   error still reaches subscribers; only a re-drive alternating two distinct
   persistent errors stays uncollapsed, which is not a shape fastify produces.
2. `invokeHookWithContext`'s async branch returned `publishError(ctx)`, i.e.
   `ctx.error`, from the `.catch` handler, which resolves the promise with the
   error and silently swallows the rejection. It now publishes and re-throws so
   the rejection keeps propagating. The synchronous branch is decoupled the same
   way: publish, then throw the original error rather than throwing the
   publisher's return value.

Fixes: #9099
Refs: #8783
@BridgeAR
BridgeAR force-pushed the BridgeAR/2026-06-27-fastify-error-recursion branch from 25aa397 to aba83d9 Compare June 27, 2026 22:38
BridgeAR added 2 commits June 28, 2026 01:07
… shared publisher

The error-keyed dedupe that bounds avvio's boot re-drive lived in the shared
`createErrorPublisher`, but koa, router, connect and restify republish the one
thrown error once per unwound middleware layer so each layer's span gets tagged
on its own publish. Keying the shared guard on the error object dropped every
publish after the first, so an outer middleware span never received its
`error.type` tag and the koa request-error spec went red on every version.

Move the `WeakSet` to fastify's own `publishError`, where the sequential
re-drive of the same error object actually happens, and revert the shared
publisher to the synchronous re-entry flag the other frameworks need.

Refs: #9099
…plit the rejection publish

The avvio re-drive re-throws the one caught error on every hop, so a reference
compare against the previously published error terminates the loop without the
allocation and per-publish lookup of a WeakSet; fastify's lifecycle never feeds
the publisher an A-B-A sequence the compare would miss.

Split the promise branch so the rejection handler only publishes: the wrapper
hands back the original promise, which keeps rejecting untouched, instead of
re-throwing from a `.catch` that returns a new promise. The publish is a side
effect, the propagation is the return value, and the two no longer share a line.

Refs: #9099
@BridgeAR
BridgeAR marked this pull request as ready for review June 28, 2026 00:30
@BridgeAR
BridgeAR requested a review from a team as a code owner June 28, 2026 00:30
@BridgeAR
BridgeAR requested review from tlhunter and removed request for a team June 28, 2026 00:30

@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: 0d544ad623

ℹ️ 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-instrumentations/src/fastify.js Outdated

@crysmags crysmags left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

one blocker, otherwise this looks good.

lastPublishedError is still keyed only on the Error object. That fixes the avvio re-drive, but it also drops a later request if the app reuses the same Error instance.

Comment thread packages/datadog-instrumentations/src/fastify.js Outdated
BridgeAR added 2 commits July 2, 2026 17:43
The last-error guard that bounds avvio's boot re-drive (#9099) was keyed on
the error object alone, so two distinct requests reusing one cached `Error`
instance collapsed to a single publish. The error channel's subscribers tag
`web.addError(req, error)` per request, so request two never reached them and
its span went untagged.

Key the guard on the error object plus its request. A re-drive of the same
error against the same request still collapses - boot hooks carry no request,
so their re-drives share the same absent request and bound the recursion - while
a distinct request reusing a cached error publishes again.

Refs: #9099
The re-drive re-throws the one caught error on the trailing hop and a request
publishes its error once, so the guard only ever compares against the single
previous publish. A pair of module-level scalars (last error, last request)
answers that with two reference compares and no allocation, dropping the
per-error WeakMap lookup and side table the previous shape carried.

Refs: #9099

@crysmags crysmags left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approved!

@BridgeAR
BridgeAR merged commit 2747b60 into master Jul 6, 2026
652 checks passed
@BridgeAR
BridgeAR deleted the BridgeAR/2026-06-27-fastify-error-recursion branch July 6, 2026 18:21
dd-octo-sts Bot pushed a commit that referenced this pull request Jul 7, 2026
…ook rejections (#9118)

Fastify boots through avvio, whose `_encapsulateThreeParam` re-invokes an
encapsulated hook after it throws, re-throwing the same error object on every
sequential re-drive. Each re-drive runs after the previous publish returned,
so the shared publisher's synchronous re-entry boolean had already reset;
every re-drive republished on `apm:fastify:middleware:error`, the channel
subscriber recursed, and boot died with `RangeError: Maximum call stack size
exceeded`.

1. `publishError` now guards on two module-level scalars - the last published
   error and its request, compared by reference - so a re-drive of the same
   error against the same request collapses to one publish. Boot hooks carry
   no request, so their re-drives share the same absent request and still
   collapse; a distinct request reusing a cached `Error` instance still
   publishes, since the subscribers tag `web.addError(req, error)` per
   request. The shared `createErrorPublisher` keeps the plain re-entry
   boolean instead, since koa, connect, restify and router each republish
   the one thrown error once per unwound middleware layer to tag a distinct
   span.
2. `invokeHookWithContext`'s async branch returned the `.catch` handler's
   promise, which resolved with the error and silently swallowed the
   rejection. It now observes the rejection to publish and returns the
   original promise unchanged, so the rejection keeps propagating; the
   synchronous branch is decoupled the same way, throwing the caught error
   instead of the publisher's return value.

Fixes: #9099
Refs: #8783
@dd-octo-sts dd-octo-sts Bot mentioned this pull request Jul 7, 2026
dd-octo-sts Bot pushed a commit that referenced this pull request Jul 7, 2026
…ook rejections (#9118)

Fastify boots through avvio, whose `_encapsulateThreeParam` re-invokes an
encapsulated hook after it throws, re-throwing the same error object on every
sequential re-drive. Each re-drive runs after the previous publish returned,
so the shared publisher's synchronous re-entry boolean had already reset;
every re-drive republished on `apm:fastify:middleware:error`, the channel
subscriber recursed, and boot died with `RangeError: Maximum call stack size
exceeded`.

1. `publishError` now guards on two module-level scalars - the last published
   error and its request, compared by reference - so a re-drive of the same
   error against the same request collapses to one publish. Boot hooks carry
   no request, so their re-drives share the same absent request and still
   collapse; a distinct request reusing a cached `Error` instance still
   publishes, since the subscribers tag `web.addError(req, error)` per
   request. The shared `createErrorPublisher` keeps the plain re-entry
   boolean instead, since koa, connect, restify and router each republish
   the one thrown error once per unwound middleware layer to tag a distinct
   span.
2. `invokeHookWithContext`'s async branch returned the `.catch` handler's
   promise, which resolved with the error and silently swallowed the
   rejection. It now observes the rejection to publish and returns the
   original promise unchanged, so the rejection keeps propagating; the
   synchronous branch is decoupled the same way, throwing the caught error
   instead of the publisher's return value.

Fixes: #9099
Refs: #8783
@dd-octo-sts dd-octo-sts Bot mentioned this pull request Jul 7, 2026
juan-fernandez pushed a commit that referenced this pull request Jul 8, 2026
…ook rejections (#9118)

Fastify boots through avvio, whose `_encapsulateThreeParam` re-invokes an
encapsulated hook after it throws, re-throwing the same error object on every
sequential re-drive. Each re-drive runs after the previous publish returned,
so the shared publisher's synchronous re-entry boolean had already reset;
every re-drive republished on `apm:fastify:middleware:error`, the channel
subscriber recursed, and boot died with `RangeError: Maximum call stack size
exceeded`.

1. `publishError` now guards on two module-level scalars - the last published
   error and its request, compared by reference - so a re-drive of the same
   error against the same request collapses to one publish. Boot hooks carry
   no request, so their re-drives share the same absent request and still
   collapse; a distinct request reusing a cached `Error` instance still
   publishes, since the subscribers tag `web.addError(req, error)` per
   request. The shared `createErrorPublisher` keeps the plain re-entry
   boolean instead, since koa, connect, restify and router each republish
   the one thrown error once per unwound middleware layer to tag a distinct
   span.
2. `invokeHookWithContext`'s async branch returned the `.catch` handler's
   promise, which resolved with the error and silently swallowed the
   rejection. It now observes the rejection to publish and returns the
   original promise unchanged, so the rejection keeps propagating; the
   synchronous branch is decoupled the same way, throwing the caught error
   instead of the publisher's return value.

Fixes: #9099
Refs: #8783
juan-fernandez pushed a commit that referenced this pull request Jul 8, 2026
…ook rejections (#9118)

Fastify boots through avvio, whose `_encapsulateThreeParam` re-invokes an
encapsulated hook after it throws, re-throwing the same error object on every
sequential re-drive. Each re-drive runs after the previous publish returned,
so the shared publisher's synchronous re-entry boolean had already reset;
every re-drive republished on `apm:fastify:middleware:error`, the channel
subscriber recursed, and boot died with `RangeError: Maximum call stack size
exceeded`.

1. `publishError` now guards on two module-level scalars - the last published
   error and its request, compared by reference - so a re-drive of the same
   error against the same request collapses to one publish. Boot hooks carry
   no request, so their re-drives share the same absent request and still
   collapse; a distinct request reusing a cached `Error` instance still
   publishes, since the subscribers tag `web.addError(req, error)` per
   request. The shared `createErrorPublisher` keeps the plain re-entry
   boolean instead, since koa, connect, restify and router each republish
   the one thrown error once per unwound middleware layer to tag a distinct
   span.
2. `invokeHookWithContext`'s async branch returned the `.catch` handler's
   promise, which resolved with the error and silently swallowed the
   rejection. It now observes the rejection to publish and returns the
   original promise unchanged, so the rejection keeps propagating; the
   synchronous branch is decoupled the same way, throwing the caught error
   instead of the publisher's return value.

Fixes: #9099
Refs: #8783
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.

[BUG]: Infinite recursion in Fastify instrumentation with fastify-plugin 6.0.0

2 participants