Repository navigation
fix(tracing): emit instrumentation lifecycle spans like Next.js 16.4 - #4913
james-elicx wants to merge 5 commits into
Conversation
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.
|
/bigbonk review for issues |
@vinext/cloudflare
create-vinext-app
@vinext/types
vinext
@cloudflare/workers-response-store
commit: |
|
Review: 3 findings.
|
|
Performance benchmarksCompared 0 improved · 0 regressed · 7 within ±1.5%
View detailed results and traces 🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head |
…led instrumentation imports
|
Addressed in fe6f750:
Declined:
|
|
/bigbonk review for issues |
| traceInstrumentationLifecycleSpan( | ||
| "Instrumentation.register", | ||
| "register instrumentation", | ||
| { startTime, endTime: getInstrumentationTimestamp() }, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Review: 1 findings. Posted 1 actionable inline finding. |
|
/bigbonk review for issues |
| // of the timed registration. | ||
| extendTracerProviderForCacheComponents(); | ||
| } catch (err) { | ||
| error = err; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Review: 1 findings. Posted 1 actionable inline finding. Targeted tracing tests pass. |
|
/bigbonk review for issues |
| * 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
|
Review: 1 findings. Posted 1 actionable inline finding. Targeted tracing tests pass. |
|
/bigbonk review for issues |
|
LGTM! |
There was a problem hiding this comment.
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
finallyblock, that error replaces the user's originalregister()error. - In the no-
register()branch, it fires beforeonRequestErroris stored and beforestate.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:
endTimeis 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 noregister(), 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( |
There was a problem hiding this comment.
ℹ️ 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.
There was a problem hiding this comment.
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.
|
clanky review |
There was a problem hiding this comment.
✅ 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.
traceInstrumentationLifecycleSpannow 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
finallyblock, the branch with noregister(), and the failed-import path. - So a throwing integration can't replace the error from
register(). It also can't skip storingonRequestErroror 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:
endTimeis read before either span is emitted.- Both spans are emitted as roots in a detached context.
- The backdated times reach OpenTelemetry through
startActiveSpanandspan.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
What
Next.js 16.4 traces the
instrumentation.tslifecycle 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 failingregister()is recorded on its span. Withoutregister(), only the load span is emitted.next startregisters at startup, outside any request, so both spans are roots. vinext emitted neither.This PR:
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, matchingnext start's shape, and are emitted once per isolate/process.startTime/endTime. The OpenTelemetry integration passes them tostartActiveSpanandspan.end(). The Workers tracing integration doesn't accept timestamps and ignores them.runInstrumentation()imports the module itself, so the load span covers that import.instrumentation.tsstatically. 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.tson Next.js v16.4.6, from run 45649241516: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:register()returns, with the given timings;register().tests/framework-tracer.test.ts: backdated times reach the registered OTel provider.All fail with
packages/vinext/src/serverrestored frommainand pass with this change.