Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/browser-utils/src/metrics/webVitalSpans.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Client, Integration, Span, SpanAttributes } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
getActiveSpan,
getClient,
Expand Down Expand Up @@ -329,7 +330,9 @@ export function trackInpAsSpan(client: Client): void {
export function _sendInpSpan(inpValue: number, entry: PerformanceEventTiming, standalone = false): void {
DEBUG_BUILD && debug.log(`Sending INP span (${inpValue})`);

const startTime = msToSec((browserPerformanceTimeOrigin() as number) + entry.startTime);
// INP reports on pagehide, potentially hours after the origin cached at init, so the corrected origin is used to stay
// on the same timeline as span and event timestamps.
const startTime = msToSec((correctedPerformanceTimeOrigin() as number) + entry.startTime);
const duration = msToSec(inpValue);
const interactionType = INP_ENTRY_MAP[entry.name];

Expand Down
3 changes: 3 additions & 0 deletions packages/browser-utils/test/metrics/webVitalSpans.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ vi.mock('@sentry/core', async () => {
return {
...actual,
browserPerformanceTimeOrigin: vi.fn(),
correctedPerformanceTimeOrigin: vi.fn(),
timestampInSeconds: vi.fn(),
getCurrentScope: vi.fn(),
getClient: vi.fn(),
Expand Down Expand Up @@ -475,6 +476,7 @@ describe('_sendInpSpan', () => {
beforeEach(() => {
vi.mocked(SentryCore.getCurrentScope).mockReturnValue(mockScope as any);
vi.mocked(SentryCore.browserPerformanceTimeOrigin).mockReturnValue(1000);
vi.mocked(SentryCore.correctedPerformanceTimeOrigin).mockReturnValue(1000);
vi.mocked(htmlTreeAsString).mockReturnValue('<button>');
vi.mocked(SentryCore.startInactiveSpan).mockReturnValue(mockSpan as any);
vi.mocked(SentryCore.getActiveSpan).mockReturnValue(undefined);
Expand Down Expand Up @@ -592,6 +594,7 @@ describe('trackInpAsSpan', () => {

beforeEach(() => {
vi.mocked(SentryCore.browserPerformanceTimeOrigin).mockReturnValue(1000);
vi.mocked(SentryCore.correctedPerformanceTimeOrigin).mockReturnValue(1000);
vi.mocked(SentryCore.getCurrentScope).mockReturnValue(mockScope as any);
vi.mocked(SentryCore.getActiveSpan).mockReturnValue(undefined);
vi.mocked(SentryCore.startInactiveSpan).mockReturnValue({ end: vi.fn() } as any);
Expand Down
6 changes: 3 additions & 3 deletions packages/browser/src/profiling/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type {
ThreadCpuProfile,
} from '@sentry/core/browser';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
DEFAULT_ENVIRONMENT,
forEachEnvelopeItem,
Expand Down Expand Up @@ -339,7 +339,7 @@ function convertToContinuousProfile(input: {
}

// Align timestamps to SDK time origin to match span/event timelines
const perfOrigin = browserPerformanceTimeOrigin();
const perfOrigin = correctedPerformanceTimeOrigin();
const origin = typeof performance.timeOrigin === 'number' ? performance.timeOrigin : perfOrigin || 0;
const adjustForOriginChange = origin - (perfOrigin || origin);

Expand Down Expand Up @@ -412,7 +412,7 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
// when that happens, we need to ensure we are correcting the profile timings so the two timelines stay in sync.
// Since JS self profiling time origin is always initialized to performance.timeOrigin, we need to adjust for
// the drift between the SDK selected value and our profile time origin.
const perfOrigin = browserPerformanceTimeOrigin();
const perfOrigin = correctedPerformanceTimeOrigin();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Profile elapsed times shift after drift

High Severity

Switching convertJSSelfProfileToSampledFormat to correctedPerformanceTimeOrigin makes adjustForOriginChange non-zero after runtime clock drift. That delta is added into every elapsed_since_start_ns, so the first sample is no longer 0 and all relative sample times shift by the full drift (often negative after device sleep). Continuous profiling absolute timestamps are fine; this only breaks transaction/sampled profiles.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 25c1b28. Configure here.

const origin = typeof performance.timeOrigin === 'number' ? performance.timeOrigin : perfOrigin || 0;
const adjustForOriginChange = origin - (perfOrigin || origin);

Expand Down
7 changes: 6 additions & 1 deletion packages/core/src/shared-exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,12 @@ export {
supportsReferrerPolicy,
} from './utils/supports';
export { SyncPromise, rejectedSyncPromise, resolvedSyncPromise } from './utils/syncpromise';
export { browserPerformanceTimeOrigin, dateTimestampInSeconds, timestampInSeconds } from './utils/time';
export {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
dateTimestampInSeconds,
timestampInSeconds,
} from './utils/time';
export {
TRACEPARENT_REGEXP,
extractTraceparentData,
Expand Down
24 changes: 22 additions & 2 deletions packages/core/src/utils/time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ export function dateTimestampInSeconds(): number {
return safeDateNow() / ONE_SECOND_IN_MS;
}

/**
* The time origin `timestampInSeconds` currently maps the monotonic clock against, kept in sync with the corrections it
* applies. `undefined` until the first `timestampInSeconds` call, and whenever the Performance API is unavailable.
*/
let _correctedTimeOrigin: number | undefined;

/**
* Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not
* support the API.
Expand All @@ -47,7 +53,7 @@ function createUnixTimestampInSecondsFunc(): () => number {

// performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current
// wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.
let timeOrigin = performance.timeOrigin;
let timeOrigin = (_correctedTimeOrigin = performance.timeOrigin);

return () => {
return withRandomSafeContext(() => {
Expand All @@ -66,7 +72,7 @@ function createUnixTimestampInSecondsFunc(): () => number {
// See: https://github.com/mdn/content/issues/4713
// See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6
if (Math.abs(timeOrigin + performanceNow - dateNow) > CLOCK_DRIFT_THRESHOLD_MS) {
timeOrigin = dateNow - performanceNow;
timeOrigin = _correctedTimeOrigin = dateNow - performanceNow;
}

return (timeOrigin + performanceNow) / ONE_SECOND_IN_MS;
Expand All @@ -76,6 +82,20 @@ function createUnixTimestampInSecondsFunc(): () => number {

let _cachedTimestampInSeconds: (() => number) | undefined;

/**
* Returns the time origin (in milliseconds since the UNIX epoch) that {@link timestampInSeconds} currently maps
* `performance.now()` against, including any correction it has applied for clock drift.
*
* Use this over {@link browserPerformanceTimeOrigin} when converting a `PerformanceEntry`'s monotonic `startTime` to
* wall clock time at the moment the entry is observed, so the result shares a timeline with span and event timestamps.
* Returns `undefined` if the Performance API is unavailable, in which case monotonic timestamps cannot be converted.
*/
export function correctedPerformanceTimeOrigin(): number | undefined {
// The origin is only populated once `timestampInSeconds` has resolved which clock source to use.
timestampInSeconds();
return _correctedTimeOrigin;
}

/**
* Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the
* availability of the Performance API.
Expand Down
81 changes: 78 additions & 3 deletions packages/core/test/lib/utils/time.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,17 @@ async function getFreshPerformanceTimeOrigin() {

let freshImportCounter = 0;

async function getFreshTimestampInSeconds(): Promise<() => number> {
async function getFreshTimeModule(): Promise<{
timestampInSeconds: () => number;
correctedPerformanceTimeOrigin: () => number | undefined;
}> {
// A counter rather than `Date.now()`: these tests run under fake timers, which freeze the wall clock and would
// otherwise hand out a cached module.
const timeModule = await import(`../../../src/utils/time?update=${freshImportCounter++}`);
return timeModule.timestampInSeconds;
return import(`../../../src/utils/time?update=${freshImportCounter++}`);
}

async function getFreshTimestampInSeconds(): Promise<() => number> {
return (await getFreshTimeModule()).timestampInSeconds;
}

const RELIABLE_THRESHOLD_MS = 300_000;
Expand Down Expand Up @@ -180,6 +186,75 @@ describe('timestampInSeconds', () => {
});
});

describe('correctedPerformanceTimeOrigin', () => {
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});

it('returns `performance.timeOrigin` while the clocks agree', async () => {
const currentTimeMs = 1767778040866;
const timeSincePageloadMs = 1_000;
const timeOrigin = currentTimeMs - timeSincePageloadMs;

vi.useFakeTimers();
vi.setSystemTime(new Date(currentTimeMs));
vi.stubGlobal('performance', { timeOrigin, now: () => timeSincePageloadMs });

const { correctedPerformanceTimeOrigin } = await getFreshTimeModule();

expect(correctedPerformanceTimeOrigin()).toBe(timeOrigin);
});

it('returns the corrected origin after clock drift, without a prior `timestampInSeconds` call', async () => {
const currentTimeMs = 1767778040866;
const timeSincePageloadMs = 1_000;
const sleepDurationMs = RELIABLE_THRESHOLD_MS + 60_000;

vi.useFakeTimers();
vi.setSystemTime(new Date(currentTimeMs));
vi.stubGlobal('performance', {
timeOrigin: currentTimeMs - timeSincePageloadMs,
now: () => timeSincePageloadMs,
});

const { correctedPerformanceTimeOrigin } = await getFreshTimeModule();

vi.setSystemTime(new Date(currentTimeMs + sleepDurationMs));

expect(correctedPerformanceTimeOrigin()).toBe(currentTimeMs + sleepDurationMs - timeSincePageloadMs);
});

it('stays on the same timeline as `timestampInSeconds`', async () => {
const currentTimeMs = 1767778040866;
const timeSincePageloadMs = 1_000;
const sleepDurationMs = RELIABLE_THRESHOLD_MS + 60_000;

vi.useFakeTimers();
vi.setSystemTime(new Date(currentTimeMs));
vi.stubGlobal('performance', {
timeOrigin: currentTimeMs - timeSincePageloadMs,
now: () => timeSincePageloadMs,
});

const { correctedPerformanceTimeOrigin, timestampInSeconds } = await getFreshTimeModule();

vi.setSystemTime(new Date(currentTimeMs + sleepDurationMs));

// Converting the current `performance.now()` against the origin must yield the same wall clock time that
// `timestampInSeconds` reports, otherwise perf entries and spans land on diverging timelines.
expect((correctedPerformanceTimeOrigin() as number) + timeSincePageloadMs).toBe(timestampInSeconds() * 1000);
});

it('returns `undefined` if the performance API is unavailable', async () => {
vi.stubGlobal('performance', undefined);

const { correctedPerformanceTimeOrigin } = await getFreshTimeModule();

expect(correctedPerformanceTimeOrigin()).toBeUndefined();
});
});

describe('browserPerformanceTimeOrigin', () => {
it('returns `performance.timeOrigin` if it is available and reliable', async () => {
const timeOrigin = await getFreshPerformanceTimeOrigin();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { browserPerformanceTimeOrigin } from '@sentry/core';
import { correctedPerformanceTimeOrigin } from '@sentry/core';
import { record } from '@sentry/rrweb';
import { WINDOW } from '../constants';
import type {
Expand Down Expand Up @@ -87,9 +87,9 @@ function createPerformanceEntry(entry: AllPerformanceEntry): ReplayPerformanceEn
}

function getAbsoluteTime(time: number): number {
// browserPerformanceTimeOrigin can be undefined if `performance` or
// correctedPerformanceTimeOrigin can be undefined if `performance` or
// `performance.now` doesn't exist, but this is already checked by this integration
return ((browserPerformanceTimeOrigin() || WINDOW.performance.timeOrigin) + time) / 1000;
return ((correctedPerformanceTimeOrigin() || WINDOW.performance.timeOrigin) + time) / 1000;
}

function createPaintEntry(entry: PerformancePaintTiming): ReplayPerformanceEntry<PaintData> {
Expand Down
Loading