Skip to content

Commit fa71595

Browse files
authored
Fix early OTel proxy tracers in Cache Components prerenders (#95317)
> [!TIP] > Best reviewed with hide whitespace. ### Why? Cache Components prerenders can fail when an OpenTelemetry tracer is acquired before provider registration and later resolves through proxy tracer delegation: ``` Next.js encountered the unstable value `Math.random()` while prerendering ``` Current behavior: https://github.com/vercel/next.js/actions/runs/28518518762/job/84536475151?pr=95317#step:32:343 ### How? Patch proxy tracer delegation to apply the same Cache Components span instrumentation used for normal tracer lookup. Closes #94753 <!-- NEXT_JS_LLM_PR -->
1 parent a7b0469 commit fa71595

5 files changed

Lines changed: 167 additions & 53 deletions

File tree

‎packages/next/src/server/lib/router-utils/instrumentation-node-extensions.ts‎

Lines changed: 86 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@
33
* This extension must only be loaded in Node environments.
44
*/
55

6-
import type { Tracer } from '@opentelemetry/api'
6+
import type {
7+
ProxyTracerProvider,
8+
Tracer,
9+
TracerProvider,
10+
} from '@opentelemetry/api'
711
import {
812
type WorkUnitStore,
913
workUnitAsyncStorage,
@@ -21,6 +25,15 @@ export function afterRegistration(): void {
2125
extendTracerProviderForCacheComponents()
2226
}
2327

28+
function isProxyTracerProvider(
29+
provider: TracerProvider
30+
): provider is ProxyTracerProvider {
31+
return (
32+
'getDelegateTracer' in provider &&
33+
typeof provider.getDelegateTracer === 'function'
34+
)
35+
}
36+
2437
// In theory we only want to enable this extension when cacheComponents is enabled
2538
// however there are certain servers that might load instrumentation before nextConfig is available
2639
// and so gating it on the config might lead to skipping this extension even when it is necessary.
@@ -49,66 +62,87 @@ function extendTracerProviderForCacheComponents(): void {
4962
// to exit the workUnitAsyncStorage context when generating spans.
5063
const originalGetTracer = provider.getTracer.bind(provider)
5164
provider.getTracer = (...args) => {
52-
const tracer = originalGetTracer.apply(provider, args)
53-
if (WeakTracers.has(tracer)) {
54-
return tracer
55-
}
56-
const originalStartSpan = tracer.startSpan
57-
tracer.startSpan = (...startSpanArgs) => {
58-
return workUnitAsyncStorage.exit(() =>
59-
originalStartSpan.apply(tracer, startSpanArgs)
60-
)
65+
return instrumentTracerForCacheComponents(
66+
originalGetTracer.apply(provider, args)
67+
)
68+
}
69+
70+
// Tracers acquired before registration can use getDelegateTracer() from the
71+
// proxy provider to get a tracer from the registered provider, bypassing the
72+
// getTracer() patch above. This can be problematic when third-party
73+
// instrumentation creates spans that call dynamic APIs like Math.random(),
74+
// causing a prerendering error. Therefore, patch getDelegateTracer() to apply
75+
// the same tracer instrumentation as getTracer().
76+
if (isProxyTracerProvider(provider)) {
77+
const originalGetDelegateTracer = provider.getDelegateTracer.bind(provider)
78+
provider.getDelegateTracer = (...args) => {
79+
const tracer = originalGetDelegateTracer(...args)
80+
return tracer === undefined
81+
? undefined
82+
: instrumentTracerForCacheComponents(tracer)
6183
}
84+
}
85+
}
6286

63-
const originalStartActiveSpan = tracer.startActiveSpan
64-
// @ts-ignore TS doesn't recognize the overloads correctly
65-
tracer.startActiveSpan = (...startActiveSpanArgs: any[]) => {
66-
const workUnitStore = workUnitAsyncStorage.getStore()
67-
if (!workUnitStore) {
68-
// @ts-ignore TS doesn't recognize the overloads correctly
69-
return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
70-
}
87+
function instrumentTracerForCacheComponents(tracer: Tracer): Tracer {
88+
if (WeakTracers.has(tracer)) {
89+
return tracer
90+
}
91+
const originalStartSpan = tracer.startSpan
92+
tracer.startSpan = (...startSpanArgs) => {
93+
return workUnitAsyncStorage.exit(() =>
94+
originalStartSpan.apply(tracer, startSpanArgs)
95+
)
96+
}
7197

72-
let fnIdx: number = 0
73-
if (
74-
startActiveSpanArgs.length === 2 &&
75-
typeof startActiveSpanArgs[1] === 'function'
76-
) {
77-
fnIdx = 1
78-
} else if (
79-
startActiveSpanArgs.length === 3 &&
80-
typeof startActiveSpanArgs[2] === 'function'
81-
) {
82-
fnIdx = 2
83-
} else if (
84-
startActiveSpanArgs.length > 3 &&
85-
typeof startActiveSpanArgs[3] === 'function'
86-
) {
87-
fnIdx = 3
88-
}
98+
const originalStartActiveSpan = tracer.startActiveSpan
99+
// @ts-ignore TS doesn't recognize the overloads correctly
100+
tracer.startActiveSpan = (...startActiveSpanArgs: any[]) => {
101+
const workUnitStore = workUnitAsyncStorage.getStore()
102+
if (!workUnitStore) {
103+
// @ts-ignore TS doesn't recognize the overloads correctly
104+
return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
105+
}
89106

90-
if (fnIdx) {
91-
const originalFn = startActiveSpanArgs[fnIdx]
92-
if (isUseCacheFunction(originalFn)) {
93-
console.error(
94-
'A Cache Function (`use cache`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.'
95-
)
96-
}
97-
startActiveSpanArgs[fnIdx] = withWorkUnitContext(
98-
workUnitStore,
99-
originalFn
107+
let fnIdx: number = 0
108+
if (
109+
startActiveSpanArgs.length === 2 &&
110+
typeof startActiveSpanArgs[1] === 'function'
111+
) {
112+
fnIdx = 1
113+
} else if (
114+
startActiveSpanArgs.length === 3 &&
115+
typeof startActiveSpanArgs[2] === 'function'
116+
) {
117+
fnIdx = 2
118+
} else if (
119+
startActiveSpanArgs.length > 3 &&
120+
typeof startActiveSpanArgs[3] === 'function'
121+
) {
122+
fnIdx = 3
123+
}
124+
125+
if (fnIdx) {
126+
const originalFn = startActiveSpanArgs[fnIdx]
127+
if (isUseCacheFunction(originalFn)) {
128+
console.error(
129+
'A Cache Function (`use cache`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.'
100130
)
101131
}
102-
103-
return workUnitAsyncStorage.exit(() => {
104-
// @ts-ignore TS doesn't recognize the overloads correctly
105-
return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
106-
})
132+
startActiveSpanArgs[fnIdx] = withWorkUnitContext(
133+
workUnitStore,
134+
originalFn
135+
)
107136
}
108137

109-
WeakTracers.add(tracer)
110-
return tracer
138+
return workUnitAsyncStorage.exit(() => {
139+
// @ts-ignore TS doesn't recognize the overloads correctly
140+
return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
141+
})
111142
}
143+
144+
WeakTracers.add(tracer)
145+
return tracer
112146
}
113147

114148
const WeakTracers = new WeakSet<Tracer>()
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { TracedComponentEarlyTracerSpan } from '../../traced-work'
2+
3+
export function generateStaticParams() {
4+
return [{ slug: 'prerendered' }]
5+
}
6+
7+
export default async function Page({
8+
params,
9+
}: {
10+
params: Promise<{ slug: string }>
11+
}) {
12+
const { slug } = await params
13+
if (slug === 'prerendered') {
14+
return null
15+
}
16+
17+
return <TracedComponentEarlyTracerSpan />
18+
}

‎test/e2e/app-dir/cache-components-allow-otel-spans/app/traced-work.tsx‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { type Span, trace, context } from '@opentelemetry/api'
1+
import { type Span, type Tracer, trace, context } from '@opentelemetry/api'
22
import { Suspense } from 'react'
33

44
async function asyncWork() {
@@ -173,6 +173,45 @@ export const TracedComponentActiveSpan = withActiveSpan(async function (
173173
)
174174
})
175175

176+
type TestGlobal = typeof globalThis & {
177+
__nextTestEarlyTracer?: Tracer
178+
}
179+
180+
export async function TracedComponentEarlyTracerSpan() {
181+
const tracer = (globalThis as TestGlobal).__nextTestEarlyTracer
182+
if (!tracer) {
183+
throw new Error(
184+
'Expected instrumentation to register the early tracer before rendering'
185+
)
186+
}
187+
188+
const span = tracer.startSpan('span-early-manual-span')
189+
const ctx = trace.setSpan(context.active(), span)
190+
191+
return context.with(ctx, async () => {
192+
async function Inner() {
193+
const result = await asyncWork()
194+
return <Result>{result}</Result>
195+
}
196+
return (
197+
<section id="t9">
198+
<h2>(Manual Span) Tracer acquired before provider registration</h2>
199+
<div>
200+
<p>
201+
Span Representative{' '}
202+
<span className="span" suppressHydrationWarning>
203+
{parseInt(span.spanContext().spanId.slice(10), 16)}
204+
</span>
205+
</p>
206+
<Suspense fallback={<Loading />}>
207+
<Inner />
208+
</Suspense>
209+
</div>
210+
</section>
211+
)
212+
})
213+
}
214+
176215
function Loading() {
177216
return <span className="fallback">loading...</span>
178217
}

‎test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,5 +367,17 @@ describe('cache-components OTEL spans', () => {
367367
expect(t8againValue).not.toEqual(0)
368368
}
369369
})
370+
it('should allow creating Spans from a tracer acquired before provider registration', async () => {
371+
const outputIndex = next.cliOutput.length
372+
const browser = await next.browser('/novel/early-span')
373+
// Guard the reported regression directly: span ID generation must not be treated as dynamic Math.random() access during prerendering.
374+
expect(
375+
next.cliOutput
376+
.slice(outputIndex)
377+
.match(/unstable value.*Math\.random\(\).*prerendering/)
378+
).toBeNull()
379+
const result = await browser.elementByCss('#t9 .result')
380+
expect(await result.textContent()).toEqual('42')
381+
})
370382
}
371383
})

‎test/e2e/app-dir/cache-components-allow-otel-spans/instrumentation.node.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
1+
import { trace, type Tracer } from '@opentelemetry/api'
12
import { NodeSDK } from '@opentelemetry/sdk-node'
23
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
34
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'
45
import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express'
56

7+
type TestGlobal = typeof globalThis & {
8+
__nextTestEarlyTracer?: Tracer
9+
}
10+
11+
// Acquire this before sdk.start() to reproduce how instrumentation libraries
12+
// receive a ProxyTracer before the real provider is registered.
13+
;(globalThis as TestGlobal).__nextTestEarlyTracer ??= trace.getTracer(
14+
'next-test-early-tracer'
15+
)
16+
617
const sdk = new NodeSDK({
718
serviceName: 'nextjs-otel-app',
819
traceExporter: new OTLPTraceExporter({

0 commit comments

Comments
 (0)