Skip to content

profiling-node: profile envelope timestamp breaks Next.js Cache Components prerendering #26431

Open

Description

@JavierCane

Is there an existing issue for this?

How do you use Sentry?

Sentry SaaS (sentry.io).

Which SDK are you using?

@sentry/nextjs with @sentry/profiling-node (package: profiling-node).

SDK Version

Originally observed with 11.11.0; the deterministic reproduction below also fails with 11.13.0, in both CommonJS and ESM.

Framework Version

Next.js 16.4.5, cacheComponents: true; Node.js 26.13.0, macOS arm64.

Problem

Closing the last sampled span during an on-demand prerender can synchronously flush a CPU profile. The profiler's separate createEventEnvelopeHeaders() still builds sent_at with a zero-argument new Date(), which reads the render clock and violates Next.js Cache Components' prerender restrictions. We observed the production error on course and blog-tag pages; the server bundle pointed to the span-end callback that flushes the profile.

The current profiling-node helper remains separate from core's event envelope helper. Its profile envelope is constructed before client.sendEnvelope(), so changing a transport or beforeEnvelope hook would be too late.

Steps to reproduce

The self-contained example below uses the real native CPU profiler and the actual Next.js SDK safe-context setup. It supplies an isolated client that only collects envelopes, a simulated Next.js work-unit store, and a guarded clock to make the restriction deterministic. It does not start a Next.js server or send telemetry.

  1. In an empty directory, install @sentry/nextjs@11.13.0, @sentry/profiling-node@11.13.0, next@16.4.5, react@19.3.1 and react-dom@19.3.1 with pnpm. Allow the official @sentry/node-cpu-profiler install script if pnpm asks.
  2. Save the following file as repro.mjs.
  3. Run node repro.mjs commonjs and node repro.mjs module.
Deterministic native-profiler reproduction
import assert from "node:assert/strict";
import { AsyncLocalStorage } from "node:async_hooks";
import { createRequire } from "node:module";
import { performance } from "node:perf_hooks";

const require = createRequire(import.meta.url);
const workUnitStorage = new AsyncLocalStorage();
globalThis[Symbol.for("@next/work-unit-async-storage@profiling-test")] = workUnitStorage;
require("@sentry/nextjs");
const { nodeProfilingIntegration } =
	process.argv[2] === "commonjs" ? require("@sentry/profiling-node") : await import("@sentry/profiling-node");
const hooks = new Map();
const envelopes = [];
const integration = nodeProfilingIntegration();

integration.setup({
	getOptions: () => ({ profileSessionSampleRate: 1, profileLifecycle: "trace" }),
	on(name, callback) {
		hooks.set(name, callback);
		return () => hooks.delete(name);
	},
	getDsn: () => undefined,
	getSdkMetadata: () => undefined,
	sendEnvelope(envelope) {
		envelopes.push(envelope);
		return Promise.resolve({ statusCode: 200 });
	},
});

const span = {
	spanContext: () => ({ traceId: "1".repeat(32), spanId: "2".repeat(16), traceFlags: 1 }),
};
const OriginalDate = Date;
const startedAt = OriginalDate.now();

globalThis.Date = new Proxy(OriginalDate, {
	construct(target, args, newTarget) {
		if (args.length === 0) {
			assert.equal(workUnitStorage.getStore(), undefined, "Profiling must not read new Date() during prerender");
		}
		return Reflect.construct(target, args, newTarget);
	},
	get(target, property, receiver) {
		if (property === "now") {
			return () => {
				assert.equal(workUnitStorage.getStore(), undefined, "Profiling must not read Date.now() during prerender");
				return OriginalDate.now();
			};
		}
		return Reflect.get(target, property, receiver);
	},
});

try {
	workUnitStorage.run("prerender", () => {
		hooks.get("spanStart")(span);
		const start = performance.now();
		let work = 0;
		while (performance.now() - start < 40) {
			work += Math.sin(work + 0.1);
		}
		hooks.get("spanEnd")(span);
	});
} finally {
	globalThis.Date = OriginalDate;
}

assert.equal(envelopes.length, 1);
const sentAt = envelopes[0][0].sent_at;
assert.ok(Date.parse(sentAt) >= startedAt && Date.parse(sentAt) <= Date.now());
process.stdout.write(JSON.stringify({ type: envelopes[0][1][0][0].type, sentAt }));

Expected result

The profile can be flushed without reading the ambient prerender clock directly. A valid profile_chunk envelope is collected with an ISO sent_at timestamp. Profiling and the page's rendering strategy stay unchanged.

Actual result

Both module formats fail with:

AssertionError [ERR_ASSERTION]: Profiling must not read new Date() during prerender
    at createEventEnvelopeHeaders
    at makeProfileChunkEnvelope
    at ContinuousProfiler._flush
    at ContinuousProfiler._stopChunkProfiling

Related fixes and why this case is still uncovered

Proposed approach and request for a maintainer's go-ahead

I would like to contribute a small draft PR replacing this timestamp read with new Date(safeDateNow()).toISOString(), importing the existing core helper through its internal export, plus regression coverage for the profiling envelope under a guarded clock.

This follows the responsibility split described in #18700: the Next.js SDK installs the safe runner, and shared SDK code uses the clock/random helpers without importing Next.js. The discussion with gnoff also cautions against broad context escapes that can hide non-determinism affecting rendered or cached values. Here the proposed escape is limited to the telemetry envelope timestamp. I am treating that discussion as design precedent, not as prior approval for this change.

Per External contributors, I have not written the SDK patch or opened a PR. Would a maintainer be happy for me to prepare this focused fix against develop?

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions