Skip to content

Nest middleware-triggered instrumentation spans in the middleware span - #100392

Merged
mischnic merged 2 commits into
fleet/otel-instrumentation-spans-under-requestfrom
fleet/otel-instrumentation-spans-under-middleware
Oct 21, 2026
Merged

mischnic merged 2 commits into
fleet/otel-instrumentation-spans-under-requestfrom
fleet/otel-instrumentation-spans-under-middleware

Conversation

@sokra

@sokra sokra commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Top of a stack: #100349 → #100294 → #100324 → #100350 → this PR.

When a Node.js middleware entrypoint triggers registering instrumentation.ts, #100350 emits the lifecycle spans as siblings of middleware GET. This PR nests them inside the middleware span instead, since the middleware triggered registration:

route / page entrypoint (unchanged):
 [P →] GET /page (BaseServer.handleRequest, backdated to cover registration)
        ├─ load instrumentation module
        ├─ register instrumentation
        └─ prepare route module → render …

Node.js middleware entrypoint, no parent:
 GET (Next.request, backdated)
  ├─ middleware GET
  │   ├─ load instrumentation module
  │   └─ register instrumentation
  └─ GET /page

Node.js middleware entrypoint with host span / incoming traceparent P:
 P
  ├─ middleware GET
  │   ├─ load instrumentation module
  │   └─ register instrumentation
  └─ GET /page

How

  • The middleware adapter calls the deferred emitter first thing inside the Middleware.execute span, rather than right before starting it.
  • When this request triggered registration, the middleware span is backdated to the request start so it covers registration; otherwise its timing is unchanged.
  • The shared parent is still captured before entering the middleware span, so the middleware and the render stay siblings, and traceparent handling / forwarding are unchanged.

Verification

  • Collector suite: cold Node.js middleware direct entrypoints (no parent, incoming traceparent, host span) now assert the lifecycle spans are children of the middleware span, with the middleware span starting no later than them and no earlier than its parent. Fail-first: these 3 tests fail on Emit instrumentation lifecycle spans in the request that registered it #100350.
  • Deploy-capable test/e2e/app-dir/otel-middleware-trace: the deployed span tree snapshots now show the Node.js middleware's lifecycle spans under middleware GET. Self-hosted startup spans remain roots.

@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Tests Passed

Commit: 1cb6df2

@sokra
sokra added this pull request to stack #100351 October 19, 2026 13:05
@sokra
sokra requested a review from mischnic October 19, 2026 13:08
@mischnic
mischnic force-pushed the fleet/otel-instrumentation-spans-under-middleware branch from 10587f2 to 7ae701d Compare October 19, 2026 15:21
@sokra
sokra force-pushed the fleet/otel-instrumentation-spans-under-middleware branch from 7ae701d to 98c5720 Compare October 20, 2026 10:51
@sokra
sokra force-pushed the fleet/otel-instrumentation-spans-under-middleware branch from 98c5720 to 3436363 Compare October 20, 2026 11:20
@sokra
sokra force-pushed the fleet/otel-instrumentation-spans-under-middleware branch from 3436363 to 3aee2c0 Compare October 20, 2026 13:36
@sokra
sokra force-pushed the fleet/otel-instrumentation-spans-under-middleware branch from 3aee2c0 to 0388e33 Compare October 20, 2026 14:05
@sokra
sokra force-pushed the fleet/otel-instrumentation-spans-under-middleware branch from 0388e33 to d0c403d Compare October 20, 2026 16:13
@sokra
sokra force-pushed the fleet/otel-instrumentation-spans-under-middleware branch from d0c403d to 15b1874 Compare October 20, 2026 16:36
@sokra
sokra force-pushed the fleet/otel-instrumentation-spans-under-middleware branch 2 times, most recently from f231d07 to 3512ce5 Compare October 21, 2026 12:58
@github-actions github-actions Bot added the Documentation Related to Next.js' official documentation. label Oct 21, 2026
@sokra
sokra force-pushed the fleet/otel-instrumentation-spans-under-middleware branch from 3512ce5 to 96ec911 Compare October 21, 2026 13:00
@sokra
sokra force-pushed the fleet/otel-instrumentation-spans-under-middleware branch from 96ec911 to c89e6c5 Compare October 21, 2026 13:33

sokra commented Oct 21, 2026

Copy link
Copy Markdown
Member Author

Reviewed c89e6c5

@sokra
sokra marked this pull request as ready for review October 21, 2026 14:55
vercel-fleet-prod Bot and others added 2 commits October 21, 2026 15:10
When a Node.js middleware entrypoint registers instrumentation.ts, emit
the lifecycle spans inside the middleware span and backdate it to cover
registration. The middleware and render stay siblings.

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-instrumentation-spans-under-middleware branch from c89e6c5 to 1cb6df2 Compare October 21, 2026 15:10
@mischnic
mischnic merged commit 1cb6df2 into canary Oct 21, 2026
120 checks passed
@mischnic
mischnic deleted the fleet/otel-instrumentation-spans-under-middleware branch October 21, 2026 17:25
mischnic added a commit that referenced this pull request Oct 21, 2026
## Summary

Bottom of a stack: this PR → #100294 → #100324 → #100350 → #100392.

In direct entrypoints (Vercel, adapters, standalone handlers, i.e.
without next-server), `prepare route module` ran before the request span
started. Since 16.4 every request therefore produced an extra parentless
`prepare route module` trace next to the request trace. Now it is part
of the request span:

```
[P →] GET /page (BaseServer.handleRequest)
       └─ prepare route module → render …
```

### How

- New `RouteModule.traceRequest` (`@internal`, kept out of the published
declaration types) starts the request span **before** `prepare`. It uses
the caller's tracer. When the handler is wrapped by next-server, which
already started the request span, it runs inside that active span
instead.
- Callers first await the new `RouteModule.ensureInstrumentation`
(`@internal`), split out of `prepareImpl`: it registers
`instrumentation.ts`, which usually installs the tracer provider, so a
span started earlier would not be recorded. `prepareImpl` still calls
it, and patches `res.setHeader` as before.
- The app-page, app-route, pages and pages-api templates/handlers call
`ensureInstrumentation` and then `traceRequest`, and handle the response
through one code path: `traceRequest` passes the request span and the
request's root span (the span that was active when the handler was
invoked — next-server's request span or a platform/host span — or the
request span itself), and the route name is propagated to the root span
when it isn't the request span.
- Parenting of the request span itself (incoming `traceparent`, host
span, root) is unchanged.

## Verification

- Collector suite `test/e2e/opentelemetry/instrumentation`: direct
entrypoint cold and warm requests for all four handler types, with and
without an incoming `traceparent` and with a host span, assert
`RouteModule.prepare` is inside the request's trace, and route names on
the request and parent spans.
- New deploy-capable e2e suite `test/e2e/app-dir/otel-middleware-trace`
(moved down from #100294): `proxy.ts` and Edge `middleware.ts` variants,
plus a custom server with a host span. The app records its spans with a
SpanProcessor; the middleware and the render report the spans they can
see, and the test asserts the stitched span tree (with `http.target`,
`http.route`, `next.route` and `http.status_code` where set at report
time) in inline snapshots for pages, route handlers, rewrites,
redirects, direct responses, matcher misses, incoming `traceparent`,
header overrides and a middleware-set `traceparent`, in dev, start,
Cache Components and deploy. Here it records the current behavior
(middleware and render in separate traces); #100294 shows the change.
- Unit tests for the tracer changes (`tracer.test.ts`).

<!-- 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: Niklas Mischkulnig <[email protected]>
Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
mischnic added a commit that referenced this pull request Oct 21, 2026
#100350)

## Summary

Stacked on #100324. Includes the commits from #100392, which were folded
into this PR.

Next.js emits two lifecycle spans for `instrumentation.ts` in the
Node.js runtime: `load instrumentation module` and `register
instrumentation`. They're backdated, because they're emitted after
`register()` returns (`register()` usually installs the tracer
provider). Until now they were always separate root traces.

Direct entrypoints (Vercel, adapters, standalone handlers) register
instrumentation lazily, in the first request. That split the first
request's work across extra traces. Now the spans join the trace of the
request that triggered registration:

```
route / page entrypoint:
 [P →] GET /page (BaseServer.handleRequest, backdated to cover registration)
        ├─ load instrumentation module
        ├─ register instrumentation
        └─ prepare route module → render …

Node.js middleware entrypoint, no parent:
 GET (Next.request, backdated)
  ├─ middleware GET (backdated to cover registration)
  │   ├─ load instrumentation module
  │   └─ register instrumentation
  └─ GET /page

Node.js middleware entrypoint with host span / incoming traceparent P:
 P
  ├─ middleware GET (backdated to cover registration)
  │   ├─ load instrumentation module
  │   └─ register instrumentation
  └─ GET /page
```

### How

- `ensureInstrumentationRegisteredWithDeferredSpans`: when this call
starts registration and registration succeeds, the lifecycle spans are
recorded instead of emitted. The function returns an idempotent emitter
to that caller only. Concurrent callers, later callers and startup
callers get nothing.
- `RouteModule.ensureInstrumentation(req, { deferSpans: true })` is
called by the templates before `traceRequest`. It records when the
request started and returns that time, together with the emitter, as
`instrumentation`. `traceRequest` takes it as an option, backdates the
request span to that time, and emits the lifecycle spans as the span's
first children.
- The Node.js middleware template passes the emitter and the start time
to the adapter. The adapter calls the emitter first thing inside the
`Middleware.execute` span and backdates that span to the request start.
- The shared parent (incoming `traceparent`, host span, or the backdated
inserted `Next.request` root) is still captured before entering the
middleware span. The middleware and the render stay siblings, and
`traceparent` handling and forwarding are unchanged.
- Unchanged:
  - `next start` / `next dev` startup registration (separate roots).
- Registration errors: emitted immediately with the same statuses,
including non-`Error` throws.
  - Edge (no lifecycle spans).
  - No `instrumentation.ts`, or no `register` export.
- User-created spans in `instrumentation.ts` are out of scope (see
#100324).

## Verification

- Collector suite, cold direct entrypoints:
- Route/page requests, with and without an incoming `traceparent`, and
with a host span.
- Node.js middleware requests: no parent, incoming `traceparent`, host
span.
- Each test asserts exactly one load span and one register span in the
request's trace, parented as shown above and covered by the backdated
parent. For middleware, the parent is the middleware span, and it starts
no later than the lifecycle spans and no earlier than its own parent.
- Direct-entrypoint single-trace assertions no longer exclude lifecycle
spans as startup work. Under `next start`, startup spans stay roots.
Fail-first verified.
- Deploy-capable `test/e2e/app-dir/otel-middleware-trace`: span tree
snapshots of the lifecycle spans with their ancestors, plus the first
request's tree including them.
- Deployed: children of the request span that triggered registration, or
of `middleware GET` for Node.js middleware.
  - `next dev` / `next start`: startup roots.
  - No deploy gate.
- Unit tests for the deferral helper: once-only, concurrency, startup
ownership, no `register`, `register()` errors (including `throw
undefined`), and module-load failure.

<!-- 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]>
mischnic pushed a commit that referenced this pull request Oct 21, 2026
## Summary

Bottom of a stack: this PR → #100294 → #100324 → #100350 → #100392.

In direct entrypoints (Vercel, adapters, standalone handlers, i.e.
without next-server), `prepare route module` ran before the request span
started. Since 16.4 every request therefore produced an extra parentless
`prepare route module` trace next to the request trace. Now it is part
of the request span:

```
[P →] GET /page (BaseServer.handleRequest)
       └─ prepare route module → render …
```

### How

- New `RouteModule.traceRequest` (`@internal`, kept out of the published
declaration types) starts the request span **before** `prepare`. It uses
the caller's tracer. When the handler is wrapped by next-server, which
already started the request span, it runs inside that active span
instead.
- Callers first await the new `RouteModule.ensureInstrumentation`
(`@internal`), split out of `prepareImpl`: it registers
`instrumentation.ts`, which usually installs the tracer provider, so a
span started earlier would not be recorded. `prepareImpl` still calls
it, and patches `res.setHeader` as before.
- The app-page, app-route, pages and pages-api templates/handlers call
`ensureInstrumentation` and then `traceRequest`, and handle the response
through one code path: `traceRequest` passes the request span and the
request's root span (the span that was active when the handler was
invoked — next-server's request span or a platform/host span — or the
request span itself), and the route name is propagated to the root span
when it isn't the request span.
- Parenting of the request span itself (incoming `traceparent`, host
span, root) is unchanged.

## Verification

- Collector suite `test/e2e/opentelemetry/instrumentation`: direct
entrypoint cold and warm requests for all four handler types, with and
without an incoming `traceparent` and with a host span, assert
`RouteModule.prepare` is inside the request's trace, and route names on
the request and parent spans.
- New deploy-capable e2e suite `test/e2e/app-dir/otel-middleware-trace`
(moved down from #100294): `proxy.ts` and Edge `middleware.ts` variants,
plus a custom server with a host span. The app records its spans with a
SpanProcessor; the middleware and the render report the spans they can
see, and the test asserts the stitched span tree (with `http.target`,
`http.route`, `next.route` and `http.status_code` where set at report
time) in inline snapshots for pages, route handlers, rewrites,
redirects, direct responses, matcher misses, incoming `traceparent`,
header overrides and a middleware-set `traceparent`, in dev, start,
Cache Components and deploy. Here it records the current behavior
(middleware and render in separate traces); #100294 shows the change.
- Unit tests for the tracer changes (`tracer.test.ts`).

<!-- 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: Niklas Mischkulnig <[email protected]>
Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: Luke Sandberg <[email protected]>
(cherry picked from commit e3c2f63)

Co-authored-by: Tobias Koppers <[email protected]>
mischnic pushed a commit that referenced this pull request Oct 21, 2026
#100350)

## Summary

Stacked on #100324. Includes the commits from #100392, which were folded
into this PR.

Next.js emits two lifecycle spans for `instrumentation.ts` in the
Node.js runtime: `load instrumentation module` and `register
instrumentation`. They're backdated, because they're emitted after
`register()` returns (`register()` usually installs the tracer
provider). Until now they were always separate root traces.

Direct entrypoints (Vercel, adapters, standalone handlers) register
instrumentation lazily, in the first request. That split the first
request's work across extra traces. Now the spans join the trace of the
request that triggered registration:

```
route / page entrypoint:
 [P →] GET /page (BaseServer.handleRequest, backdated to cover registration)
        ├─ load instrumentation module
        ├─ register instrumentation
        └─ prepare route module → render …

Node.js middleware entrypoint, no parent:
 GET (Next.request, backdated)
  ├─ middleware GET (backdated to cover registration)
  │   ├─ load instrumentation module
  │   └─ register instrumentation
  └─ GET /page

Node.js middleware entrypoint with host span / incoming traceparent P:
 P
  ├─ middleware GET (backdated to cover registration)
  │   ├─ load instrumentation module
  │   └─ register instrumentation
  └─ GET /page
```

### How

- `ensureInstrumentationRegisteredWithDeferredSpans`: when this call
starts registration and registration succeeds, the lifecycle spans are
recorded instead of emitted. The function returns an idempotent emitter
to that caller only. Concurrent callers, later callers and startup
callers get nothing.
- `RouteModule.ensureInstrumentation(req, { deferSpans: true })` is
called by the templates before `traceRequest`. It records when the
request started and returns that time, together with the emitter, as
`instrumentation`. `traceRequest` takes it as an option, backdates the
request span to that time, and emits the lifecycle spans as the span's
first children.
- The Node.js middleware template passes the emitter and the start time
to the adapter. The adapter calls the emitter first thing inside the
`Middleware.execute` span and backdates that span to the request start.
- The shared parent (incoming `traceparent`, host span, or the backdated
inserted `Next.request` root) is still captured before entering the
middleware span. The middleware and the render stay siblings, and
`traceparent` handling and forwarding are unchanged.
- Unchanged:
  - `next start` / `next dev` startup registration (separate roots).
- Registration errors: emitted immediately with the same statuses,
including non-`Error` throws.
  - Edge (no lifecycle spans).
  - No `instrumentation.ts`, or no `register` export.
- User-created spans in `instrumentation.ts` are out of scope (see
#100324).

## Verification

- Collector suite, cold direct entrypoints:
- Route/page requests, with and without an incoming `traceparent`, and
with a host span.
- Node.js middleware requests: no parent, incoming `traceparent`, host
span.
- Each test asserts exactly one load span and one register span in the
request's trace, parented as shown above and covered by the backdated
parent. For middleware, the parent is the middleware span, and it starts
no later than the lifecycle spans and no earlier than its own parent.
- Direct-entrypoint single-trace assertions no longer exclude lifecycle
spans as startup work. Under `next start`, startup spans stay roots.
Fail-first verified.
- Deploy-capable `test/e2e/app-dir/otel-middleware-trace`: span tree
snapshots of the lifecycle spans with their ancestors, plus the first
request's tree including them.
- Deployed: children of the request span that triggered registration, or
of `middleware GET` for Node.js middleware.
  - `next dev` / `next start`: startup roots.
  - No deploy gate.
- Unit tests for the deferral helper: once-only, concurrency, startup
ownership, no `register`, `register()` errors (including `throw
undefined`), and module-load failure.

<!-- 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]>
(cherry picked from commit 65675c3)

Co-authored-by: Tobias Koppers <[email protected]>
@github-actions github-actions Bot added the locked label Nov 5, 2026
@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Nov 5, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants