Skip to content

Commit f669f66

Browse files
authored
fix(profiling): align to SDK selected time origin (#8599)
This was causing drift between profiling and transaction timelines
1 parent 7d7b8ad commit f669f66

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

packages/browser/src/profiling/utils.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import { DEFAULT_ENVIRONMENT, getCurrentHub } from '@sentry/core';
44
import type { DebugImage, Envelope, Event, StackFrame, StackParser } from '@sentry/types';
55
import type { Profile, ThreadCpuProfile } from '@sentry/types/src/profiling';
6-
import { forEachEnvelopeItem, GLOBAL_OBJ, logger, uuid4 } from '@sentry/utils';
6+
import { browserPerformanceTimeOrigin, forEachEnvelopeItem, GLOBAL_OBJ, logger, uuid4 } from '@sentry/utils';
77

88
import { WINDOW } from '../helpers';
99
import type { JSSelfProfile, JSSelfProfileStack } from './jsSelfProfiling';
@@ -213,6 +213,13 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
213213

214214
// We assert samples.length > 0 above and timestamp should always be present
215215
const start = input.samples[0].timestamp;
216+
// The JS SDK might change it's time origin based on some heuristic (see See packages/utils/src/time.ts)
217+
// when that happens, we need to ensure we are correcting the profile timings so the two timelines stay in sync.
218+
// Since JS self profiling time origin is always initialized to performance.timeOrigin, we need to adjust for
219+
// the drift between the SDK selected value and our profile time origin.
220+
const origin =
221+
typeof performance.timeOrigin === 'number' ? performance.timeOrigin : browserPerformanceTimeOrigin || 0;
222+
const adjustForOriginChange = origin - (browserPerformanceTimeOrigin || origin);
216223

217224
for (let i = 0; i < input.samples.length; i++) {
218225
const jsSample = input.samples[i];
@@ -227,7 +234,7 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
227234

228235
profile['samples'][i] = {
229236
// convert ms timestamp to ns
230-
elapsed_since_start_ns: ((jsSample.timestamp - start) * MS_TO_NS).toFixed(0),
237+
elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start) * MS_TO_NS).toFixed(0),
231238
stack_id: EMPTY_STACK_ID,
232239
thread_id: THREAD_ID_STRING,
233240
};
@@ -260,7 +267,7 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
260267

261268
const sample: Profile['profile']['samples'][0] = {
262269
// convert ms timestamp to ns
263-
elapsed_since_start_ns: ((jsSample.timestamp - start) * MS_TO_NS).toFixed(0),
270+
elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start) * MS_TO_NS).toFixed(0),
264271
stack_id: STACK_ID,
265272
thread_id: THREAD_ID_STRING,
266273
};

0 commit comments

Comments
 (0)