Skip to content

fix(tracing): emit instrumentation lifecycle spans like Next.js 16.4 - #4913

Open
james-elicx wants to merge 5 commits into
mainfrom
fix/otel-instrumentation-spans
Open

james-elicx wants to merge 5 commits into
mainfrom
fix/otel-instrumentation-spans

Conversation

@james-elicx

Copy link
Copy Markdown
Member

What

Next.js 16.4 traces the instrumentation.ts lifecycle with two spans. Source: server/lib/router-utils/instrumentation-globals.external.ts.

  • load instrumentation module (Instrumentation.loadModule)
  • register instrumentation (Instrumentation.register)

register() usually installs the tracer provider, so Next records the timings and emits both spans after it returns, backdated. A failing register() is recorded on its span. Without register(), only the load span is emitted. next start registers at startup, outside any request, so both spans are roots. vinext emitted neither.

This PR:

  • Emit the spans. ensureInstrumentationRegistered() emits the two spans once registration finishes. That's the shared helper behind the App and Pages server entries, the Workers entry and the dev runner. The spans go in a detached (root) context, matching next start's shape, and are emitted once per isolate/process.
  • Backdated spans. Framework span descriptors take optional startTime/endTime. The OpenTelemetry integration passes them to startActiveSpan and span.end(). The Workers tracing integration doesn't accept timestamps and ignores them.
  • Load timing.
    • Dev: runInstrumentation() imports the module itself, so the load span covers that import.
    • Generated server entries import instrumentation.ts statically. It's evaluated with the entry, so there is no separate load step to time, and the load span is zero-length, placed where registration starts. On Workers, time doesn't advance during startup anyway.

Request paths are unchanged: the spans are emitted once, at registration.

Deploy suite

test/e2e/app-dir/otel-middleware-trace/otel-middleware-trace.test.ts on Next.js v16.4.6, from run 45649241516:

  • Baseline (CI): 24 failed.
  • This branch alone (local deploy-suite run): 2 fail → pass, 0 pass → fail. Now passing: traces instrumentation registration in the triggering request (proxy and edge-middleware variants).

#4912 independently fixes 8 more. The suite doesn't exist in 16.2.6.

Tests

  • tests/instrumentation-tracing.test.ts:
    • spans emitted as roots only after register() returns, with the given timings;
    • error recorded on the register span;
    • load span only without register().
  • tests/framework-tracer.test.ts: backdated times reach the registered OTel provider.

All fail with packages/vinext/src/server restored from main and pass with this change.

Next.js 16.4 traces loading instrumentation.ts (Instrumentation.loadModule)
and running its register() (Instrumentation.register), emitting both after
register() returns with their original timestamps, since register() usually
installs the tracer provider. next start registers at startup, so they are
roots. vinext emitted neither. Emit them once registration finishes, outside
of the triggering request's trace, and let framework spans carry backdated
start and end times.
@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head eb761a8fd50a60de13c8a15d3a5d873e967b916f without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@vinext/cloudflare

npm i https://pkg.pr.new/@vinext/cloudflare@4913

create-vinext-app

npm i https://pkg.pr.new/create-vinext-app@4913

@vinext/types

npm i https://pkg.pr.new/@vinext/types@4913

vinext

npm i https://pkg.pr.new/vinext@4913

@cloudflare/workers-response-store

npm i https://pkg.pr.new/@cloudflare/workers-response-store@4913

commit: aa7487c

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 3 findings.

  • Warning packages/vinext/src/server/instrumentation-runtime.ts:57: Cloudflare registration occurs before traceFrameworkRequest, but spans are forcibly detached. Next.js adapter deployments defer them into the triggering request span. Vinext therefore emits incorrect root OTel spans, while Workers tracing may still parent them because it cannot detach.
  • Warning packages/vinext/src/server/instrumentation-runtime.ts:143: The register span ends before extendTracerProviderForCacheComponents() runs. Next.js includes its equivalent extension inside the timed operation, so vinext omits its duration and reports success if the extension subsequently throws.
  • Warning packages/vinext/src/server/instrumentation.ts:166: A rejected runner.import() emits no failed Instrumentation.loadModule span. Next.js records and emits the load failure when a provider is available; wrap the import, record its error, and trace before rethrowing.

github run

@github-actions

Copy link
Copy Markdown
Contributor
Example Preview Production Original
app-router-cloudflare preview production
pages-router-cloudflare preview production
app-router-playground preview production original
realworld-api-rest preview production
nextra-docs-template preview production
benchmarks preview production
hackernews preview production original
response-store-demo preview production
workers-cache preview production
kv preview production
static-assets-cache preview production
static-assets-pages preview production
static-assets-pages-i18n preview production
static-export preview production
web preview production

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Performance benchmarks

Compared aa7487c against base 219c880 using alternating same-runner rounds. Next.js was unchanged and skipped.

0 improved · 0 regressed · 7 within ±1.5%

Scenario Framework Baseline Current Change
Client bundle size (gzip) vinext 157.3 KB 157.3 KB ⚫ 0.0%
Client entry size (gzip) vinext 145.5 KB 145.5 KB ⚫ 0.0%
Dev server cold start vinext 3.07 s 3.03 s ⚫ -1.2%
Dev server cold start (large Pages Router app) vinext 25.76 s 26.02 s ⚫ +1.0%
Production build time vinext 3.95 s 3.97 s ⚫ +0.5%
RSC entry closure size (gzip) vinext 150.6 KB 150.6 KB ⚫ +0.0%
Server bundle size (gzip) vinext 262.8 KB 262.9 KB ⚫ +0.0%

View detailed results and traces

🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head

@james-elicx

Copy link
Copy Markdown
Member Author

Addressed in fe6f750:

  • Register span ends before extendTracerProviderForCacheComponents(): fixed. The extension now runs inside the timed register() step, like Next's afterRegistration(), so its duration and any error land on the Instrumentation.register span. Covered by "times the tracer provider extension as part of register()".
  • Rejected runner.import() emits no load span: fixed. runInstrumentation now emits a failed Instrumentation.loadModule span, then rethrows. As in Next, it is only exported when a provider is already installed. Covered by "emits a failed load span when importing the module throws".

Declined:

  • Spans are forcibly detached on Cloudflare: the detached roots are intentional and follow the test this PR ports. In otel-middleware-trace.test.ts, "traces instrumentation registration in the triggering request" expects deferred children only for adapter deploys (isNextDeploy && !isNonAdapterDeploy). For next start, next dev and "the render of a deployment without the adapter (observed in the release deploy tests)", it expects two root spans. vinext's Workers deploy runs that non-adapter snapshot. With this PR it passes in both variants, and parenting under the request span would fail it. Next's deferral (ensureInstrumentationRegisteredWithDeferredSpans) exists only in the adapter entrypoints (route-module.ts, build/templates/middleware.ts).

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head fe6f750d1b64b827e492c53bb69693952000467a without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

traceInstrumentationLifecycleSpan(
"Instrumentation.register",
"register instrumentation",
{ startTime, endTime: getInstrumentationTimestamp() },

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.

Capture endTime before emitting either lifecycle span. traceInstrumentationLifecycleSpan() synchronously reaches OTel span.end(), whose span processors run synchronously, so the current timestamp includes load-span processing/export latency in the Instrumentation.register duration. Next.js samples endTime first and only then emits both backdated spans.

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.

Fixed in bcb8013. endTime is now read when register() settles, before either lifecycle span is emitted, as in Next's registerInstrumentation. Covered by "ends the register span before emitting the lifecycle spans", where exporting the load span advances the clock.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 1 findings.

Posted 1 actionable inline finding.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head bcb8013d372f6a7df5e6059796314ccef10ab809 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

// of the timed registration.
extendTracerProviderForCacheComponents();
} catch (err) {
error = err;

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.

Prefix Error messages before recording and rethrowing them, as Next.js 16.4 does (An error occurred while loading instrumentation hook: ...). This PR newly emits the register failure span, but currently records the raw message as both the exception and span status, so its telemetry differs from Next; the test at tests/instrumentation-tracing.test.ts:116 also codifies the unprefixed value.

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.

Fixed in 41c1680. A thrown Error now gets Next's An error occurred while loading instrumentation hook: prefix, as in registerInstrumentation (16.2.6 and 16.4.6). The prefix is added before the error is recorded on the register span and rethrown, and this also covers a failing tracer-provider extension, which Next runs in the same try. Both span tests now assert the prefixed status. Non-Error throws are left unchanged.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 1 findings.

Posted 1 actionable inline finding. Targeted tracing tests pass.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 41c1680dd285943d4c8a1373aa8aa2fe097837d3 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

* instrumentation file when Vite evaluates it in separate environments.
* @param loadTiming - When importing the module started and finished, when the
* caller imported it itself. Generated server entries import it statically,
* so it was evaluated with the entry and its load has no separate duration.

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.

The production App and Pages entries still statically import instrumentation.ts, so a top-level import failure aborts module evaluation before this helper or traceInstrumentationModuleLoadError() can run. The new failed-load span therefore exists only in the development ModuleRunner path, while Next.js catches getInstrumentationModule() failures and emits Instrumentation.loadModule when a provider is already installed. Load the generated module inside the initialization promise (preserving registration-before-user-module ordering), capture its timing/error there, and add a generated-entry failure test.

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.

Declining this one. Next only exports a failed Instrumentation.loadModule span when a tracer provider was installed before instrumentation.ts loaded ("A load error is only exportable when a provider was already installed" in registerInstrumentation). In vinext's production entries nothing runs before the entry module: instrumentation.ts is what installs the provider, and on Workers nothing can preload one. So no provider exists to export the span to. A top-level import failure also stops the worker or server module from evaluating at all, so no request is ever served. Switching the generated entries to a dynamic import would change chunking and startup for every app with instrumentation.ts, which is more than this edge case is worth, and the 16.4.6 deploy test doesn't cover it. The dev ModuleRunner path, where the import can fail on its own, does emit the span (runInstrumentation).

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 1 findings.

Posted 1 actionable inline finding. Targeted tracing tests pass.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 41c1680dd285943d4c8a1373aa8aa2fe097837d3 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

LGTM!

github run

@james-elicx
james-elicx marked this pull request as ready for review November 26, 2026 07:34

@clanky-the-clanker clanky-the-clanker 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.

Superseded by the review of aa7487cf.

This review, of 41c1680d

💬 Approved with comments — The lifecycle spans are correct and well tested. The one note is non-blocking: a tracing integration that throws while these spans are emitted could change how registration ends.

Findings: 1 info (1 is an inline comment on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 1 info

The lifecycle spans match the description. One robustness note: span emission is not guarded inside the one-shot registration path.

Recommendation: 💬 Optional Nits

  • [INFO] Lifecycle span emission is not guarded inside the one-shot registration path. A tracing integration that throws could hide the real register() error, or leave registration permanently rejected. (packages/vinext/src/server/instrumentation-runtime.ts:179)
View full review

Span emission now runs inside ensureInstrumentationRegistered(), in the finally block and in the branch with no register(). frameworkTracer.trace does not catch errors thrown by an integration's span creation or by span.end().

If one throws:

  • In the finally block, that error replaces the user's original register() error.
  • In the no-register() branch, it fires before onRequestError is stored and before state.initialized = true.

Either way, initPromise stays rejected and is never retried. The OpenTelemetry SDK normally catches span-processor errors itself, so this is unlikely in practice. A try/catch inside traceInstrumentationLifecycleSpan would keep telemetry failures from changing how registration ends.

The rest holds up:

  • endTime is read before either span is emitted.
  • Both spans are emitted in a detached root context.
  • The backdated times reach the OpenTelemetry integration.
  • The new tests cover the success path, a failing register(), the case with no register(), the extension running inside the timed step, and a failing dev import.

✅ All other checks passed

🔒 Security: ✅ LGTM

No security issues found.

  • Span timestamps come only from the process clock.
  • Spans are emitted once per isolate or process, inside the registration guard, so requests cannot multiply them.
  • A failed registration still rethrows, so it does not fail open.

📖 AGENTS.md: ✅ LGTM

These tracing changes do not need an AGENTS.md update.


⚡ Performance: ✅ LGTM

No performance issues. The spans are emitted once, at registration, and request paths are unchanged.


📝 Documentation: ✅ LGTM

No documentation issues in the changed files.


Reviewed commit: 41c1680d

} finally {
// Before emitting: span processors run synchronously in span.end().
const endTime = getInstrumentationTimestamp();
traceInstrumentationLifecycleSpan(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ℹ️ INFO · Code Quality

Lifecycle span emission is not guarded inside the one-shot registration path. A tracing integration that throws could hide the real register() error, or leave registration permanently rejected.

traceInstrumentationLifecycleSpan is now called from this finally block and from the branch with no register() (line 192). frameworkTracer.trace doesn't catch errors from an integration's span creation or span.end(). If one throws here, it replaces the user's register() error. In the no-register() branch it fires before onRequestError is stored and state.initialized is set, so initPromise stays rejected and every later request fails. The OpenTelemetry SDK usually catches processor errors itself, so this is unlikely, but wrapping the body of traceInstrumentationLifecycleSpan in a try/catch would keep telemetry failures from changing how registration ends.

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.

Fixed in aa7487c. traceInstrumentationLifecycleSpan now catches and logs any error from the tracing integration, so telemetry can't replace register()'s own error or leave the one-shot registration rejected. Covered by "keeps a throwing tracing integration from changing how registration ends": the register error still propagates unchanged, and registration without register() still completes and stores onRequestError.

@james-elicx

Copy link
Copy Markdown
Member Author

clanky review

@clanky-the-clanker clanky-the-clanker 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.

✅ Approved — No findings. The lifecycle spans now match Next.js 16.4, and the earlier note is fixed: a throwing tracing integration can no longer change how registration ends.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security issues found. Span timestamps come only from the process clock. The spans are emitted once, inside the registration guard. A failed registration still rethrows, so it does not fail open.


📖 AGENTS.md: ✅ LGTM

These tracing changes do not need an AGENTS.md update.


📋 Code Quality: ✅ LGTM

🔄 Since last review: 1 finding resolved, 0 preserved, 0 new

The earlier note is fixed: lifecycle span emission wasn't guarded inside the one-shot registration path.

  • traceInstrumentationLifecycleSpan now wraps the detached trace in a try/catch and logs any failure from the tracing integration.
  • All three places that emit spans go through it: the finally block, the branch with no register(), and the failed-import path.
  • So a throwing integration can't replace the error from register(). It also can't skip storing onRequestError or leave registration rejected for good.
  • The new test "keeps a throwing tracing integration from changing how registration ends" covers both paths.

The rest of the change holds up:

  • endTime is read before either span is emitted.
  • Both spans are emitted as roots in a detached context.
  • The backdated times reach OpenTelemetry through startActiveSpan and span.end(endTime).

⚡ Performance: ✅ LGTM

No performance issues. The spans are emitted once, at registration, and request paths are unchanged.


📝 Documentation: ✅ LGTM

No documentation issues in the changed files.


Reviewed commit: aa7487cf

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant