fix(nextjs): Make request data available to tracesSampler for edge middleware root spans#22232
fix(nextjs): Make request data available to tracesSampler for edge middleware root spans#22232s1gr1d wants to merge 1 commit into
tracesSampler for edge middleware root spans#22232Conversation
…middleware root spans
| if (isolationScope.getScopeData().sdkProcessingMetadata?.normalizedRequest) { | ||
| return; | ||
| } |
There was a problem hiding this comment.
Bug: In warm serverless environments, stale normalizedRequest data from a previous request can be reused because the global default isolation scope is not reset between requests.
Severity: MEDIUM
Suggested Fix
The global default isolation scope should be cleared or reset at the beginning of each request in serverless environments. This ensures that buildContextWithSentryScopes starts with a clean scope and does not reuse stale data from previous invocations in the same warm worker.
Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.
Location: packages/nextjs/src/edge/index.ts#L110-L112
Potential issue: In warm serverless environments like Vercel Edge or Cloudflare Workers,
the module-level singleton from `getDefaultIsolationScope()` is not reset between
requests. This causes stale `normalizedRequest` data from a previous request to persist.
When a subsequent request is processed, the `beforeSampling` hook incorrectly finds
existing `normalizedRequest` data and exits early. As a result, the sampler uses the
stale data from the first request to make a sampling decision for the second request,
potentially leading to incorrect sampling.
Did we get this right? 👍 / 👎 to inform future reviews.
chargome
left a comment
There was a problem hiding this comment.
Can we add one (unskipped) test case to verify the intent of this pr works correctly e2e in a non-cf scenario?
|
👋 @mydea, @nicohrubec — Please review this PR when you get a chance! |
On the edge runtime, Next.js's OTel instrumentation creates and samples the
Middleware.executeroot span before the Sentry middleware wrapper runs. SonormalizedRequestwas never on the isolation scope at sampling time, and tracesSampler received undefined.This adds a
beforeSamplinghook in the edge SDK which populatesnormalizedRequest(method, URL, query string) based on HTTP span attributes. It also extends the edgespanStarthandler to fork the isolation scope forMiddleware.executeroot spans (similar to what #22013 did on the Node side after vercel/next.js#95357 made middleware a detached root span).The isolation-scope fork is extracted into a shared
maybeForkIsolationScopeForRootSpanutility used by both the Node and edge handlers.Fixes #22200