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 numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, Integration, Span, SpanAttributes } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
Comment on lines 3 to +4

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we need both? I don't think we would like to use a non-accurate time origin anywhere, or maybe I misunderstood?

debug,
getActiveSpan,
getClient,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import type {
ThreadCpuProfile,
} from '@sentry/core/browser';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
DEFAULT_ENVIRONMENT,
forEachEnvelopeItem,
Expand DownExpand 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 DownExpand 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 CursorFix 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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 numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, Integration, Span, SpanAttributes } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
Comment on lines 3 to +4

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we need both? I don't think we would like to use a non-accurate time origin anywhere, or maybe I misunderstood?

debug,
getActiveSpan,
getClient,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import type {
ThreadCpuProfile,
} from '@sentry/core/browser';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
DEFAULT_ENVIRONMENT,
forEachEnvelopeItem,
Expand DownExpand 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 DownExpand 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 CursorFix 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, Integration, Span, SpanAttributes } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
Comment on lines 3 to +4

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we need both? I don't think we would like to use a non-accurate time origin anywhere, or maybe I misunderstood?

debug,
getActiveSpan,
getClient,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import type {
ThreadCpuProfile,
} from '@sentry/core/browser';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
DEFAULT_ENVIRONMENT,
forEachEnvelopeItem,
Expand DownExpand 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 DownExpand 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 CursorFix 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, Integration, Span, SpanAttributes } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
Comment on lines 3 to +4

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we need both? I don't think we would like to use a non-accurate time origin anywhere, or maybe I misunderstood?

debug,
getActiveSpan,
getClient,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import type {
ThreadCpuProfile,
} from '@sentry/core/browser';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
DEFAULT_ENVIRONMENT,
forEachEnvelopeItem,
Expand DownExpand 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 DownExpand 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 CursorFix 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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 numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, Integration, Span, SpanAttributes } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
Comment on lines 3 to +4

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we need both? I don't think we would like to use a non-accurate time origin anywhere, or maybe I misunderstood?

debug,
getActiveSpan,
getClient,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import type {
ThreadCpuProfile,
} from '@sentry/core/browser';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
DEFAULT_ENVIRONMENT,
forEachEnvelopeItem,
Expand DownExpand 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 DownExpand 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 CursorFix 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, Integration, Span, SpanAttributes } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
Comment on lines 3 to +4

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we need both? I don't think we would like to use a non-accurate time origin anywhere, or maybe I misunderstood?

debug,
getActiveSpan,
getClient,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import type {
ThreadCpuProfile,
} from '@sentry/core/browser';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
DEFAULT_ENVIRONMENT,
forEachEnvelopeItem,
Expand DownExpand 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 DownExpand 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 CursorFix 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, Integration, Span, SpanAttributes } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
Comment on lines 3 to +4

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we need both? I don't think we would like to use a non-accurate time origin anywhere, or maybe I misunderstood?

debug,
getActiveSpan,
getClient,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import type {
ThreadCpuProfile,
} from '@sentry/core/browser';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
DEFAULT_ENVIRONMENT,
forEachEnvelopeItem,
Expand DownExpand 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 DownExpand 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 CursorFix 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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 numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
import type { Client, Integration, Span, SpanAttributes } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
Comment on lines 3 to +4

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we need both? I don't think we would like to use a non-accurate time origin anywhere, or maybe I misunderstood?

debug,
getActiveSpan,
getClient,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -12,7 +12,7 @@ import type {
ThreadCpuProfile,
} from '@sentry/core/browser';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
DEFAULT_ENVIRONMENT,
forEachEnvelopeItem,
Expand DownExpand 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 DownExpand 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 CursorFix 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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