Unverified Commit fa71595a authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

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 https://github.com/vercel/next.js/issues/94753

<!-- NEXT_JS_LLM_PR -->
parent a7b04690
......@@ -3,7 +3,11 @@
* This extension must only be loaded in Node environments.
*/
import type { Tracer } from '@opentelemetry/api'
import type {
ProxyTracerProvider,
Tracer,
TracerProvider,
} from '@opentelemetry/api'
import {
type WorkUnitStore,
workUnitAsyncStorage,
......@@ -21,6 +25,15 @@ export function afterRegistration(): void {
extendTracerProviderForCacheComponents()
}
function isProxyTracerProvider(
provider: TracerProvider
): provider is ProxyTracerProvider {
return (
'getDelegateTracer' in provider &&
typeof provider.getDelegateTracer === 'function'
)
}
// In theory we only want to enable this extension when cacheComponents is enabled
// however there are certain servers that might load instrumentation before nextConfig is available
// 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 {
// to exit the workUnitAsyncStorage context when generating spans.
const originalGetTracer = provider.getTracer.bind(provider)
provider.getTracer = (...args) => {
const tracer = originalGetTracer.apply(provider, args)
if (WeakTracers.has(tracer)) {
return tracer
}
const originalStartSpan = tracer.startSpan
tracer.startSpan = (...startSpanArgs) => {
return workUnitAsyncStorage.exit(() =>
originalStartSpan.apply(tracer, startSpanArgs)
)
return instrumentTracerForCacheComponents(
originalGetTracer.apply(provider, args)
)
}
// Tracers acquired before registration can use getDelegateTracer() from the
// proxy provider to get a tracer from the registered provider, bypassing the
// getTracer() patch above. This can be problematic when third-party
// instrumentation creates spans that call dynamic APIs like Math.random(),
// causing a prerendering error. Therefore, patch getDelegateTracer() to apply
// the same tracer instrumentation as getTracer().
if (isProxyTracerProvider(provider)) {
const originalGetDelegateTracer = provider.getDelegateTracer.bind(provider)
provider.getDelegateTracer = (...args) => {
const tracer = originalGetDelegateTracer(...args)
return tracer === undefined
? undefined
: instrumentTracerForCacheComponents(tracer)
}
}
}
const originalStartActiveSpan = tracer.startActiveSpan
// @ts-ignore TS doesn't recognize the overloads correctly
tracer.startActiveSpan = (...startActiveSpanArgs: any[]) => {
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workUnitStore) {
// @ts-ignore TS doesn't recognize the overloads correctly
return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
}
function instrumentTracerForCacheComponents(tracer: Tracer): Tracer {
if (WeakTracers.has(tracer)) {
return tracer
}
const originalStartSpan = tracer.startSpan
tracer.startSpan = (...startSpanArgs) => {
return workUnitAsyncStorage.exit(() =>
originalStartSpan.apply(tracer, startSpanArgs)
)
}
let fnIdx: number = 0
if (
startActiveSpanArgs.length === 2 &&
typeof startActiveSpanArgs[1] === 'function'
) {
fnIdx = 1
} else if (
startActiveSpanArgs.length === 3 &&
typeof startActiveSpanArgs[2] === 'function'
) {
fnIdx = 2
} else if (
startActiveSpanArgs.length > 3 &&
typeof startActiveSpanArgs[3] === 'function'
) {
fnIdx = 3
}
const originalStartActiveSpan = tracer.startActiveSpan
// @ts-ignore TS doesn't recognize the overloads correctly
tracer.startActiveSpan = (...startActiveSpanArgs: any[]) => {
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workUnitStore) {
// @ts-ignore TS doesn't recognize the overloads correctly
return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
}
if (fnIdx) {
const originalFn = startActiveSpanArgs[fnIdx]
if (isUseCacheFunction(originalFn)) {
console.error(
'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.'
)
}
startActiveSpanArgs[fnIdx] = withWorkUnitContext(
workUnitStore,
originalFn
let fnIdx: number = 0
if (
startActiveSpanArgs.length === 2 &&
typeof startActiveSpanArgs[1] === 'function'
) {
fnIdx = 1
} else if (
startActiveSpanArgs.length === 3 &&
typeof startActiveSpanArgs[2] === 'function'
) {
fnIdx = 2
} else if (
startActiveSpanArgs.length > 3 &&
typeof startActiveSpanArgs[3] === 'function'
) {
fnIdx = 3
}
if (fnIdx) {
const originalFn = startActiveSpanArgs[fnIdx]
if (isUseCacheFunction(originalFn)) {
console.error(
'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.'
)
}
return workUnitAsyncStorage.exit(() => {
// @ts-ignore TS doesn't recognize the overloads correctly
return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
})
startActiveSpanArgs[fnIdx] = withWorkUnitContext(
workUnitStore,
originalFn
)
}
WeakTracers.add(tracer)
return tracer
return workUnitAsyncStorage.exit(() => {
// @ts-ignore TS doesn't recognize the overloads correctly
return originalStartActiveSpan.apply(tracer, startActiveSpanArgs)
})
}
WeakTracers.add(tracer)
return tracer
}
const WeakTracers = new WeakSet<Tracer>()
......
import { TracedComponentEarlyTracerSpan } from '../../traced-work'
export function generateStaticParams() {
return [{ slug: 'prerendered' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
if (slug === 'prerendered') {
return null
}
return <TracedComponentEarlyTracerSpan />
}
import { type Span, trace, context } from '@opentelemetry/api'
import { type Span, type Tracer, trace, context } from '@opentelemetry/api'
import { Suspense } from 'react'
async function asyncWork() {
......@@ -173,6 +173,45 @@ export const TracedComponentActiveSpan = withActiveSpan(async function (
)
})
type TestGlobal = typeof globalThis & {
__nextTestEarlyTracer?: Tracer
}
export async function TracedComponentEarlyTracerSpan() {
const tracer = (globalThis as TestGlobal).__nextTestEarlyTracer
if (!tracer) {
throw new Error(
'Expected instrumentation to register the early tracer before rendering'
)
}
const span = tracer.startSpan('span-early-manual-span')
const ctx = trace.setSpan(context.active(), span)
return context.with(ctx, async () => {
async function Inner() {
const result = await asyncWork()
return <Result>{result}</Result>
}
return (
<section id="t9">
<h2>(Manual Span) Tracer acquired before provider registration</h2>
<div>
<p>
Span Representative{' '}
<span className="span" suppressHydrationWarning>
{parseInt(span.spanContext().spanId.slice(10), 16)}
</span>
</p>
<Suspense fallback={<Loading />}>
<Inner />
</Suspense>
</div>
</section>
)
})
}
function Loading() {
return <span className="fallback">loading...</span>
}
......
......@@ -367,5 +367,17 @@ describe('cache-components OTEL spans', () => {
expect(t8againValue).not.toEqual(0)
}
})
it('should allow creating Spans from a tracer acquired before provider registration', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/novel/early-span')
// Guard the reported regression directly: span ID generation must not be treated as dynamic Math.random() access during prerendering.
expect(
next.cliOutput
.slice(outputIndex)
.match(/unstable value.*Math\.random\(\).*prerendering/)
).toBeNull()
const result = await browser.elementByCss('#t9 .result')
expect(await result.textContent()).toEqual('42')
})
}
})
import { trace, type Tracer } from '@opentelemetry/api'
import { NodeSDK } from '@opentelemetry/sdk-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'
import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express'
type TestGlobal = typeof globalThis & {
__nextTestEarlyTracer?: Tracer
}
// Acquire this before sdk.start() to reproduce how instrumentation libraries
// receive a ProxyTracer before the real provider is registered.
;(globalThis as TestGlobal).__nextTestEarlyTracer ??= trace.getTracer(
'next-test-early-tracer'
)
const sdk = new NodeSDK({
serviceName: 'nextjs-otel-app',
traceExporter: new OTLPTraceExporter({
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment