@@ -5,6 +5,7 @@ import type { DebugImage, Envelope, Event, StackFrame, StackParser } from '@sent
55import type { Profile , ThreadCpuProfile } from '@sentry/types/src/profiling' ;
66import { forEachEnvelopeItem , GLOBAL_OBJ , logger , uuid4 } from '@sentry/utils' ;
77
8+ import { browserPerformanceTimeOrigin } from '../../../utils/src/time' ;
89import { WINDOW } from '../helpers' ;
910import type { JSSelfProfile , JSSelfProfileStack } from './jsSelfProfiling' ;
1011
@@ -213,6 +214,11 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
213214
214215 // We assert samples.length > 0 above and timestamp should always be present
215216 const start = input . samples [ 0 ] . timestamp ;
217+ // The JS SDK might change it's time origin based on some heuristic (see See packages/utils/src/time.ts)
218+ // when that happens, we need to ensure we are correcting the profile timings so the two timelines stay in sync.
219+ // Since JS self profiling time origin is always initialized to performance.timeOrigin, we need to adjust for
220+ // the drift between the SDK selected value and our profile time origin.
221+ const adjustForOriginChange = performance . timeOrigin - ( browserPerformanceTimeOrigin || performance . timeOrigin ) ;
216222
217223 for ( let i = 0 ; i < input . samples . length ; i ++ ) {
218224 const jsSample = input . samples [ i ] ;
@@ -227,7 +233,7 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
227233
228234 profile [ 'samples' ] [ i ] = {
229235 // convert ms timestamp to ns
230- elapsed_since_start_ns : ( ( jsSample . timestamp - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
236+ elapsed_since_start_ns : ( ( jsSample . timestamp + adjustForOriginChange - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
231237 stack_id : EMPTY_STACK_ID ,
232238 thread_id : THREAD_ID_STRING ,
233239 } ;
@@ -260,7 +266,7 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
260266
261267 const sample : Profile [ 'profile' ] [ 'samples' ] [ 0 ] = {
262268 // convert ms timestamp to ns
263- elapsed_since_start_ns : ( ( jsSample . timestamp - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
269+ elapsed_since_start_ns : ( ( jsSample . timestamp + adjustForOriginChange - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
264270 stack_id : STACK_ID ,
265271 thread_id : THREAD_ID_STRING ,
266272 } ;
0 commit comments