Skip to content

Only emit Next.request for requests that reach a render, and make middleware the root otherwise - #100665

Draft
sokra wants to merge 10 commits into
canaryfrom
fleet/otel-deferred-next-request-span
Draft

sokra wants to merge 10 commits into
canaryfrom
fleet/otel-deferred-next-request-span

Conversation

@sokra

@sokra sokra commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

What?

When middleware runs separately from the render (e.g. when deployed) without trace context, the inserted Next.request root span is now emitted only for requests that continue to a render, and it covers the render too, instead of ending with the middleware. Direct responses, redirects, external rewrites, a user-set render traceparent and middleware errors no longer get a Next.request span: Middleware.execute is the root span instead.

Why?

adapter() inserts Next.request as the shared parent of the middleware span and the render. It wrapped only the middleware handler, so the root ended before its child, the render, even started. Its duration covered only the middleware. For requests that never continue to a render (a redirect, a direct response, an external rewrite), the extra root added nothing: Next.request should only wrap requests that are rewritten or continue with NextResponse.next().

How?

  • Middleware: reserves the root instead of starting it (reserveRequestSpan). It takes the IDs and the sampling decision from the OpenTelemetry SDK's tracer (_idGenerator, _sampler) and runs the middleware under a non-recording parent with those IDs.

    • No unended SDK root is kept. Leaving one open would retain an entry in @vercel/otel's open-root map for every request.
    • An unsampled decision is reserved too, so the sampler doesn't run again with new IDs.
  • Deferring (NextResponse.next(), same-origin rewrite): the forwarded traceparent gets a next-deferred tracestate entry.

    • The entry is the leftmost member and follows the W3C limits (32 members, 512 characters; values up to 256 characters).
    • It's versioned and holds the bound span ID, start time, method and target.
  • Not continuing (direct responses, redirects, external rewrites, a user-set traceparent, and middleware errors): the outcome is checked before the middleware span ends. The reserved root is never emitted, its context isn't forwarded, and the middleware span's SDK parent is cleared (parentSpanContext in @opentelemetry/sdk-trace 2.x, parentSpanId in sdk-trace-base 1.x), so it is exported as the root. Its span ID, attributes, events and children are unchanged. A user-set traceparent / tracestate is kept; an external origin gets no added trace-context overrides.

  • Render (withPropagatedContext, so next-server, direct entrypoints, Edge SSR and Edge functions): it accepts the entry only when all of these hold:

    • the format and version are valid;
    • the bound span ID equals the incoming parent span ID, and the trace is sampled;
    • the start time is at most 30 minutes old and at most 1 minute ahead. A time that's ahead is set to now.

    It then emits Next.request with exactly the incoming IDs once its request handling has settled, so it ends no earlier than the render's request span. A rejection sets ERROR status, and tracing failures never replace the render's result or error. The start time is the earlier of the entry's and the render's backdated request span.

  • Once per request: nested render entries emit at most once, tracked by a value in the OTel context rather than global state.

  • Confinement: the entry is removed from the carrier headers and the active or extracted context, including under a host span. Outgoing fetches and client-visible responses never carry it.

  • Fallback: without the SDK ID/sampler internals, the previous behavior is kept (a real root ends with the middleware, for every outcome). If a reserved parent can't be cleared, the middleware span keeps that unexported parent; tracing never fails the request.

Trade-offs and limitations

  • The entry isn't signed. A valid entry sent by a client is accepted, which only affects trace data.
  • Relies on SDK internals (_idGenerator, _sampler, and the started span's parent field), verified for @opentelemetry/sdk-trace 2.x / @vercel/otel 2.1.3. Parent clearing also supports the sdk-trace-base 1.x parentSpanId shape used by the collector suite.
  • Span processors see the reserved parent at onStart and a root span at onEnd. @vercel/otel exports it correctly, but a custom processor that caches ancestry at onStart could differ.
  • When no render picks the deferred entry up (a page served from cache or static without a function, a render that crashes or times out, an unsupported SDK, or a render-side sampler that drops it), no root is exported and the middleware span keeps a parent that's never exported.
  • Clocks of the middleware and render hosts can differ, so a truthful envelope badge is possible.
  • Self-hosted, next-server's middleware-invoke root still ends early, as before. Fixing it is planned separately.
  • Cost: with OTel enabled, building and parsing the entry, one sampler call and one extra span start and end for the re-created root. Nothing changes with OTel disabled.

Testing

  • Unit tests (deferred-request-span.test.ts, tracer.test.ts, forward-trace-context.test.ts, 125 passing) cover:
    • the protocol and its W3C budget;
    • reservation, including the unsampled case, and render-side emission with fixed IDs;
    • emitting once under nested and copied headers, also after many other requests;
    • stripping under host spans, error preservation, the earlier render start, same-origin detection, and same-trace detection;
    • clearing only the reserved parent for SDK 2.x and 1.x span shapes, with failures ignored.
  • otel-middleware-trace: 40 tests in all 6 local modes (start/dev × Turbopack/webpack, plus Cache Components start/dev), local snapshots unchanged. It adds an outgoing-request confinement test and a /root-state check that the middleware keeps no open root spans, which is only meaningful when deployed.
  • Collector suite (test/e2e/opentelemetry/instrumentation):
    • The direct-entrypoint middleware test asserts that Next.request covers the middleware and the render. It failed before (the root ended 379 ms before the render) and passes now.
    • New: a direct middleware response and a middleware redirect aren't wrapped in Next.request; with direct entrypoints and no trace context, the middleware span is a root span. The two root-context variants failed before this change (parentId was the reserved span) and pass now.
    • Overall: start turbo 138 passed, dev turbo 75 passed.
  • Header overrides: 9 passed. pnpm --filter=next types, pnpm typescript, ESLint and Prettier pass.
  • Local SDK probes with the real @vercel/[email protected]: a deferred root leaves 0 open-root entries; a root left open leaves 1. Nine adapter outcomes confirm root/non-root parents, forwarding, children and attributes/events: direct, redirect, external rewrite, user-set traceparent, thrown error, internal rewrite, NextResponse.next(), and incoming-trace direct/external.
  • Test recorder (otel-middleware-trace/trace-recorder.ts): it now reports the parent a span has at onEnd, which is what exporters see, instead of the parent cached at onStart. Before this, re-parented roots still showed as [remote] in the first deploy run. A local probe with the real SDK and the built adapter failed before the change and passes now. It also covers the SDK 1.x/2.x root and parent shapes.

Deploy CI: the continuing requests' deploy trees show no envelope badge on Next.request, with the render's request span and the middleware span under it. The deploy snapshots for direct responses, redirects, external rewrites and middleware-set traceparents now start with Middleware.execute. This push's deploy jobs are confirming them, with the fixed recorder.

Stack: canary → #100664 (test infrastructure) → #100690 (dev validation trace) → this PR.

@github-actions

github-actions Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Tests Passed

Commit: ba342a8
View workflow run

Comment on lines +699 to +704
const ids = reserveRootSpanIds(this.getTracerInstance(), {
context: ROOT_CONTEXT,
name,
kind: SpanKind.SERVER,
attributes: getRequestSpanAttributes(name, attributes),
})

@vercel vercel Bot Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

When a propagator extracts sampler inputs without a parent span, reservation and deferred emission discard those inputs through ROOT_CONTEXT, causing context-dependent samplers to drop request traces or omit root attributes.

Fix on Vercel

@sokra
sokra added this pull request to stack #100667 October 23, 2026 15:41
@sokra
sokra force-pushed the fleet/otel-deferred-next-request-span branch 3 times, most recently from 488e096 to b50d68b Compare October 24, 2026 06:09
@github-actions github-actions Bot added the Documentation Related to Next.js' official documentation. label Oct 24, 2026
@sokra
sokra removed this pull request from stack #100667 October 24, 2026 06:10
@sokra
sokra changed the base branch from fleet/otel-trace-console-capture to fleet/otel-dev-validation-root-span October 24, 2026 06:10
@sokra
sokra added this pull request to stack #100691 October 24, 2026 06:10
@sokra
sokra force-pushed the fleet/otel-deferred-next-request-span branch 2 times, most recently from a906306 to b240b19 Compare October 27, 2026 13:18
// spans, and nothing emits the deferred `Next.request`.
expect(tree).toMatchInlineSnapshot(`
"[trace A] GET (Next.request) {http.target=/rewrite-isr}
"[trace A] [remote]

@sokra sokra Oct 27, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is the trade-off with this approach

// spans, and nothing emits the deferred `Next.request`.
expect(tree).toMatchInlineSnapshot(`
"[trace A] GET (Next.request) {http.target=/rewrite-static}
"[trace A] [remote]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is the trade-off with this approach

@sokra sokra changed the title Defer the inserted Next.request span until the render has run Only emit the inserted Next.request span for requests that reach a render, deferred until the render has run Oct 27, 2026
@sokra
sokra force-pushed the fleet/otel-deferred-next-request-span branch from 5c8a16f to f754ffb Compare October 27, 2026 18:31
@sokra
sokra force-pushed the fleet/otel-deferred-next-request-span branch from f754ffb to e75cf00 Compare October 27, 2026 18:32
@sokra sokra changed the title Only emit the inserted Next.request span for requests that reach a render, deferred until the render has run Only emit Next.request for requests that reach a render, and make middleware the root otherwise Oct 28, 2026

@vercel vercel Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Additional findings

  1. test/e2e/app-dir/otel-middleware-trace/trace-recorder.ts:94-96 — When deployed middleware is promoted to a root, the recorder emits its cached reserved parent, adding a spurious [remote] ancestor and failing the new root-span snapshots.

    Fix on Vercel

@vercel-fleet-prod

Copy link
Copy Markdown
Contributor

Re the Vercel Agent finding on trace-recorder.ts: confirmed and fixed in 49c5fe6. The recorder cached each span's parent at onStart and preferred it at onEnd, so a middleware span the adapter made a root still printed under [remote] (the 8 deploy failures on 4dd01b8). It now reports the parent field the SDK span has at end (parentSpanContext in 2.x, parentSpanId in 1.x; present but undefined means root) and only falls back to the onStart parent for spans without either field.

@sokra
sokra force-pushed the fleet/otel-deferred-next-request-span branch from ae62e3c to a345222 Compare October 31, 2026 14:26
sokra added a commit that referenced this pull request Nov 5, 2026
…are-trace (#100664)

### What?

Test infrastructure for `test/e2e/app-dir/otel-middleware-trace`: the
fixture now writes span lifecycle events to the console, and tests
collect the **finished** spans of a request after the response, then
check that every span covers all spans below it.

### Why?

The fixture reported spans while they were still running (in an
`x-mw-spans` response header from inside the middleware, and in the page
or route body during rendering). Span timing couldn't be checked, so the
test couldn't see that the inserted `Next.request` root ends before its
render child. This is the baseline for the next PR in the stack, which
fixes that root.

### How?

- **Recorder** (`trace-recorder.ts`): a span processor writes one
`[otel-span] {json}` line per `start` and `end` event, with a unique
event ID. It works in the Node.js runtime, the Edge runtime and when
deployed.
- **Collection** (`test/lib/otel-span-capture.ts`):
- Self-hosted, it reads `next.cliOutput`. Deployed, it reads `vercel
logs --json` through a new `NextDeployInstance.getRuntimeLogs`, using a
paged reader in `test/lib/vercel-runtime-logs.ts`.
- Polls until each request's expected spans have ended, then a later
successful poll (at least the settle delay later) must find nothing new
for that request.
- Events are merged across polls; two distinct `end` events for one span
fail the test with a diagnostic.
- It fails with a diagnostic (tree so far, missing spans, poll history)
on timeout, rather than hanging or passing. A failed `vercel logs` read
is recorded and retried at the next poll; each call is capped at 60 s.
- Settling can't prove that no late log line arrives; that limitation is
documented in the helper.
- **Deployed: one collection per suite.** Each `describe` variant sends
every test's request in a `beforeAll` (in test order, so the first
request stays the cold one), then collects the spans of all of them in
one poll loop, with one unfiltered `vercel logs` read of the deployment
per poll. Each test then asserts on its own response and tree, so
failures stay per test. Self-hosted, each test still requests, collects
and asserts in turn. This replaced per-test polling, which added up the
ingestion delay and timed out late in the suite (1–3 tests per job on
the first deploy runs, including a hanging call and an API 504).
- **Diagnostics in every deployed run:** each `vercel logs` call is
logged (arguments with any token redacted, page, exit status, duration,
record count), and every captured `[otel-span]` event is printed once
with its times, so the raw data behind a tree is in the job log.
- **Envelope badges** (`printSpanTree`):
- A span gets `[error: doesn't cover descendants]` when a descendant
starts before it or ends after it, and `[error: not ended]` when it
hasn't ended.
- Times within the same millisecond count as covered, because the SDK
records times in whole milliseconds.
- `NextNodeServer.startResponse` is left out of the check, because its
timing against the render span is flaky. It's still printed.
- **Correlation:** a request's trace IDs come from an `x-mw-trace-id`
response header and the render's body. Incoming and middleware-set
`traceparent`s are new per request, so collection only sees that
request's spans.
- **Snapshots:** the snapshots now show complete trees, selected per
environment (mode, bundler, Cache Components, middleware entry).
- The only badge in the self-hosted snapshots is on next-server's
middleware-invoke root (`GET (BaseServer.handleRequest)`), which ends
before the render it is the parent of. Fixing it is out of scope here.
- The deploy snapshots are filled from complete CI trees, for both
builders (adapter and non-adapter) with and without Cache Components,
and both middleware runtimes. Their only badges are on the inserted `GET
(Next.request)` root of requests that continue to a render, which ends
before the render. The PR above fixes that. No deploy assertions are
skipped.
- **Rewrite edge cases:** three new tests trace a middleware rewrite to
an external origin (`https://example.vercel.sh`), to a static page
(`app/static`) and to an ISR page (`app/isr`, `revalidate = 3600`; with
Cache Components a `'use cache'` + `cacheLife('hours')` variant). They
assert the status, the page marker, that no internal headers leak, and
the tree. In `start`, the static and ISR pages are served from the cache
(no `render route (app)` span). The PR above shows what changes for them
deployed.
- In `dev, cache components`, the ISR tree has 2 more badges, on `GET
/isr` and `render route (app) /isr`. They come from Cache Components'
background validation, which renders again after the response, under the
render's context. #100690 (above) fixes that.
- **Span links:** the recorder also records each span's links, and
parsed spans carry them (not printed), so #100690 can assert its linked
validation root.
- No `packages/next` changes.

### Testing

The rewrite edge cases (36 tests / 34 snapshots) pass in all 6 local
modes (start/dev × turbo/webpack, Cache Components start/dev turbo).
Before the fixture changes they failed (404). Their deploy snapshots are
filled from CI. Deployed (both builders, with and without Cache
Components), all three trees are just `GET (Next.request)` with the
middleware span: the static and ISR pages are served without invoking a
function, so there are no render spans.

Earlier runs against the base framework without the PR above
(`otel-middleware-trace`, 30 tests / 28 snapshots):

| Mode | Runs |
|---|---|
| start turbo, dev turbo, start webpack | 2 each |
| Cache Components start turbo and dev turbo | 2 each |
| dev webpack | 1 |

All 11 runs passed, along with 41 unit tests
(`test/unit/otel-span-tree.test.ts`,
`test/unit/vercel-runtime-logs.test.ts`) and `pnpm typescript`. The
batch collection was also run locally by temporarily forcing it on for
self-hosted (start and dev turbo): same snapshots, including the cold
first request.

Stack: #100591 ← **this PR** ← #100690 ← #100665. Stacked on #100591, so
deploy CI runs this with both the adapter and the non-adapter builder.


<!-- fleet ce0ecb23-b14c-4679-92a9-e676130f618e -->

---------

Co-authored-by: vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>
@sokra
sokra force-pushed the fleet/otel-deferred-next-request-span branch from a345222 to 5beca6a Compare November 9, 2026 11:35
@sokra

sokra commented Nov 17, 2026

Copy link
Copy Markdown
Member Author

Would wrapSpanContext help to avoid the hacks in the code

Base automatically changed from fleet/otel-dev-validation-root-span to canary November 17, 2026 11:20
sokra added a commit that referenced this pull request Nov 17, 2026
…100690)

## What?

In `next dev` with Cache Components, the background validation of a
rendered route now runs in an OpenTelemetry trace of its own: its spans
are children of a new root span, `validate route (app) <page>`
(`next.span_type`: `AppRender.devValidation`), with a span link to the
request's `render route (app) <page>` span.

## Why?

`runDevValidationInBackground`
(`packages/next/src/server/app-render/app-render.tsx`) waits for the
response to finish, then renders the route again (`build component
tree`, `generateMetadata`, …). Those spans inherited the render's
context, so they were children of `render route (app)` and
`BaseServer.handleRequest` even though they ran after both had ended. In
`otel-middleware-trace` (#100664), that shows as 2 envelope badges on
the `dev, cache components` ISR tree.

## How?

- The render's span context is captured when the validation is
scheduled. After `waitForFinish()` (and the existing abort check), the
validation runs inside `tracer.trace(AppRenderSpan.devValidation, {
root: true, links: [render span] })`, which ends the span once the
validation settles, with an error status if it rejects. Validation
behavior and its error handling are unchanged (the diff is mostly
re-indentation).
- With Request Insights the validation already runs in an isolated local
trace, so that path is unchanged. With OpenTelemetry disabled nothing
new runs. The code path is dev only.
- The new span type is added to `NextVanillaSpanAllowlist` and
documented in the OpenTelemetry guide.

## Tests

In `otel-middleware-trace`:
- The `dev, cache components` ISR request trees no longer contain the
validation spans and lose the 2 badges they caused. The remaining root
badge is the known self-hosted middleware-invoke request span
(unchanged, out of scope).
- A new dev Cache Components assertion finds exactly one validation root
by its link to the request's render span, with no parent and in a
different trace, and snapshots its tree.

Stacked: #100591 ← #100664 ← **this PR** ← #100665.

## Verification

- `otel-middleware-trace` in `start`/`dev` × Turbopack/webpack and with
Cache Components (`start`/`dev` Turbopack): all pass. Before the fix,
the new assertion fails (no linked root).
- Temporary negative control (validation throws, not committed): the
root ends exactly once per validation, with error status.
- `test/e2e/opentelemetry/instrumentation` (`test-dev-turbo`): passes.
That suite is excluded from Cache Components runs
(`test/cache-components-tests-manifest.json`).
- Not run: a superseding-navigation abort; it settles through the same
path.
- Deployed trees are unaffected (dev only): deploy CI produced the same
trees as #100664.

<!-- NEXT_JS_LLM -->


<!-- fleet ce0ecb23-b14c-4679-92a9-e676130f618e -->

Co-authored-by: vercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>
vercel-fleet-prod Bot and others added 9 commits November 17, 2026 12:20
When middleware runs separately from the render (e.g. when deployed)
without trace context, the middleware adapter inserts a `Next.request`
root span. It used to end with the middleware, before its child (the
render) even started.

The middleware now reserves the span's IDs and sampling decision
through the OpenTelemetry SDK's tracer (`_idGenerator`, `_sampler`)
without starting it, and runs under it as a non-recording parent. When
the request continues to the app, it forwards a versioned
`next-deferred` `tracestate` entry with the `traceparent`; the render
validates it (bound span ID, sampled, start time at most 30 minutes old
and 1 minute ahead) and emits the span with exactly that span ID once
its request handling has settled. Direct responses, redirects, external
rewrites, a user-set `traceparent` and errors emit it in the middleware.

The entry is removed from carriers and contexts, so outgoing requests
never carry it, and nested render entries emit the span only once.
Without the SDK internals, the previous behavior is kept.

Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>
tracer.js now imports server/lib/trace/deferred-request-span.js, so it's traced into next-minimal-server.js.nft.json.

Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>
…e snapshots

Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>
Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>
…s parent unexported

Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>
Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>
Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>
Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>
Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>
@sokra
sokra force-pushed the fleet/otel-deferred-next-request-span branch from 5beca6a to 1117570 Compare November 17, 2026 11:20
@vercel

vercel Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Vercel Agent finished reviewing your changes.
ba342a8 • Tue, 17 Nov 2026 11:38:48 GMT

Vercel Agent found issues that need attention.

Issues (1)
packages/next/src/server/lib/trace/tracer.ts:700-705 — When a propagator extracts sampler inputs without a parent span, reservation and deferred emission discard those inputs through ROOT_CONTEXT, causing context-dependent samplers to drop request traces or omit root attributes.

Resolved issues (1)

test/e2e/app-dir/otel-middleware-trace/trace-recorder.ts:94-96 — When deployed middleware is promoted to a root, the recorder emits its cached reserved parent, adding a spurious [remote] ancestor and failing the new root-span snapshots.

Review steps (1m 26s)

Preparing the workspace 20.0s
Analyzing the changes 1m 0s
Finalizing the review 5.2s

Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
Co-authored-by: Niklas Mischkulnig <[email protected]>

This branch has not been deployed

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

Labels

created-by: Turbopack team PRs by the Turbopack team. Documentation Related to Next.js' official documentation. tests type: next

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant