diff --git a/static/app/components/events/interfaces/performance/spanEvidenceTraceView.tsx b/static/app/components/events/interfaces/performance/spanEvidenceTraceView.tsx index 89fcc71de388..6c6a72e7a6da 100644 --- a/static/app/components/events/interfaces/performance/spanEvidenceTraceView.tsx +++ b/static/app/components/events/interfaces/performance/spanEvidenceTraceView.tsx @@ -33,6 +33,7 @@ const DEFAULT_ISSUE_DETAILS_TRACE_VIEW_PREFERENCES: TracePreferencesState = { missing_instrumentation: true, autogroup: {parent: true, sibling: true}, compressed_timeline: false, + clock_drift_correction: false, layout: 'drawer bottom', list: {width: 0.5}, }; diff --git a/static/app/components/events/interfaces/performance/tracePreview.tsx b/static/app/components/events/interfaces/performance/tracePreview.tsx index 3b2dd268ca84..59542ca44725 100644 --- a/static/app/components/events/interfaces/performance/tracePreview.tsx +++ b/static/app/components/events/interfaces/performance/tracePreview.tsx @@ -43,6 +43,7 @@ const DEFAULT_ISSUE_DETAILS_TRACE_VIEW_PREFERENCES: TracePreferencesState = { missing_instrumentation: true, autogroup: {parent: true, sibling: true}, compressed_timeline: false, + clock_drift_correction: false, layout: 'drawer bottom', list: {width: 0.5}, }; diff --git a/static/app/utils/analytics/tracingEventMap.tsx b/static/app/utils/analytics/tracingEventMap.tsx index bbf18bf9c604..8e23d0f61d3f 100644 --- a/static/app/utils/analytics/tracingEventMap.tsx +++ b/static/app/utils/analytics/tracingEventMap.tsx @@ -73,6 +73,7 @@ export type TracingEventParameters = { trace_duration_seconds: number; }; 'trace.preferences.autogrouping_change': {enabled: boolean}; + 'trace.preferences.clock_drift_correction_change': {enabled: boolean}; 'trace.preferences.compressed_timeline_change': {enabled: boolean}; 'trace.preferences.missing_instrumentation_change': {enabled: boolean}; 'trace.quality.missing_spans.doc_link_clicked': Record; @@ -210,6 +211,8 @@ export const tracingEventMap: Record = { 'trace_explorer.toggle_trace_details': 'Trace Explorer: Toggle Trace Details in Table', 'trace_explorer.toggle_span_details': 'Trace Explorer: Toggle Span Details in Table', 'trace.preferences.autogrouping_change': 'Changed Autogrouping Preference', + 'trace.preferences.clock_drift_correction_change': + 'Changed Clock Drift Correction Preference', 'trace.preferences.compressed_timeline_change': 'Changed Compressed Timeline Preference', 'trace.preferences.missing_instrumentation_change': diff --git a/static/app/views/explore/replays/detail/trace/trace.tsx b/static/app/views/explore/replays/detail/trace/trace.tsx index 8af5d594d35f..e039fedfb0be 100644 --- a/static/app/views/explore/replays/detail/trace/trace.tsx +++ b/static/app/views/explore/replays/detail/trace/trace.tsx @@ -47,6 +47,7 @@ const DEFAULT_REPLAY_TRACE_VIEW_PREFERENCES: TracePreferencesState = { missing_instrumentation: true, autogroup: {parent: true, sibling: true}, compressed_timeline: false, + clock_drift_correction: false, layout: 'drawer bottom', list: {width: 0.5}, }; diff --git a/static/app/views/performance/traceDetails/clockDriftIndicators.spec.tsx b/static/app/views/performance/traceDetails/clockDriftIndicators.spec.tsx new file mode 100644 index 000000000000..5ddb0389eb64 --- /dev/null +++ b/static/app/views/performance/traceDetails/clockDriftIndicators.spec.tsx @@ -0,0 +1,32 @@ +import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary'; + +import {ClockDriftTag} from './clockDriftIndicators'; + +describe('ClockDriftTag', () => { + it('renders nothing for a span that was not shifted', () => { + const {container} = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('explains a shift to a later time', async () => { + render(); + + await userEvent.hover(screen.getByText('Shifted +2.00s')); + + expect( + await screen.findByText( + "Shown 2.00s later in the waterfall to correct for clock drift: the clocks of the services in this trace were out of sync. The span's duration and the timestamps below are unchanged." + ) + ).toBeInTheDocument(); + }); + + it('explains a shift to an earlier time', async () => { + render(); + + await userEvent.hover(screen.getByText('Shifted −340.00ms')); + + expect( + await screen.findByText(/^Shown 340.00ms earlier in the waterfall/) + ).toBeInTheDocument(); + }); +}); diff --git a/static/app/views/performance/traceDetails/clockDriftIndicators.tsx b/static/app/views/performance/traceDetails/clockDriftIndicators.tsx new file mode 100644 index 000000000000..f86f88840e25 --- /dev/null +++ b/static/app/views/performance/traceDetails/clockDriftIndicators.tsx @@ -0,0 +1,90 @@ +import {IconClock} from '@sentry/icons/clock'; + +import {Tag} from '@sentry/scraps/badge'; +import {Tooltip} from '@sentry/scraps/tooltip'; + +import {t} from 'sentry/locale'; +import {formatTraceDuration} from 'sentry/utils/duration/formatTraceDuration'; + +import {formatClockDriftOffset} from './traceModels/clockDriftCorrection'; + +// These components take the correction values as props rather than the node: nodes are mutated in +// place when the correction is toggled, so the React Compiler would not see a change in the node. + +/** + * Explains the shift of a span in the waterfall. Wraps the duration label of the span. Renders the + * element as is if the span was not shifted. + * + * The element must be a DOM element, so the tooltip can attach to it without a wrapper that would + * break its positioning. + */ +export function ClockDriftTooltip({ + children, + offsetMs, +}: { + children: React.ReactElement; + offsetMs: number; +}) { + if (offsetMs === 0) { + return children; + } + + return ( + + {children} + + ); +} + +/** + * Marks the duration label of the root of a subtree moved to correct for clock drift. + */ +export function ClockDriftLabelIcon({visible}: {visible: boolean}) { + if (!visible) { + return null; + } + + return ( + + + + ); +} + +/** + * Shown next to the duration in the drawer of a shifted span, as the drawer shows the recorded + * timestamps while the waterfall shows the shifted ones. + */ +export function ClockDriftTag({offsetMs}: {offsetMs: number}) { + if (offsetMs === 0) { + return null; + } + + const distance = formatTraceDuration(Math.abs(offsetMs)); + const title = + offsetMs > 0 + ? t( + "Shown %s later in the waterfall to correct for clock drift: the clocks of the services in this trace were out of sync. The span's duration and the timestamps below are unchanged.", + distance + ) + : t( + "Shown %s earlier in the waterfall to correct for clock drift: the clocks of the services in this trace were out of sync. The span's duration and the timestamps below are unchanged.", + distance + ); + + return ( + + }> + {t('Shifted %s', formatClockDriftOffset(offsetMs))} + + + ); +} diff --git a/static/app/views/performance/traceDetails/trace.spec.tsx b/static/app/views/performance/traceDetails/trace.spec.tsx index fec0286724ed..0b91d8f20e4a 100644 --- a/static/app/views/performance/traceDetails/trace.spec.tsx +++ b/static/app/views/performance/traceDetails/trace.spec.tsx @@ -1375,6 +1375,178 @@ describe('trace view', () => { }); }); + describe('clock drift correction', () => { + const organization = OrganizationFixture({ + features: ['trace-waterfall-clock-drift-correction'], + }); + + beforeEach(() => { + // Trace preferences persist in local storage, don't let a toggled preference leak + localStorage.clear(); + }); + + // The correction is off by default, store it as turned on + function storeClockDriftCorrectionPreference() { + localStorage.setItem( + 'trace-waterfall-preferences', + JSON.stringify({ + drawer_layout: 'drawer right', + missing_instrumentation: false, + autogroup: {parent: true, sibling: true}, + compressed_timeline: true, + clock_drift_correction: true, + }) + ); + } + + function mockClockDriftTrace() { + mockPerformanceSubscriptionDetailsResponse(); + mockProjectDetailsResponse(); + mockTraceResponse({ + body: makeEAPTrace([ + makeEAPSpan({ + event_id: 'browser-request', + op: 'http.client', + description: 'GET /api/0/projects/', + project_id: 1, + sdk_name: 'sentry.javascript.react', + start_timestamp: 10, + end_timestamp: 10.5, + children: [ + makeEAPSpan({ + event_id: 'server-request', + op: 'http.server', + description: 'server request', + is_transaction: true, + project_id: 2, + sdk_name: 'sentry.python.django', + parent_span_id: 'browser-request', + // Recorded 2s before the browser sent the request + start_timestamp: 8, + end_timestamp: 8.2, + children: [ + makeEAPSpan({ + event_id: 'server-query', + op: 'db', + description: 'SELECT * FROM projects', + project_id: 2, + sdk_name: 'sentry.python.django', + parent_span_id: 'server-request', + start_timestamp: 8.05, + end_timestamp: 8.1, + }), + ], + }), + ], + }), + ]), + }); + mockTraceMetaResponse({ + body: { + errorsCount: 0, + logsCount: 0, + metricsCount: 0, + performanceIssuesCount: 0, + spansCount: 3, + spansCountMap: {}, + }, + }); + mockTraceRootFacets(); + mockEventsResponse(); + MockApiClient.addMockResponse({ + url: '/projects/org-slug/project_slug/trace-items/browser-request/', + body: { + itemId: 'browser-request', + links: null, + meta: {}, + timestamp: new Date(10e3).toISOString(), + attributes: [], + }, + }); + MockApiClient.addMockResponse({ + url: '/projects/org-slug/project_slug/trace-items/server-request/', + body: { + itemId: 'server-request', + links: null, + meta: {}, + timestamp: new Date(8e3).toISOString(), + attributes: [], + }, + }); + MockApiClient.addMockResponse({ + url: '/projects/org-slug/project_slug/trace-items/server-query/', + body: { + itemId: 'server-query', + links: null, + meta: {}, + timestamp: new Date(8.1e3).toISOString(), + attributes: [], + }, + }); + MockApiClient.addMockResponse({ + url: '/organizations/org-slug/logs/', + body: {data: []}, + }); + MockApiClient.addMockResponse({ + url: '/organizations/org-slug/dashboards/', + body: [], + }); + } + + it('is off by default and can be toggled', async () => { + mockClockDriftTrace(); + + render(, {initialRouterConfig, organization}); + + expect(await screen.findByText('server request')).toBeInTheDocument(); + expect(screen.queryByTestId('trace-clock-drift-icon')).not.toBeInTheDocument(); + + await userEvent.click(screen.getByRole('button', {name: 'Trace Preferences'})); + await userEvent.click(screen.getByRole('option', {name: /Clock Drift Correction/})); + + expect(await screen.findByTestId('trace-clock-drift-icon')).toBeInTheDocument(); + + await userEvent.click(screen.getByRole('option', {name: /Clock Drift Correction/})); + + await waitFor(() => { + expect(screen.queryByTestId('trace-clock-drift-icon')).not.toBeInTheDocument(); + }); + }); + + it('is not available without the feature', async () => { + mockClockDriftTrace(); + storeClockDriftCorrectionPreference(); + + render(, { + initialRouterConfig, + organization: OrganizationFixture({features: []}), + }); + + expect(await screen.findByText('server request')).toBeInTheDocument(); + expect(screen.queryByTestId('trace-clock-drift-icon')).not.toBeInTheDocument(); + + await userEvent.click(screen.getByRole('button', {name: 'Trace Preferences'})); + + expect( + screen.queryByRole('option', {name: /Clock Drift Correction/}) + ).not.toBeInTheDocument(); + }); + + it('explains the shift when hovering the duration label of a span that moved along with its parent', async () => { + mockClockDriftTrace(); + storeClockDriftCorrectionPreference(); + + render(, {initialRouterConfig, organization}); + + // The child has no icon, its label still explains the shift + await userEvent.hover(await screen.findByText('50.00ms')); + + expect( + await screen.findByText('Shifted by +2.00s to correct for clock drift') + ).toBeInTheDocument(); + }); + }); + describe('pageload', () => { it('expands and collapses loaded EAP children with keyboard navigation', async () => { mockPerformanceSubscriptionDetailsResponse(); diff --git a/static/app/views/performance/traceDetails/trace.tsx b/static/app/views/performance/traceDetails/trace.tsx index bcd5c47a1800..5b55bf4a864b 100644 --- a/static/app/views/performance/traceDetails/trace.tsx +++ b/static/app/views/performance/traceDetails/trace.tsx @@ -33,6 +33,7 @@ import { STATUS_TEXT, } from 'sentry/views/insights/browser/webVitals/utils/scoreToStatus'; +import {CLOCK_DRIFT_ICON_GAP_PX} from './traceModels/clockDriftCorrection'; import {TraceTree} from './traceModels/traceTree'; import type {BaseNode} from './traceModels/traceTreeNode/baseNode'; import type {TraceEvents, TraceScheduler} from './traceRenderers/traceScheduler'; @@ -1641,6 +1642,7 @@ const TraceStylingWrapper = styled('div')` bottom: 0; display: flex; align-items: center; + gap: ${CLOCK_DRIFT_ICON_GAP_PX}px; transform-origin: left center; font-size: ${p => p.theme.font.size.xs}; line-height: 1; @@ -1658,6 +1660,10 @@ const TraceStylingWrapper = styled('div')` text-box: trim-both cap alphabetic; } + .TraceClockDriftIcon { + display: flex; + } + .TraceChildrenCount { height: 16px; white-space: nowrap; diff --git a/static/app/views/performance/traceDetails/traceAnalytics.tsx b/static/app/views/performance/traceDetails/traceAnalytics.tsx index 86d187a72162..5ad057aa8be4 100644 --- a/static/app/views/performance/traceDetails/traceAnalytics.tsx +++ b/static/app/views/performance/traceDetails/traceAnalytics.tsx @@ -236,6 +236,15 @@ const trackCompressedTimelinePreferenceChange = ( ) => trackAnalytics('trace.preferences.compressed_timeline_change', {organization, enabled}); +const trackClockDriftCorrectionPreferenceChange = ( + organization: Organization, + enabled: boolean +) => + trackAnalytics('trace.preferences.clock_drift_correction_change', { + organization, + enabled, + }); + const traceAnalytics = { // Trace Onboarding trackTracingOnboarding, @@ -274,6 +283,7 @@ const traceAnalytics = { trackAutogroupingPreferenceChange, trackMissingInstrumentationPreferenceChange, trackCompressedTimelinePreferenceChange, + trackClockDriftCorrectionPreferenceChange, // Trace Drawer Details trackEAPSpanHasDetails, trackGenAISpanDetailsViewed, diff --git a/static/app/views/performance/traceDetails/traceDrawer/details/styles.tsx b/static/app/views/performance/traceDetails/traceDrawer/details/styles.tsx index 6cf0f62fcb14..01d823c870bd 100644 --- a/static/app/views/performance/traceDetails/traceDrawer/details/styles.tsx +++ b/static/app/views/performance/traceDetails/traceDrawer/details/styles.tsx @@ -51,12 +51,14 @@ import {useParams} from 'sentry/utils/useParams'; import {useUser} from 'sentry/utils/useUser'; import {getIsAiNode} from 'sentry/views/insights/pages/agents/utils/aiTraceNodes'; import {getIsMCPNode} from 'sentry/views/insights/pages/mcp/utils/mcpTraceNodes'; +import {ClockDriftTag} from 'sentry/views/performance/traceDetails/clockDriftIndicators'; import {traceAnalytics} from 'sentry/views/performance/traceDetails/traceAnalytics'; import { makeTraceContinuousProfilingLink, makeTransactionProfilingLink, } from 'sentry/views/performance/traceDetails/traceDrawer/traceProfilingLink'; import {isEAPSpanNode} from 'sentry/views/performance/traceDetails/traceGuards'; +import {getRecordedSubtreeSpace} from 'sentry/views/performance/traceDetails/traceModels/clockDriftCorrection'; import type {BaseNode} from 'sentry/views/performance/traceDetails/traceModels/traceTreeNode/baseNode'; import type {EapSpanNode} from 'sentry/views/performance/traceDetails/traceModels/traceTreeNode/eapSpanNode'; import { @@ -223,6 +225,7 @@ function Highlights({ {comparison.deltaText} ) : null} + @@ -405,13 +408,14 @@ export function getTraceIssuesTarget({ // Adding a buffer of 15mins for errors only traces, where there is no concept of // trace duration and start equals end timestamps. const buffer = node.space[1] > 0 ? 0 : 15 * 60 * 1000; + const [recordedStart, recordedDuration] = getRecordedSubtreeSpace(node); return { pathname: `/organizations/${organization.slug}/issues/`, query: { query: `trace:${traceSlug.trim()}`, - start: new Date(node.space[0] - buffer).toISOString(), - end: new Date(node.space[0] + node.space[1] + buffer).toISOString(), + start: new Date(recordedStart - buffer).toISOString(), + end: new Date(recordedStart + recordedDuration + buffer).toISOString(), // If we don't pass the project param, the issues page will filter by the last selected project. // Traces can have multiple projects, so we query issues by all projects and rely on our search query to filter the results. project: -1, diff --git a/static/app/views/performance/traceDetails/traceDrawer/tabs/traceProfiles.tsx b/static/app/views/performance/traceDetails/traceDrawer/tabs/traceProfiles.tsx index 0c2aa6d2b04a..c484a1ce94e4 100644 --- a/static/app/views/performance/traceDetails/traceDrawer/tabs/traceProfiles.tsx +++ b/static/app/views/performance/traceDetails/traceDrawer/tabs/traceProfiles.tsx @@ -16,6 +16,7 @@ import {ellipsize} from 'sentry/utils/string/ellipsize'; import {useOrganization} from 'sentry/utils/useOrganization'; import {useProjects} from 'sentry/utils/useProjects'; import {traceAnalytics} from 'sentry/views/performance/traceDetails/traceAnalytics'; +import {getRecordedSpace} from 'sentry/views/performance/traceDetails/traceModels/clockDriftCorrection'; import {TraceTree} from 'sentry/views/performance/traceDetails/traceModels/traceTree'; import type {BaseNode} from 'sentry/views/performance/traceDetails/traceModels/traceTreeNode/baseNode'; @@ -71,13 +72,14 @@ export function TraceProfiles({tree}: {tree: TraceTree}) { } const query = getProfileRouteQueryFromNode(node); + const [recordedStart, recordedDuration] = getRecordedSpace(node); const link = profilerId ? generateContinuousProfileFlamechartRouteWithQuery({ organization, profilerId, - start: new Date(node.space[0]).toISOString(), - end: new Date(node.space[0] + node.space[1]).toISOString(), + start: new Date(recordedStart).toISOString(), + end: new Date(recordedStart + recordedDuration).toISOString(), projectSlug: node.projectSlug ?? '', query, }) diff --git a/static/app/views/performance/traceDetails/traceDrawer/traceProfilingLink.spec.tsx b/static/app/views/performance/traceDetails/traceDrawer/traceProfilingLink.spec.tsx index d09c4339c1eb..94621aad920f 100644 --- a/static/app/views/performance/traceDetails/traceDrawer/traceProfilingLink.spec.tsx +++ b/static/app/views/performance/traceDetails/traceDrawer/traceProfilingLink.spec.tsx @@ -60,6 +60,21 @@ describe('traceProfilingLink', () => { ); }); + it('uses the recorded time of a span moved to correct for clock drift', () => { + const node = makeEapSpanNode({transaction_id: undefined}); + node.space = [node.space[0] + 60_000, node.space[1]]; + node.clockDriftOffsetMs = 60_000; + + expect(makeTraceContinuousProfilingLink(node, 'profiler-id', options)).toEqual( + expect.objectContaining({ + query: expect.objectContaining({ + end: new Date(2100).toISOString(), + start: new Date(900).toISOString(), + }), + }) + ); + }); + it('uses the transaction span ID without a transaction event', () => { const node = makeEapSpanNode({ transaction_id: 'transaction-event-id', diff --git a/static/app/views/performance/traceDetails/traceDrawer/traceProfilingLink.ts b/static/app/views/performance/traceDetails/traceDrawer/traceProfilingLink.ts index 738a658cb2e5..f13a5ca30013 100644 --- a/static/app/views/performance/traceDetails/traceDrawer/traceProfilingLink.ts +++ b/static/app/views/performance/traceDetails/traceDrawer/traceProfilingLink.ts @@ -8,6 +8,7 @@ import { PROFILE_CONTEXT_WINDOW_MS, } from 'sentry/utils/profiling/routes'; import {isEAPSpanNode} from 'sentry/views/performance/traceDetails/traceGuards'; +import {getRecordedSpace} from 'sentry/views/performance/traceDetails/traceModels/clockDriftCorrection'; import type {BaseNode} from 'sentry/views/performance/traceDetails/traceModels/traceTreeNode/baseNode'; export function makeTransactionProfilingLink( @@ -38,9 +39,10 @@ export function makeTraceContinuousProfilingLink( return null; } - const start = getDateFromTimestamp(node.space[0] - PROFILE_CONTEXT_WINDOW_MS); + const [recordedStart, recordedDuration] = getRecordedSpace(node); + const start = getDateFromTimestamp(recordedStart - PROFILE_CONTEXT_WINDOW_MS); const end = getDateFromTimestamp( - node.space[0] + node.space[1] + PROFILE_CONTEXT_WINDOW_MS + recordedStart + recordedDuration + PROFILE_CONTEXT_WINDOW_MS ); if (start === null || end === null) { diff --git a/static/app/views/performance/traceDetails/traceIssueUtils.ts b/static/app/views/performance/traceDetails/traceIssueUtils.ts index d4581f35d52c..127284df6cb4 100644 --- a/static/app/views/performance/traceDetails/traceIssueUtils.ts +++ b/static/app/views/performance/traceDetails/traceIssueUtils.ts @@ -161,12 +161,17 @@ function getTraceIssueSeverityRank(issue: TraceTree.TraceIssue): number { } } +/** + * Pass the node's `clockDriftOffsetMs` as `offsetMs`, so issues line up with a node that was + * moved to correct for clock drift. + */ export function getTraceIssueTimestamp( issue: TraceTree.TraceIssue, - nodeSpace: [number, number] + nodeSpace: [number, number], + offsetMs = 0 ): number { if ('timestamp' in issue && typeof issue.timestamp === 'number') { - return issue.timestamp * 1e3; + return issue.timestamp * 1e3 + offsetMs; } let startTimestamp: number | undefined; @@ -176,5 +181,7 @@ export function getTraceIssueTimestamp( startTimestamp = issue.start; } - return typeof startTimestamp === 'number' ? startTimestamp * 1e3 : nodeSpace[0]; + return typeof startTimestamp === 'number' + ? startTimestamp * 1e3 + offsetMs + : nodeSpace[0]; } diff --git a/static/app/views/performance/traceDetails/traceModels/clockDriftCorrection.spec.tsx b/static/app/views/performance/traceDetails/traceModels/clockDriftCorrection.spec.tsx new file mode 100644 index 000000000000..5cf395172c9f --- /dev/null +++ b/static/app/views/performance/traceDetails/traceModels/clockDriftCorrection.spec.tsx @@ -0,0 +1,829 @@ +import {OrganizationFixture} from 'sentry-fixture/organization'; + +import { + isEAPSpanNode, + isParentAutogroupedNode, + isSiblingAutogroupedNode, +} from 'sentry/views/performance/traceDetails/traceGuards'; + +import type {BaseNode} from './traceTreeNode/baseNode'; +import { + applyClockDriftCorrection, + getAlignmentRange, + getClockDriftShifts, + getRecordedSubtreeSpace, + getSmallestShift, + MIN_CLOCK_DRIFT_CORRECTION_MS, + removeClockDriftCorrection, +} from './clockDriftCorrection'; +import {TraceTree} from './traceTree'; +import {makeEAPSpan, makeEAPTrace} from './traceTreeTestUtils'; + +const organization = OrganizationFixture(); + +const T = 1_700_000_000; +const ms = (value: number) => value / 1e3; + +const preferences = { + clock_drift_correction: true, + missing_instrumentation: false, + autogroup: {parent: false, sibling: false}, +}; + +type Request = { + /** Client span duration in ms. */ + clientDuration: number; + /** Client span start in ms after the pageload started. */ + clientStart: number; + id: string; + /** Server span duration in ms. */ + serverDuration: number; + /** Server span start in ms, relative to the client span start, as recorded. */ + serverStartGap: number; + serverChildren?: Array>; + /** Whether the server span starts a new segment, i.e. runs in another process. */ + serverIsSegment?: boolean; + serverProjectId?: number; + serverSdkName?: string; +}; + +function makeRequest(request: Request) { + const clientStart = T + ms(request.clientStart); + const serverStart = clientStart + ms(request.serverStartGap); + + return makeEAPSpan({ + event_id: `client-${request.id}`, + op: 'http.client', + project_id: 1, + project_slug: 'javascript', + sdk_name: 'sentry.javascript.react', + start_timestamp: clientStart, + end_timestamp: clientStart + ms(request.clientDuration), + children: [ + makeEAPSpan({ + event_id: `server-${request.id}`, + op: 'http.server', + is_transaction: request.serverIsSegment ?? true, + project_id: request.serverProjectId ?? 2, + project_slug: 'sentry', + sdk_name: request.serverSdkName ?? 'sentry.python.django', + parent_span_id: `client-${request.id}`, + start_timestamp: serverStart, + end_timestamp: serverStart + ms(request.serverDuration), + children: request.serverChildren ?? [], + }), + ], + }); +} + +function makePageload(requests: Array>) { + return makeEAPTrace([ + makeEAPSpan({ + event_id: 'pageload', + op: 'pageload', + is_transaction: true, + project_id: 1, + project_slug: 'javascript', + sdk_name: 'sentry.javascript.react', + start_timestamp: T - 10, + end_timestamp: T + 300, + children: requests, + }), + ]); +} + +/** A server segment, e.g. one request handled on one host, making requests to other services. */ +function makeSegment(id: string, requests: Array>) { + return makeEAPSpan({ + event_id: `segment-${id}`, + op: 'http.server', + is_transaction: true, + project_id: 2, + sdk_name: 'sentry.python.django', + start_timestamp: T - 10, + end_timestamp: T + 300, + children: requests, + }); +} + +function build(trace: ReturnType, clockDriftCorrection = true) { + return TraceTree.FromTrace(trace, { + replay: null, + organization, + preferences: {...preferences, clock_drift_correction: clockDriftCorrection}, + }); +} + +function findSpan(tree: TraceTree, id: string): BaseNode { + const node = tree.root.findChild(n => isEAPSpanNode(n) && n.value.event_id === id); + if (!node) { + throw new Error(`Span ${id} not found`); + } + return node; +} + +/** Recorded server start relative to the (unshifted) client start, as currently displayed. */ +function displayedGaps(tree: TraceTree, id: string) { + const client = findSpan(tree, `client-${id}`); + const server = findSpan(tree, `server-${id}`); + return { + start: server.space[0] - client.space[0], + end: client.space[0] + client.space[1] - (server.space[0] + server.space[1]), + }; +} + +describe('clock drift correction', () => { + describe('getAlignmentRange', () => { + it('returns the shifts that fit the server span into the client span', () => { + expect(getAlignmentRange([1000, 500], [1100, 200])).toEqual([-100, 200]); + }); + + it('returns null if the server span is longer than the client span', () => { + expect(getAlignmentRange([1000, 100], [1000, 200])).toBeNull(); + }); + }); + + describe('getSmallestShift', () => { + it.each([ + [[-100, 200], 0], + [[50, 200], 50], + [[-300, -20], -20], + ] as Array<[[number, number], number]>)( + 'picks the shift closest to 0 in %j', + (range, shift) => { + expect(getSmallestShift(range)).toBe(shift); + } + ); + }); + + describe('getClockDriftShifts', () => { + it('uses one shift for all requests if one fits them all', () => { + expect( + getClockDriftShifts([ + [100, 300], + [150, 400], + ]) + ).toEqual([150, 150]); + }); + + it('leaves requests alone that disagree with the majority', () => { + expect( + getClockDriftShifts([ + [100, 200], + [150, 250], + [-400, -300], + ]) + ).toEqual([150, 150, null]); + }); + + it('corrects nothing if there is no majority', () => { + expect( + getClockDriftShifts([ + [100, 200], + [-400, -300], + ]) + ).toEqual([null, null]); + expect( + getClockDriftShifts([ + [100, 200], + [150, 250], + [-400, -300], + [-350, -250], + ]) + ).toEqual([null, null, null, null]); + }); + + it('does not correct requests if the majority agrees no correction is needed', () => { + expect( + getClockDriftShifts([ + [-100, 200], + [-50, 300], + [400, 500], + ]) + ).toEqual([0, 0, null]); + }); + + it('treats requests that miss each other by less than the tolerance as agreeing', () => { + // No shift fits both exactly, so both end up 2.5ms off + expect( + getClockDriftShifts([ + [100, 200], + [205, 300], + ]) + ).toEqual([202.5, 202.5]); + }); + + it('skips requests that cannot be aligned', () => { + expect(getClockDriftShifts([[100, 200], null])).toEqual([100, null]); + }); + }); + + describe('trace tree', () => { + it('moves a server span that started before the request was sent (client clock ahead by 2min)', () => { + // client 481ms, server 121ms, recorded 121s before the client span + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 480.8, + serverStartGap: -121_056.4, + serverDuration: 121.4, + }), + ]) + ); + + const server = findSpan(tree, 'server-1'); + expect(server.clockDriftOffsetMs).toBeCloseTo(121_056.4); + expect(server.isClockDriftCorrectionRoot).toBe(true); + expect(displayedGaps(tree, '1').start).toBeCloseTo(0); + // The recorded timestamps are untouched + expect(server.startTimestamp).toBeCloseTo(T - 121.0564); + }); + + it('moves a server span that ended after the response was received (client clock behind by 20s)', () => { + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 537, + serverStartGap: 20_655.9, + serverDuration: 287.2, + }), + ]) + ); + + expect(findSpan(tree, 'server-1').clockDriftOffsetMs).toBeCloseTo(-20_406.1); + expect(displayedGaps(tree, '1').end).toBeCloseTo(0); + }); + + it('moves all requests of a client by the same amount', () => { + // 7 requests from the same browser, recorded 295-300ms late + const recorded = [ + [161.4, 99.6, 358.9], + [190.6, 128.9, 361.2], + [180.7, 112.6, 365.6], + [198.7, 129.1, 368.3], + [299.7, 221.9, 373], + [183.5, 125.5, 355.6], + [195.3, 142.4, 350.3], + ] as const; + + const tree = build( + makePageload( + recorded.map(([clientDuration, serverDuration, serverStartGap], index) => + makeRequest({ + id: `${index}`, + clientStart: index * 1000, + clientDuration, + serverDuration, + serverStartGap, + }) + ) + ) + ); + + const offsets = recorded.map( + (_, index) => findSpan(tree, `server-${index}`).clockDriftOffsetMs + ); + // The tightest request decides the shift, and every request gets it + for (const offset of offsets) { + expect(offset).toBeCloseTo(-299.5); + } + recorded.forEach((_, index) => { + const gaps = displayedGaps(tree, `${index}`); + expect(gaps.start).toBeGreaterThanOrEqual(-1e-6); + expect(gaps.end).toBeGreaterThanOrEqual(-1e-6); + }); + }); + + it('moves the requests of each segment by their own shared amount', () => { + // Two hosts of the same service, with clocks that disagree in different directions + const tree = build( + makeEAPTrace([ + makeSegment('a', [ + makeRequest({ + id: 'a1', + clientStart: 0, + clientDuration: 161.4, + serverStartGap: 358.9, + serverDuration: 99.6, + }), + makeRequest({ + id: 'a2', + clientStart: 1000, + clientDuration: 195.3, + serverStartGap: 350.3, + serverDuration: 142.4, + }), + ]), + makeSegment('b', [ + makeRequest({ + id: 'b1', + clientStart: 0, + clientDuration: 400, + serverStartGap: -150, + serverDuration: 100, + }), + ]), + ]) + ); + + // Each request on host A alone would need a slightly different shift, they get the one + // that fits both + expect(findSpan(tree, 'server-a1').clockDriftOffsetMs).toBeCloseTo(-297.4); + expect(findSpan(tree, 'server-a2').clockDriftOffsetMs).toBeCloseTo(-297.4); + expect(findSpan(tree, 'server-b1').clockDriftOffsetMs).toBeCloseTo(150); + }); + + it('does not move a request that disagrees with the other requests of its segment', () => { + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 161.4, + serverStartGap: 358.9, + serverDuration: 99.6, + }), + makeRequest({ + id: '2', + clientStart: 1000, + clientDuration: 195.3, + serverStartGap: 350.3, + serverDuration: 142.4, + }), + // Off in the other direction, which the browser's clock can't explain + makeRequest({ + id: '3', + clientStart: 2000, + clientDuration: 400, + serverStartGap: -150, + serverDuration: 100, + }), + ]) + ); + + expect(findSpan(tree, 'server-1').clockDriftOffsetMs).toBeCloseTo(-297.4); + expect(findSpan(tree, 'server-2').clockDriftOffsetMs).toBeCloseTo(-297.4); + expect(findSpan(tree, 'server-3').isClockDriftCorrectionRoot).toBe(false); + expect(findSpan(tree, 'server-3').clockDriftOffsetMs).toBe(0); + }); + + it('moves the whole server subtree, including issues', () => { + const serverStart = T + ms(-1366); + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 287.6, + serverStartGap: -1366, + serverDuration: 186.6, + serverChildren: [ + makeEAPSpan({ + event_id: 'db', + op: 'db', + project_id: 2, + sdk_name: 'sentry.python.django', + start_timestamp: serverStart + ms(20), + end_timestamp: serverStart + ms(50), + }), + ], + }), + ]) + ); + + const server = findSpan(tree, 'server-1'); + const db = findSpan(tree, 'db'); + + expect(server.clockDriftOffsetMs).toBeCloseTo(1366); + expect(server.isClockDriftCorrectionRoot).toBe(true); + expect(db.clockDriftOffsetMs).toBeCloseTo(1366); + expect(db.isClockDriftCorrectionRoot).toBe(false); + expect(db.space[0] - server.space[0]).toBeCloseTo(20); + }); + + it('gives autogroups in a moved subtree the offset of the spans they wrap', () => { + const serverStart = T + ms(-1366); + const span = ( + id: string, + op: string, + children: Array> = [] + ) => + makeEAPSpan({ + event_id: id, + op, + project_id: 2, + start_timestamp: serverStart + ms(20), + end_timestamp: serverStart + ms(50), + children, + }); + + const tree = TraceTree.FromTrace( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 287.6, + serverStartGap: -1366, + serverDuration: 186.6, + serverChildren: [ + span('middleware-1', 'middleware', [span('middleware-2', 'middleware')]), + ...[1, 2, 3, 4, 5].map(i => span(`db-${i}`, 'db')), + ], + }), + ]), + { + replay: null, + organization, + preferences: {...preferences, autogroup: {parent: true, sibling: true}}, + } + ); + + const parentGroup = tree.root.findChild(isParentAutogroupedNode); + const siblingGroup = tree.root.findChild(isSiblingAutogroupedNode); + + expect(parentGroup?.clockDriftOffsetMs).toBeCloseTo(1366); + expect(siblingGroup?.clockDriftOffsetMs).toBeCloseTo(1366); + }); + + it('does not move server spans that fit inside their client span', () => { + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 400, + serverStartGap: 170, + serverDuration: 200, + }), + ]) + ); + + expect(tree.clock_drift_correction_count).toBe(0); + }); + + it('does not move server spans that are less than the threshold off', () => { + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 400, + serverStartGap: -(MIN_CLOCK_DRIFT_CORRECTION_MS - 1), + serverDuration: 200, + }), + ]) + ); + + expect(tree.clock_drift_correction_count).toBe(0); + }); + + it('moves server spans that are at least the threshold off', () => { + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 400, + serverStartGap: -MIN_CLOCK_DRIFT_CORRECTION_MS, + serverDuration: 200, + }), + ]) + ); + + expect(findSpan(tree, 'server-1').clockDriftOffsetMs).toBeCloseTo( + MIN_CLOCK_DRIFT_CORRECTION_MS + ); + }); + + it('does not move server spans that are longer than their client span', () => { + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 100, + serverStartGap: 50, + serverDuration: 300, + }), + ]) + ); + + expect(tree.clock_drift_correction_count).toBe(0); + }); + + it('moves server spans of full-stack frameworks that share the project and sdk', () => { + // e.g. Next.js reports the browser and the server under the same project and SDK name + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 100, + serverStartGap: -500, + serverDuration: 50, + serverProjectId: 1, + serverSdkName: 'sentry.javascript.react', + }), + ]) + ); + + expect(findSpan(tree, 'server-1').clockDriftOffsetMs).toBeCloseTo(500); + }); + + it('does not move server spans that do not start a new segment', () => { + // Same process, so the same clock + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 100, + serverStartGap: -500, + serverDuration: 50, + serverIsSegment: false, + }), + ]) + ); + + expect(tree.clock_drift_correction_count).toBe(0); + }); + + it('does not correct anything if the preference is disabled', () => { + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 480.8, + serverStartGap: -121_056.4, + serverDuration: 121.4, + }), + ]), + false + ); + + expect(tree.clock_drift_correction_count).toBe(0); + }); + + it('restores the recorded spaces when removed, and can be applied again', () => { + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 537, + serverStartGap: 20_655.9, + serverDuration: 287.2, + }), + ]) + ); + const server = findSpan(tree, 'server-1'); + const recordedStart = server.startTimestamp! * 1e3; + + removeClockDriftCorrection(tree.root); + expect(server.space[0]).toBe(recordedStart); + expect(server.clockDriftOffsetMs).toBe(0); + expect(server.isClockDriftCorrectionRoot).toBe(false); + + expect(applyClockDriftCorrection(tree.root)).toBe(1); + expect(server.clockDriftOffsetMs).toBeCloseTo(-20_406.1); + }); + + it('corrects a server rendered pageload the same way when toggled later', () => { + // The server handler renders the page whose pageload continues its trace. The pageload is + // swapped above the server handler, so it is not a client server pair anymore. + const trace = makeEAPTrace([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 300, + serverStartGap: -1000, + serverDuration: 200, + serverChildren: [ + makeEAPSpan({ + event_id: 'ssr-pageload', + op: 'pageload', + is_transaction: true, + project_id: 1, + sdk_name: 'sentry.javascript.react', + start_timestamp: T + ms(100), + end_timestamp: T + ms(250), + }), + ], + }), + ]); + + const built = build(trace); + const toggled = build(trace, false); + applyClockDriftCorrection(toggled.root); + + for (const tree of [built, toggled]) { + const pageload = findSpan(tree, 'ssr-pageload'); + expect(pageload.parent).toBe(findSpan(tree, 'client-1')); + expect(pageload.clockDriftOffsetMs).toBe(0); + expect(findSpan(tree, 'server-1').clockDriftOffsetMs).toBe(0); + } + }); + + it('does not stretch the trace space to where misaligned spans were recorded', () => { + const trace = makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 480.8, + serverStartGap: -121_056.4, + serverDuration: 121.4, + }), + ]); + + // The pageload starts 10s before the request, the server span was recorded 121s before it + expect(build(trace).root.space[0]).toBeCloseTo((T - 10) * 1e3); + expect(build(trace, false).root.space[0]).toBeCloseTo((T - 121.0564) * 1e3); + }); + + it('updates the trace space when the correction is removed', () => { + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 480.8, + serverStartGap: -121_056.4, + serverDuration: 121.4, + }), + ]) + ); + const onTimelineChange = jest.fn(); + tree.on('trace timeline change', onTimelineChange); + + tree.setClockDriftCorrection(false, {organization, preferences}); + + expect(tree.root.space[0]).toBeCloseTo((T - 121.0564) * 1e3); + expect(onTimelineChange).toHaveBeenCalledWith(tree.root.space); + + tree.setClockDriftCorrection(true, {organization, preferences}); + + expect(tree.root.space[0]).toBeCloseTo((T - 10) * 1e3); + }); + + it('counts the corrected spans of the tree', () => { + const misaligned = (id: string) => + makeRequest({ + id, + clientStart: 0, + clientDuration: 480.8, + serverStartGap: -121_056.4, + serverDuration: 121.4, + }); + + const tree = build(makePageload([misaligned('1')])); + expect(tree.clock_drift_correction_count).toBe(1); + + tree.appendTree(build(makePageload([misaligned('2')]))); + expect(tree.clock_drift_correction_count).toBe(2); + + expect(tree.setClockDriftCorrection(false, {organization, preferences})).toBe(0); + expect(tree.clock_drift_correction_count).toBe(0); + + expect(tree.setClockDriftCorrection(true, {organization, preferences})).toBe(2); + expect(tree.clock_drift_correction_count).toBe(2); + }); + + it('corrects requests made from spans nested in the segment', () => { + const tree = build( + makePageload([ + makeEAPSpan({ + event_id: 'render', + op: 'ui.react.render', + project_id: 1, + sdk_name: 'sentry.javascript.react', + start_timestamp: T, + end_timestamp: T + ms(300), + children: [ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 300, + serverStartGap: -1000, + serverDuration: 200, + }), + ], + }), + ]) + ); + + expect(findSpan(tree, 'server-1').isClockDriftCorrectionRoot).toBe(true); + expect(displayedGaps(tree, '1').start).toBeCloseTo(0); + }); + + it('moves services called by a moved server along with it', () => { + const serverStart = T + ms(-1000); + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 300, + serverStartGap: -1000, + serverDuration: 200, + serverChildren: [ + makeEAPSpan({ + event_id: 'client-nested', + op: 'http.client', + project_id: 2, + sdk_name: 'sentry.python.django', + start_timestamp: serverStart + ms(50), + end_timestamp: serverStart + ms(150), + children: [ + makeEAPSpan({ + event_id: 'server-nested', + op: 'http.server', + is_transaction: true, + project_id: 3, + sdk_name: 'sentry.python', + start_timestamp: serverStart + ms(60), + end_timestamp: serverStart + ms(140), + }), + ], + }), + ], + }), + ]) + ); + + const nested = findSpan(tree, 'server-nested'); + expect(nested.clockDriftOffsetMs).toBeCloseTo(1000); + // Its own clock agrees with its caller, so it is not corrected on its own + expect(nested.isClockDriftCorrectionRoot).toBe(false); + expect(tree.clock_drift_correction_count).toBe(1); + }); + }); + + describe('getRecordedSubtreeSpace', () => { + it('covers the recorded time of spans moved out of the trace', () => { + const tree = build( + makePageload([ + makeRequest({ + id: '1', + clientStart: 0, + clientDuration: 480.8, + serverStartGap: -121_056.4, + serverDuration: 121.4, + }), + ]) + ); + + const trace = tree.root.children[0]!; + const [start, duration] = getRecordedSubtreeSpace(trace); + + // The server span was recorded 121s before the corrected trace starts + expect(trace.space[0]).toBeCloseTo((T - 10) * 1e3); + expect(start).toBeCloseTo((T - 121.0564) * 1e3); + expect(start + duration).toBeCloseTo(trace.space[0] + trace.space[1]); + }); + }); + + describe('recorded space', () => { + const drifted = (id: string) => + makeRequest({ + id, + clientStart: 0, + clientDuration: 480.8, + serverStartGap: -121_056.4, + serverDuration: 121.4, + }); + + it('covers the recorded time of moved spans', () => { + const tree = build(makePageload([drifted('1')])); + + expect(tree.root.space[0]).toBeCloseTo((T - 10) * 1e3); + expect(tree.recorded_space[0]).toBeCloseTo((T - 121.0564) * 1e3); + expect(tree.recorded_space[0] + tree.recorded_space[1]).toBeCloseTo( + tree.root.space[0] + tree.root.space[1] + ); + }); + + it('matches the trace space without correction', () => { + const tree = build(makePageload([drifted('1')])); + + tree.setClockDriftCorrection(false, {organization, preferences}); + + expect(tree.recorded_space).toEqual(tree.root.space); + expect(tree.recorded_space[0]).toBeCloseTo((T - 121.0564) * 1e3); + }); + + it('covers the recorded time of moved spans in appended trees', () => { + const tree = build(makePageload([])); + tree.appendTree(build(makePageload([drifted('1')]))); + + expect(tree.recorded_space[0]).toBeCloseTo((T - 121.0564) * 1e3); + expect(tree.recorded_space[0] + tree.recorded_space[1]).toBeCloseTo( + (T + 300) * 1e3 + ); + }); + }); +}); diff --git a/static/app/views/performance/traceDetails/traceModels/clockDriftCorrection.tsx b/static/app/views/performance/traceDetails/traceModels/clockDriftCorrection.tsx new file mode 100644 index 000000000000..76ddec7c2c71 --- /dev/null +++ b/static/app/views/performance/traceDetails/traceModels/clockDriftCorrection.tsx @@ -0,0 +1,291 @@ +import type {Organization} from 'sentry/types/organization'; +import {formatTraceDuration} from 'sentry/utils/duration/formatTraceDuration'; +import {isEAPSpanNode} from 'sentry/views/performance/traceDetails/traceGuards'; + +import type {BaseNode} from './traceTreeNode/baseNode'; +import type {EapSpanNode} from './traceTreeNode/eapSpanNode'; + +/** + * Clock drift smaller than this is not corrected. A few milliseconds of overlap are invisible at + * normal zoom levels, and are within what browsers' coarsened timers can produce on their own, so + * correcting and flagging them would mostly add noise. + */ +export const MIN_CLOCK_DRIFT_CORRECTION_MS = 10; + +/** + * The clock drift icon is part of the span's duration label. The label placement makes room for it, + * so keep these in sync with the icon's styles. + */ +export const CLOCK_DRIFT_ICON_SIZE_PX = 12; // the `xs` icon size +export const CLOCK_DRIFT_ICON_GAP_PX = 4; + +export function hasClockDriftCorrectionFeature( + organization: Organization | null +): boolean { + return ( + organization?.features.includes('trace-waterfall-clock-drift-correction') ?? false + ); +} + +/** + * Formats a signed offset, e.g. `+312.00ms` or `−1.42s`. + */ +export function formatClockDriftOffset(offsetMs: number): string { + const sign = offsetMs < 0 ? '−' : '+'; + return `${sign}${formatTraceDuration(Math.abs(offsetMs))}`; +} + +type ClientServerPair = {client: EapSpanNode; server: EapSpanNode}; + +/** + * A server span continuing a trace from a client span in another process. Their timestamps come + * from different clocks, so they can disagree. + */ +function isClientServerPair(client: EapSpanNode, server: EapSpanNode): boolean { + if (!client.op?.startsWith('http.client') || !server.op?.startsWith('http.server')) { + return false; + } + + // The server span starting a new segment is what tells us the request left the client's + // process. We can't rely on the project or SDK: full-stack frameworks like Next.js report both + // sides under the same project and SDK name. + return server.value.is_transaction; +} + +function getSegment(node: EapSpanNode): BaseNode { + if (node.value.is_transaction) { + return node; + } + // Without a segment, the span is its own group. + return node.findParentEapTransaction() ?? node; +} + +function findClientServerPairs(root: BaseNode): ClientServerPair[] { + const pairs: ClientServerPair[] = []; + + root.forEachChild(node => { + if (!isEAPSpanNode(node)) { + return; + } + for (const child of node.children) { + if (isEAPSpanNode(child) && isClientServerPair(node, child)) { + pairs.push({client: node, server: child}); + } + } + }); + + return pairs; +} + +/** + * Returns the range of shifts (in ms) that would place the server span inside the client span, + * or null if the server span is longer than the client span. A longer server span cannot be + * explained by clock drift (e.g. streaming responses or work after an aborted request), so we + * leave it alone. + */ +export function getAlignmentRange( + clientSpace: [number, number], + serverSpace: [number, number] +): [min: number, max: number] | null { + const [clientStart, clientDuration] = clientSpace; + const [serverStart, serverDuration] = serverSpace; + + const min = clientStart - serverStart; + const max = clientStart + clientDuration - (serverStart + serverDuration); + + return min <= max ? [min, max] : null; +} + +/** + * Picks the smallest shift within the range. We don't center the server span, because the + * request leg (incl. connection setup and CORS preflights) is usually much longer than the + * response leg, so centering would distort more than it fixes. + */ +export function getSmallestShift([min, max]: [number, number]): number { + if (min > 0) { + return min; + } + if (max < 0) { + return max; + } + return 0; +} + +/** + * Whether the shift lies within the range, give or take {@link MIN_CLOCK_DRIFT_CORRECTION_MS}. + * Requests whose ranges miss each other by that much still count as agreeing on a shift: their + * timestamps come from timers with limited precision, so exact agreement is too strict. + */ +function isWithinRange(range: [number, number], shift: number): boolean { + const tolerance = MIN_CLOCK_DRIFT_CORRECTION_MS; + return range[0] - tolerance <= shift && shift <= range[1] + tolerance; +} + +/** + * All requests made from the same process share one clock, so clock drift moves all of them by the + * same amount. We look for the shift that most requests agree on, and only correct the requests + * that agree with it. A request that disagrees is misaligned for another reason (e.g. a retry or a + * reused trace header), which shifting would only hide. + * + * If there is no strict majority, the requests contradict each other and we can't tell which ones + * are off, so we correct none of them. + */ +export function getClockDriftShifts( + ranges: Array<[number, number] | null> +): Array { + const validRanges = ranges.filter((range): range is [number, number] => range !== null); + if (validRanges.length === 0) { + return ranges.map(() => null); + } + + // The best shift is either 0 or at the edge of a range, so these are the only candidates to check + const candidates = [0]; + for (const [min, max] of validRanges) { + candidates.push( + min - MIN_CLOCK_DRIFT_CORRECTION_MS, + max + MIN_CLOCK_DRIFT_CORRECTION_MS + ); + } + + let consensus = 0; + let consensusCount = 0; + for (const candidate of candidates) { + const count = validRanges.filter(range => isWithinRange(range, candidate)).length; + if ( + count > consensusCount || + (count === consensusCount && Math.abs(candidate) < Math.abs(consensus)) + ) { + consensus = candidate; + consensusCount = count; + } + } + + if (consensusCount * 2 <= validRanges.length) { + return ranges.map(() => null); + } + + const agrees = (range: [number, number] | null): range is [number, number] => + range !== null && isWithinRange(range, consensus); + + // Use the smallest shift that fits all agreeing requests exactly. If they only agree within the + // tolerance, split the difference so no request is off by more than the others. + let min = Number.NEGATIVE_INFINITY; + let max = Number.POSITIVE_INFINITY; + for (const range of ranges) { + if (agrees(range)) { + min = Math.max(min, range[0]); + max = Math.min(max, range[1]); + } + } + const shift = min <= max ? getSmallestShift([min, max]) : (min + max) / 2; + + return ranges.map(range => (agrees(range) ? shift : null)); +} + +function shiftSubtree(server: BaseNode, offsetMs: number): void { + const shift = (node: BaseNode) => { + node.space = [node.space[0] + offsetMs, node.space[1]]; + node.clockDriftOffsetMs += offsetMs; + }; + + shift(server); + server.forEachChild(shift); + server.isClockDriftCorrectionRoot = true; +} + +/** + * Moves server subtrees into the client spans that made the requests, if the clocks of both + * sides disagree. Only node spaces change, the original timestamps stay intact. + * + * Must run before autogrouping and missing instrumentation detection, as these derive their + * spaces from the spans. + * + * Returns the number of server subtrees that were moved. + */ +export function applyClockDriftCorrection(root: BaseNode): number { + // Requests are grouped by the segment they were made from. A segment always runs in a single + // process, so all its requests share one clock. A project or SDK does not: NextJS projects run + // on clients and server for example, each with its own clock. + const groups = new Map(); + + for (const pair of findClientServerPairs(root)) { + const key = getSegment(pair.client); + const group = groups.get(key); + if (group) { + group.push(pair); + } else { + groups.set(key, [pair]); + } + } + + let correctedCount = 0; + + // Groups are ordered by their first pair in depth-first order, so a client further up the tree + // is corrected before the services it calls. Ranges are computed per group, after the groups + // before it were shifted. + for (const pairs of groups.values()) { + const ranges = pairs.map(({client, server}) => + getAlignmentRange(client.space, server.space) + ); + const shifts = getClockDriftShifts(ranges); + + for (const [index, {server}] of pairs.entries()) { + const shift = shifts[index] ?? 0; + if (Math.abs(shift) < MIN_CLOCK_DRIFT_CORRECTION_MS) { + continue; + } + shiftSubtree(server, shift); + correctedCount++; + } + } + + return correctedCount; +} + +/** + * The space a node was recorded at, before clock drift correction moved it. Data stored with the + * node, like its profiles and issues, has to be queried by this space, not the one shown. + */ +export function getRecordedSpace(node: BaseNode): [start: number, duration: number] { + return [node.space[0] - node.clockDriftOffsetMs, node.space[1]]; +} + +/** + * The range the node and its descendants were recorded in. Clock drift correction can move + * descendants away from the node, so the node's own recorded space may not cover them, e.g. for + * the trace node. + */ +export function getRecordedSubtreeSpace( + node: BaseNode +): [start: number, duration: number] { + const [recordedStart, recordedDuration] = getRecordedSpace(node); + let start = recordedStart; + let end = recordedStart + recordedDuration; + + node.forEachChild(child => { + if (child.clockDriftOffsetMs === 0) { + return; + } + const [childStart, childDuration] = getRecordedSpace(child); + start = Math.min(start, childStart); + end = Math.max(end, childStart + childDuration); + }); + + return [start, end - start]; +} + +/** + * Restores the original spaces of all nodes moved by {@link applyClockDriftCorrection}. + */ +export function removeClockDriftCorrection(root: BaseNode): void { + const restore = (node: BaseNode) => { + node.isClockDriftCorrectionRoot = false; + if (node.clockDriftOffsetMs !== 0) { + node.space = getRecordedSpace(node); + node.clockDriftOffsetMs = 0; + } + }; + + restore(root); + root.forEachChild(restore); +} diff --git a/static/app/views/performance/traceDetails/traceModels/issuesTraceTree.tsx b/static/app/views/performance/traceDetails/traceModels/issuesTraceTree.tsx index ab87a7d3644b..15f20cda7ed4 100644 --- a/static/app/views/performance/traceDetails/traceModels/issuesTraceTree.tsx +++ b/static/app/views/performance/traceDetails/traceModels/issuesTraceTree.tsx @@ -1,7 +1,7 @@ import type {Event} from 'sentry/types/event'; import type {Organization} from 'sentry/types/organization'; import type {HydratedReplayRecord} from 'sentry/views/explore/replays/types'; -import type {TracePreferencesState} from 'sentry/views/performance/traceDetails/traceState/tracePreferences'; +import type {TraceTreePreferences} from 'sentry/views/performance/traceDetails/traceState/tracePreferences'; import type {BaseNode} from './traceTreeNode/baseNode'; import {CollapsedNode} from './traceTreeNode/collapsedNode'; @@ -38,7 +38,7 @@ export class IssuesTraceTree extends TraceTree { options: { organization: Organization; replay: HydratedReplayRecord | null; - preferences?: Pick; + preferences?: TraceTreePreferences; } ): IssuesTraceTree { const baseTree = super.FromTrace(trace, options); diff --git a/static/app/views/performance/traceDetails/traceModels/traceTree.tsx b/static/app/views/performance/traceDetails/traceModels/traceTree.tsx index 190ebf920c5f..863a73f25c76 100644 --- a/static/app/views/performance/traceDetails/traceModels/traceTree.tsx +++ b/static/app/views/performance/traceDetails/traceModels/traceTree.tsx @@ -31,7 +31,7 @@ import { isTraceError, isUptimeCheck, } from 'sentry/views/performance/traceDetails/traceGuards'; -import type {TracePreferencesState} from 'sentry/views/performance/traceDetails/traceState/tracePreferences'; +import type {TraceTreePreferences} from 'sentry/views/performance/traceDetails/traceState/tracePreferences'; import type {BaseNode} from './traceTreeNode/baseNode'; import {EapSpanNode} from './traceTreeNode/eapSpanNode'; @@ -44,6 +44,11 @@ import {SiblingAutogroupNode} from './traceTreeNode/siblingAutogroupNode'; import {TraceNode} from './traceTreeNode/traceNode'; import {UptimeCheckNode} from './traceTreeNode/uptimeCheckNode'; import {traceChronologicalSort} from './traceTreeNode/utils'; +import { + applyClockDriftCorrection, + getRecordedSubtreeSpace, + removeClockDriftCorrection, +} from './clockDriftCorrection'; import {makeExampleTraceData} from './makeExampleTraceData'; import { collectTraceMeasurements, @@ -324,6 +329,10 @@ function fetchTrace( export class TraceTree extends TraceTreeEventDispatcher { collapsed_nodes = 0; eap_spans_count = 0; + /** + * The number of server spans moved to correct for clock drift, along with their subtrees. + */ + clock_drift_correction_count = 0; projects = new Map(); type: 'loading' | 'empty' | 'error' | 'trace' = 'trace'; @@ -337,6 +346,18 @@ export class TraceTree extends TraceTreeEventDispatcher { list: BaseNode[] = []; + /** + * The start and end of the replay the trace belongs to, in milliseconds. The trace space always + * covers it. + */ + replay_bounds: [start: number, end: number] | null = null; + + /** + * The range the spans of the trace were recorded in. Clock drift correction can move spans out + * of it, so the root space no longer covers them. Query data stored with the spans by this range. + */ + recorded_space: [start: number, duration: number] = [0, 0]; + static MISSING_INSTRUMENTATION_THRESHOLD_MS = 100; static Empty() { @@ -367,10 +388,7 @@ export class TraceTree extends TraceTreeEventDispatcher { static ApplyPreferences( root: BaseNode, - options: { - organization: Organization; - preferences?: Pick; - } + options: {organization: Organization; preferences?: TraceTreePreferences} ): void { if (options?.preferences?.missing_instrumentation) { TraceTree.DetectMissingInstrumentation(root); @@ -390,7 +408,7 @@ export class TraceTree extends TraceTreeEventDispatcher { options: { organization: Organization; replay: HydratedReplayRecord | null; - preferences?: Pick; + preferences?: TraceTreePreferences; // This is used to track the traceslug associated with a trace in a replay. // This is necessary because a replay has multiple traces and the current ui requires // us to merge them into one trace. We still need to keep track of the original traceSlug @@ -466,15 +484,35 @@ export class TraceTree extends TraceTreeEventDispatcher { visit(traceNode, item); } - // At this point, the tree is built, we need iterate over it again to collect all of the - // measurements, web vitals, errors and perf issues as well as calculate the min and max space - // the trace should take up. - const traceSpaceBounds = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]; - + // Moves the pageload of a server rendered page above the server handler that rendered it. traceNode.forEachChild(c => { - traceSpaceBounds[0] = Math.min(traceSpaceBounds[0]!, c.space[0]); - traceSpaceBounds[1] = Math.max(traceSpaceBounds[1]!, c.space[0] + c.space[1]); + if ( + c.parent && + c.op === 'pageload' && + c.parent.op === 'http.server' && + c.parent.directVisibleChildren.filter(child => child.op === 'pageload').length === + 1 + ) { + // The swap can occur at a later point when new transactions are fetched, + // which means we need to invalidate the tree and re-render the UI. + const parent = c.parent.parent; + TraceTree.Swap({parent: c.parent, child: c, reason: 'pageload server handler'}); + parent!.invalidate(); + parent!.forEachChild(child => { + child.invalidate(); + }); + } + }); + + // Runs before we compute the trace space, so it does not stretch to where the misaligned + // spans were recorded, and after the pageload swap, so it sees the same tree as a later toggle. + if (options.preferences?.clock_drift_correction) { + tree.clock_drift_correction_count = applyClockDriftCorrection(tree.root); + } + // At this point, the tree is built, we need iterate over it again to collect all of the + // measurements, web vitals, errors and perf issues. + traceNode.forEachChild(c => { for (const error of c.errors) { traceNode.errors.add(error); } @@ -495,23 +533,6 @@ export class TraceTree extends TraceTreeEventDispatcher { ) ); } - - if ( - c.parent && - c.op === 'pageload' && - c.parent.op === 'http.server' && - c.parent.directVisibleChildren.filter(child => child.op === 'pageload').length === - 1 - ) { - // // The swap can occur at a later point when new transactions are fetched, - // // which means we need to invalidate the tree and re-render the UI. - const parent = c.parent.parent; - TraceTree.Swap({parent: c.parent, child: c, reason: 'pageload server handler'}); - parent!.invalidate(); - parent!.forEachChild(child => { - child.invalidate(); - }); - } }); // The sum of all durations of traces that exist under a replay is not always @@ -519,44 +540,106 @@ export class TraceTree extends TraceTreeEventDispatcher { // to ensure that we can see the max of the replay duration and the sum(trace durations). This way, we // can ensure that the replay timestamp indicators are always visible in the traceview along with all spans from the traces. if (options.replay) { - const replayStart = options.replay.started_at.getTime(); - const replayEnd = options.replay.finished_at.getTime(); + tree.replay_bounds = [ + options.replay.started_at.getTime(), + options.replay.finished_at.getTime(), + ]; + } + + tree.refreshTraceSpace(); + + tree.indicators.sort((a, b) => a.start - b.start); + + TraceTree.AddServerRenderPlaceholders(tree.root); + + TraceTree.ApplyPreferences(tree.root, options); + + return tree; + } - traceSpaceBounds[0] = Math.min(traceSpaceBounds[0]!, replayStart); - traceSpaceBounds[1] = Math.max(traceSpaceBounds[1]!, replayEnd); + /** + * Computes the trace space from its nodes, indicators and replay, e.g. again after clock drift + * correction moved some of the nodes. + */ + refreshTraceSpace(): void { + let start = Number.POSITIVE_INFINITY; + let end = Number.NEGATIVE_INFINITY; + + const include = (node: BaseNode) => { + start = Math.min(start, node.space[0]); + end = Math.max(end, node.space[0] + node.space[1]); + }; + for (const traceNode of this.root.children) { + traceNode.forEachChild(include); } - for (const indicator of tree.indicators) { - // If any indicator starts after the trace ends, set end to the indicator start - if (indicator.start > traceSpaceBounds[1]!) { - traceSpaceBounds[1] = indicator.start; - } - // If an indicator starts before the trace start, set start to the indicator start - if (indicator.start < traceSpaceBounds[0]!) { - traceSpaceBounds[0] = indicator.start; - } + for (const indicator of this.indicators) { + start = Math.min(start, indicator.start); + end = Math.max(end, indicator.start); + } + + if (this.replay_bounds) { + start = Math.min(start, this.replay_bounds[0]); + end = Math.max(end, this.replay_bounds[1]); } // Space needs a start and end, if we don't have one we can't construct a timeline. - if (!Number.isFinite(traceSpaceBounds[0])) { - traceSpaceBounds[0] = 0; + if (!Number.isFinite(start)) { + start = 0; } - if (!Number.isFinite(traceSpaceBounds[1])) { - traceSpaceBounds[1] = 0; + if (!Number.isFinite(end)) { + end = 0; } - const space = [traceSpaceBounds[0]!, traceSpaceBounds[1]! - traceSpaceBounds[0]!]; + const changed = this.root.space[0] !== start || this.root.space[1] !== end - start; - tree.root.space = [space[0]!, space[1]!]; - traceNode.space = [space[0]!, space[1]!]; + this.root.space = [start, end - start]; + for (const traceNode of this.root.children) { + traceNode.space = [start, end - start]; + } + this.recorded_space = + this.clock_drift_correction_count > 0 + ? getRecordedSubtreeSpace(this.root) + : [start, end - start]; - tree.indicators.sort((a, b) => a.start - b.start); + if (changed) { + this.dispatch('trace timeline change', this.root.space); + } + } - TraceTree.AddServerRenderPlaceholders(tree.root); + /** + * Applies or removes clock drift correction. Autogroups and missing instrumentation spans derive + * their spaces from the spans it moves, so they are taken out and added back once the spans are + * in place. Returns the number of corrected spans. + */ + setClockDriftCorrection( + enabled: boolean, + options: {organization: Organization; preferences: TraceTreePreferences} + ): number { + const {autogroup, missing_instrumentation} = options.preferences; - TraceTree.ApplyPreferences(tree.root, options); + if (autogroup.sibling) { + TraceTree.RemoveSiblingAutogroupNodes(this.root); + } + if (autogroup.parent) { + TraceTree.RemoveDirectChildrenAutogroupNodes(this.root); + } + if (missing_instrumentation) { + TraceTree.RemoveMissingInstrumentationNodes(this.root); + } - return tree; + if (enabled) { + this.clock_drift_correction_count = applyClockDriftCorrection(this.root); + } else { + removeClockDriftCorrection(this.root); + this.clock_drift_correction_count = 0; + } + + TraceTree.ApplyPreferences(this.root, options); + + this.refreshTraceSpace(); + + return this.clock_drift_correction_count; } appendTree(tree: TraceTree) { @@ -584,6 +667,8 @@ export class TraceTree extends TraceTreeEventDispatcher { this.profiled_events.add(profiledEvent); } + this.clock_drift_correction_count += tree.clock_drift_correction_count; + for (const [node, vitals] of tree.vitals) { this.vitals.set(node, vitals); } @@ -631,6 +716,13 @@ export class TraceTree extends TraceTreeEventDispatcher { this.dispatch('trace timeline change', this.root.space); } + const recordedStart = Math.min(this.recorded_space[0], tree.recorded_space[0]); + const recordedEnd = Math.max( + this.recorded_space[0] + this.recorded_space[1], + tree.recorded_space[0] + tree.recorded_space[1] + ); + this.recorded_space = [recordedStart, recordedEnd - recordedStart]; + for (const child of tree.root.children) { this.list = this.list.concat(child.visibleChildren); } @@ -839,6 +931,7 @@ export class TraceTree extends TraceTreeEventDispatcher { end = Math.max(end, tail.space[0] + tail.space[1]); autoGroupedNode.space = [start, end - start]; + autoGroupedNode.clockDriftOffsetMs = head.clockDriftOffsetMs; autoGroupedNode.errors = new Set(errors); autoGroupedNode.occurrences = new Set(occurrences); @@ -979,6 +1072,7 @@ export class TraceTree extends TraceTreeEventDispatcher { } autoGroupedNode.space = [start_timestamp, timestamp - start_timestamp]; + autoGroupedNode.clockDriftOffsetMs = current.clockDriftOffsetMs; node.children.splice(start, matchCount + 1, autoGroupedNode); index = start + 1; @@ -1293,7 +1387,7 @@ export class TraceTree extends TraceTreeEventDispatcher { replayTraces: ReplayTrace[]; rerender: () => void; urlParams: Location['query']; - preferences?: Pick; + preferences?: TraceTreePreferences; }): () => void { let cancelled = false; const {organization, api, urlParams, filters, rerender, replayTraces} = options; diff --git a/static/app/views/performance/traceDetails/traceModels/traceTreeNode/baseNode.tsx b/static/app/views/performance/traceDetails/traceModels/traceTreeNode/baseNode.tsx index 90dbb1c6a0ca..f2fff19448da 100644 --- a/static/app/views/performance/traceDetails/traceModels/traceTreeNode/baseNode.tsx +++ b/static/app/views/performance/traceDetails/traceModels/traceTreeNode/baseNode.tsx @@ -79,6 +79,18 @@ export abstract class BaseNode()( '/organizations/$organizationIdOrSlug/events/', diff --git a/static/app/views/performance/traceDetails/tracePreferencesDropdown.tsx b/static/app/views/performance/traceDetails/tracePreferencesDropdown.tsx index 0a10c68ee8b7..ac412c9ed17e 100644 --- a/static/app/views/performance/traceDetails/tracePreferencesDropdown.tsx +++ b/static/app/views/performance/traceDetails/tracePreferencesDropdown.tsx @@ -1,4 +1,4 @@ -import {useCallback, useMemo} from 'react'; +import {Fragment, useCallback, useMemo} from 'react'; import type {Placement} from '@floating-ui/react-dom'; import {IconSettings} from '@sentry/icons/settings'; @@ -10,8 +10,9 @@ import { import {ExternalLink} from '@sentry/scraps/link'; import {useModal} from '@sentry/scraps/modal'; import {OverlayTrigger} from '@sentry/scraps/overlayTrigger'; +import {Text} from '@sentry/scraps/text'; -import {t, tct} from 'sentry/locale'; +import {t, tct, tn} from 'sentry/locale'; import type {Project} from 'sentry/types/project'; import {getAttributeValue} from 'sentry/utils/fields/getAttributeValue'; import {useOrganization} from 'sentry/utils/useOrganization'; @@ -20,15 +21,19 @@ import {OurLogKnownFieldKey} from 'sentry/views/explore/logs/types'; import type {TraceRootEventQueryResults} from './traceApi/useTraceRootEvent'; import {isTraceItemDetailsResponse} from './traceApi/utils'; +import {hasClockDriftCorrectionFeature} from './traceModels/clockDriftCorrection'; import {traceAnalytics} from './traceAnalytics'; import {getCustomInstrumentationLink} from './traceConfigurations'; import {TraceShortcutsModal} from './traceShortcutsModal'; interface TracePreferencesDropdownProps { autogroup: boolean; + clockDriftCorrection: boolean; + clockDriftCorrectionCount: number; compressedTimeline: boolean; missingInstrumentation: boolean; onAutogroupChange: () => void; + onClockDriftCorrectionChange: () => void; onCompressedTimelineChange: () => void; onMissingInstrumentationChange: () => void; rootEventResults: TraceRootEventQueryResults; @@ -68,6 +73,33 @@ export function TracePreferencesDropdown(props: TracePreferencesDropdownProps) { value: 'compressed-timeline', details: t('Collapses long inactive gaps in the waterfall timeline.'), }, + ...(hasClockDriftCorrectionFeature(organization) + ? [ + { + label: t('Clock Drift Correction'), + value: 'clock-drift-correction', + details: ( + + {t( + 'Shifts server spans into the client requests that made them, when the clocks of the client and the server disagree.' + )} + {props.clockDriftCorrectionCount > 0 && ( + + {' '} + + {tn( + 'Adjusted %s span in this trace.', + 'Adjusted %s spans in this trace.', + props.clockDriftCorrectionCount + )} + + + )} + + ), + }, + ] + : []), ]; const values = useMemo(() => { @@ -81,8 +113,16 @@ export function TracePreferencesDropdown(props: TracePreferencesDropdownProps) { if (props.compressedTimeline) { value.push('compressed-timeline'); } + if (props.clockDriftCorrection) { + value.push('clock-drift-correction'); + } return value; - }, [props.autogroup, props.compressedTimeline, props.missingInstrumentation]); + }, [ + props.autogroup, + props.clockDriftCorrection, + props.compressedTimeline, + props.missingInstrumentation, + ]); const fallbackPlacements = props.fallbackPlacements; const flipOptions = useMemo( @@ -93,6 +133,7 @@ export function TracePreferencesDropdown(props: TracePreferencesDropdownProps) { const onAutogroupChange = props.onAutogroupChange; const onMissingInstrumentationChange = props.onMissingInstrumentationChange; const onCompressedTimelineChange = props.onCompressedTimelineChange; + const onClockDriftCorrectionChange = props.onClockDriftCorrectionChange; const onChange = useCallback( (newValues: Array>) => { @@ -109,6 +150,9 @@ export function TracePreferencesDropdown(props: TracePreferencesDropdownProps) { if (newOption === 'compressed-timeline') { onCompressedTimelineChange(); } + if (newOption === 'clock-drift-correction') { + onClockDriftCorrectionChange(); + } } if (values.length > newValuesArray.length) { @@ -122,11 +166,15 @@ export function TracePreferencesDropdown(props: TracePreferencesDropdownProps) { if (removedOption === 'compressed-timeline') { onCompressedTimelineChange(); } + if (removedOption === 'clock-drift-correction') { + onClockDriftCorrectionChange(); + } } }, [ values, onAutogroupChange, + onClockDriftCorrectionChange, onCompressedTimelineChange, onMissingInstrumentationChange, ] diff --git a/static/app/views/performance/traceDetails/traceRenderers/virtualizedViewManager.spec.tsx b/static/app/views/performance/traceDetails/traceRenderers/virtualizedViewManager.spec.tsx index 4116d041f6d8..abbc4e31b4a0 100644 --- a/static/app/views/performance/traceDetails/traceRenderers/virtualizedViewManager.spec.tsx +++ b/static/app/views/performance/traceDetails/traceRenderers/virtualizedViewManager.spec.tsx @@ -1,5 +1,9 @@ import {ThemeFixture} from 'sentry-fixture/theme'; +import { + CLOCK_DRIFT_ICON_GAP_PX, + CLOCK_DRIFT_ICON_SIZE_PX, +} from 'sentry/views/performance/traceDetails/traceModels/clockDriftCorrection'; import type {TraceTree} from 'sentry/views/performance/traceDetails/traceModels/traceTree'; import type {BaseNode} from 'sentry/views/performance/traceDetails/traceModels/traceTreeNode/baseNode'; @@ -390,6 +394,106 @@ describe('VirtualizedViewManger', () => { expect(placement.edge).toBe('end'); expect(placement.anchorTimestamp).toBe(200); }); + + it('moves span issue icons with the view', () => { + const manager = new VirtualizedViewManager( + {list: {width: 0}, span_list: {width: 1}}, + new TraceScheduler(), + new TraceView(), + ThemeFixture() + ); + + manager.view.setTraceSpace([0, 0, 1000, 1]); + manager.view.setTracePhysicalSpace([0, 0, 1000, 1], [0, 0, 1000, 1]); + + const error = { + event_id: 'error', + issue_id: 1, + level: 'error', + start_timestamp: 0.15, + }; + const node = { + value: {errors: [error], occurrences: []}, + errors: new Set([error]), + occurrences: new Set(), + space: [100, 100], + clockDriftOffsetMs: 0, + } as unknown as BaseNode; + + // As placed by its row while the view was zoomed in left of the span + const icon = document.createElement('div'); + icon.className = 'TraceIcon TraceIconEnd'; + icon.style.left = '0%'; + const bar = document.createElement('div'); + bar.appendChild(icon); + + manager.registerColumnRef('list', document.createElement('div'), 0, node); + manager.registerSpanBarRef(bar, node.space, 'red', 0); + manager.draw(); + + expect(icon).toHaveStyle({left: '50%'}); + expect(icon).not.toHaveClass('TraceIconEnd'); + }); + }); + + describe('span text placement', () => { + function makeNode(clockDriftOffsetMs = 0): BaseNode { + return { + errors: new Set(), + occurrences: new Set(), + clockDriftOffsetMs, + isClockDriftCorrectionRoot: clockDriftOffsetMs !== 0, + } as unknown as BaseNode; + } + + function makeManager() { + const manager = new VirtualizedViewManager( + {list: {width: 0}, span_list: {width: 1}}, + new TraceScheduler(), + new TraceView(), + ThemeFixture() + ); + + manager.view.setTraceSpace([0, 0, 1000, 1]); + manager.view.setTracePhysicalSpace([0, 0, 1000, 1], [0, 0, 1000, 1]); + manager.recomputeSpanToPXMatrix(); + return manager; + } + + const shifted = makeNode(100); + + it('makes room for the clock drift icon when placing the text left of the span', () => { + const manager = makeManager(); + // The span is in the right half, so the text is placed left of it + const span: [number, number] = [800, 100]; + + const [insideWithout, withoutIcon] = manager.computeSpanTextPlacement( + makeNode(), + span, + '100.00ms' + ); + const [insideWith, withIcon] = manager.computeSpanTextPlacement( + shifted, + span, + '100.00ms' + ); + + expect(insideWithout).toBe(0); + expect(insideWith).toBe(0); + expect(withoutIcon! - withIcon!).toBe( + CLOCK_DRIFT_ICON_SIZE_PX + CLOCK_DRIFT_ICON_GAP_PX + ); + }); + + it('keeps the text in place when placing it right of the span', () => { + const manager = makeManager(); + // The span is in the left half, so the text is placed right of it, starting with the icon + const span: [number, number] = [100, 100]; + + expect(manager.computeSpanTextPlacement(shifted, span, '100.00ms')).toEqual( + manager.computeSpanTextPlacement(makeNode(), span, '100.00ms') + ); + }); }); describe('isTimestampInsideCollapsedGap', () => { diff --git a/static/app/views/performance/traceDetails/traceRenderers/virtualizedViewManager.tsx b/static/app/views/performance/traceDetails/traceRenderers/virtualizedViewManager.tsx index 7e8b51bee098..29c29bf0f26a 100644 --- a/static/app/views/performance/traceDetails/traceRenderers/virtualizedViewManager.tsx +++ b/static/app/views/performance/traceDetails/traceRenderers/virtualizedViewManager.tsx @@ -24,6 +24,10 @@ import { getTraceIssueTimestamp, TRACE_ICON_WIDTH, } from 'sentry/views/performance/traceDetails/traceIssueUtils'; +import { + CLOCK_DRIFT_ICON_GAP_PX, + CLOCK_DRIFT_ICON_SIZE_PX, +} from 'sentry/views/performance/traceDetails/traceModels/clockDriftCorrection'; import {TraceTree} from 'sentry/views/performance/traceDetails/traceModels/traceTree'; import type {BaseNode} from 'sentry/views/performance/traceDetails/traceModels/traceTreeNode/baseNode'; @@ -1449,7 +1453,7 @@ export class VirtualizedViewManager { this.time_compression.toCompressedOffset( this.view.to_origin + this.view.trace_space.width * 0.5 ); - const text_width = this.text_measurer.measure(text); + const text_width = this.text_measurer.measure(text) + getLabelIconWidthPx(node); const text_width_ceil = Math.ceil(text_width); const timestamps = getIconTimestamps( @@ -1703,6 +1707,7 @@ export class VirtualizedViewManager { } this.drawSpanBar(this.span_bars[i]); + this.drawIssueIcons(span.ref, this.columns.list.column_nodes[i]); this.drawSpanText(this.span_text[i], this.columns.list.column_nodes[i]); this.drawSpanArrow(this.span_arrows[i], false, 0); } @@ -2235,7 +2240,15 @@ export class VirtualizedViewManager { } } - private drawAutogroupIssueIcons(ref: HTMLElement, node: BaseNode) { + /** + * Icons are placed relative to the view when their row renders. Redraw them with the bars, so + * they stay in place while the user zooms or pans, as the duration label makes room for them. + */ + private drawIssueIcons(ref: HTMLElement, node: BaseNode | undefined) { + if (!node || (!node.errors.size && !node.occurrences.size)) { + return; + } + const icons = Array.from(ref.children).filter( (child): child is HTMLElement => child instanceof HTMLElement && @@ -2266,7 +2279,7 @@ export class VirtualizedViewManager { this.text_measurer.measure(text) ); const {edge, anchorTimestamp} = this.computeTraceIconPlacement( - getTraceIssueTimestamp(issue, node.space), + getTraceIssueTimestamp(issue, node.space, node.clockDriftOffsetMs), width, node.space ); @@ -2298,7 +2311,7 @@ export class VirtualizedViewManager { }%`; bar.style.width = `${this.computeRelativeWidth(space, node.space) * 100}%`; }); - this.drawAutogroupIssueIcons(invisible_bar.ref, node); + this.drawIssueIcons(invisible_bar.ref, node); } } @@ -2332,6 +2345,15 @@ export class VirtualizedViewManager { } } +/** + * The width of icons rendered inside the duration label, in addition to its text. + */ +function getLabelIconWidthPx(node: BaseNode): number { + return node.isClockDriftCorrectionRoot + ? CLOCK_DRIFT_ICON_SIZE_PX + CLOCK_DRIFT_ICON_GAP_PX + : 0; +} + // Computes a min and max icon timestamp. This effectively extends or reduces the hitbox // of the span to include the icon. We need this because when the icon is close to the edge // it can extend it and cause overlaps with duration labels @@ -2360,7 +2382,7 @@ function getIconTimestamps( additionalIssueCount === undefined ? TRACE_ICON_WIDTH : getTraceIconGroupWidth(additionalIssueCount, measureText); - const timestamp = getTraceIssueTimestamp(issue, span_space); + const timestamp = getTraceIssueTimestamp(issue, span_space, node.clockDriftOffsetMs); const {bounds} = getTraceIconPlacement(timestamp, icon_width_px); const [icon_left, icon_right] = bounds; diff --git a/static/app/views/performance/traceDetails/traceRow/traceBackgroundPatterns.spec.tsx b/static/app/views/performance/traceDetails/traceRow/traceBackgroundPatterns.spec.tsx index 9aaf5456476c..452b723765e4 100644 --- a/static/app/views/performance/traceDetails/traceRow/traceBackgroundPatterns.spec.tsx +++ b/static/app/views/performance/traceDetails/traceRow/traceBackgroundPatterns.spec.tsx @@ -59,4 +59,37 @@ describe('TraceBackgroundPatterns', () => { expect(screen.getByTestId('trace-issue-pattern')).toBeInTheDocument(); }); + + it('places the pattern of a node shifted for clock drift at the shifted timestamp', () => { + const occurrence = makeEAPOccurrence({ + event_id: 'shifted-occurrence', + issue_id: 1, + start_timestamp: 1, + }); + const node = { + value: makeEAPSpan({errors: [], occurrences: [occurrence]}), + errors: new Set(), + occurrences: new Set([occurrence]), + clockDriftOffsetMs: 2_000, + } as unknown as BaseNode; + const computeRelativeLeftPositionFromOrigin = jest.fn(() => 0.5); + + render( + + ); + + // Recorded at 1000ms, shown 2000ms later along with its span + expect(computeRelativeLeftPositionFromOrigin).toHaveBeenCalledWith( + 3_000, + [2_500, 5_000] + ); + }); }); diff --git a/static/app/views/performance/traceDetails/traceRow/traceBackgroundPatterns.tsx b/static/app/views/performance/traceDetails/traceRow/traceBackgroundPatterns.tsx index f12999f10ca3..f924f16a6b93 100644 --- a/static/app/views/performance/traceDetails/traceRow/traceBackgroundPatterns.tsx +++ b/static/app/views/performance/traceDetails/traceRow/traceBackgroundPatterns.tsx @@ -89,10 +89,12 @@ export function TraceBackgroundPatterns(props: BackgroundPatternsProps) { ) : occurrences.length > 0 ? ( {occurrences.map((occurrence, i) => { + // The node's space is shifted for clock drift, but its occurrences keep their recorded + // timestamps, so shift them by the same offset to place them on the bar. const timestamp = - 'start_timestamp' in occurrence + ('start_timestamp' in occurrence ? occurrence.start_timestamp * 1e3 - : occurrence.start * 1e3; + : occurrence.start * 1e3) + props.node.clockDriftOffsetMs; // Clamp the issue timestamp to the span's timestamp const left = props.manager.computeRelativeLeftPositionFromOrigin( clamp( diff --git a/static/app/views/performance/traceDetails/traceRow/traceBar.spec.tsx b/static/app/views/performance/traceDetails/traceRow/traceBar.spec.tsx index 89411fb05cb7..07d3b09342ea 100644 --- a/static/app/views/performance/traceDetails/traceRow/traceBar.spec.tsx +++ b/static/app/views/performance/traceDetails/traceRow/traceBar.spec.tsx @@ -2,7 +2,7 @@ import {useLayoutEffect, type PropsWithChildren} from 'react'; import {OrganizationFixture} from 'sentry-fixture/organization'; import {ThemeFixture} from 'sentry-fixture/theme'; -import {act, render, screen} from 'sentry-test/reactTestingLibrary'; +import {act, render, screen, userEvent} from 'sentry-test/reactTestingLibrary'; import { isParentAutogroupedNode, @@ -261,6 +261,41 @@ describe.each([false, true])('AutogroupedTraceBar with compression=%s', compress ); }); +describe('AutogroupedTraceBar clock drift', () => { + it('explains the shift of a group moved to correct for clock drift', async () => { + const spanSpaces: Array<[number, number]> = [ + [1000, 400], + [1600, 400], + ]; + const manager = createManager({compressed: false, spanSpaces}); + const node = new SiblingAutogroupNode(null, makeSiblingAutogroup(), { + organization: OrganizationFixture(), + }); + node.space = [1000, 1000]; + node.clockDriftOffsetMs = 2_000; + manager.columns.list.column_nodes[0] = node; + + render( + + ); + + await userEvent.hover(screen.getByText('1.00s')); + + expect( + await screen.findByText('Shifted by +2.00s to correct for clock drift') + ).toBeInTheDocument(); + }); +}); + describe.each(['sibling', 'parent'] as const)('AutogroupedTraceBar (%s)', grouping => { it.each(['none', 'error', 'occurrence', 'combined'] as const)( 'redraws segments and %s issues when compression changes after render', diff --git a/static/app/views/performance/traceDetails/traceRow/traceBar.tsx b/static/app/views/performance/traceDetails/traceRow/traceBar.tsx index eb08f2d7a7ec..dbb4bc7e32ea 100644 --- a/static/app/views/performance/traceDetails/traceRow/traceBar.tsx +++ b/static/app/views/performance/traceDetails/traceRow/traceBar.tsx @@ -1,6 +1,10 @@ import {Fragment, useCallback} from 'react'; import {formatTraceDuration} from 'sentry/utils/duration/formatTraceDuration'; +import { + ClockDriftLabelIcon, + ClockDriftTooltip, +} from 'sentry/views/performance/traceDetails/clockDriftIndicators'; import type {BaseNode} from 'sentry/views/performance/traceDetails/traceModels/traceTreeNode/baseNode'; import type {VirtualizedViewManager} from 'sentry/views/performance/traceDetails/traceRenderers/virtualizedViewManager'; @@ -165,9 +169,12 @@ export function TraceBar(props: TraceBarProps) { /> ) : null} -
- {duration} -
+ +
+ + {duration} +
+
); } @@ -264,9 +271,11 @@ export function AutogroupedTraceBar(props: AutogroupedTraceBarProps) { /> ) : null} -
- {duration} -
+ +
+ {duration} +
+
); } diff --git a/static/app/views/performance/traceDetails/traceRow/traceIcons.tsx b/static/app/views/performance/traceDetails/traceRow/traceIcons.tsx index b3be438be4c0..cf56eefadc55 100644 --- a/static/app/views/performance/traceDetails/traceRow/traceIcons.tsx +++ b/static/app/views/performance/traceDetails/traceRow/traceIcons.tsx @@ -38,7 +38,11 @@ export function TraceIssueIcons(props: TraceIssueIconsProps) { return ( {issues.map(({issue, additionalIssueCount}, i) => { - const timestamp = getTraceIssueTimestamp(issue, node_space); + const timestamp = getTraceIssueTimestamp( + issue, + node_space, + props.node.clockDriftOffsetMs + ); const className = getTraceIssueSeverityClassName(issue); if (additionalIssueCount !== undefined) { diff --git a/static/app/views/performance/traceDetails/traceState/tracePreferences.tsx b/static/app/views/performance/traceDetails/traceState/tracePreferences.tsx index 8347e4f23e45..82e74594626e 100644 --- a/static/app/views/performance/traceDetails/traceState/tracePreferences.tsx +++ b/static/app/views/performance/traceDetails/traceState/tracePreferences.tsx @@ -13,6 +13,7 @@ type TracePreferencesAction = | {payload: boolean; type: 'minimize drawer'} | {payload: boolean; type: 'set missing instrumentation'} | {payload: boolean; type: 'set compressed timeline'} + | {payload: boolean; type: 'set clock drift correction'} | {payload: boolean; type: 'set autogrouping'}; type TraceDrawerPreferences = { @@ -23,6 +24,7 @@ type TraceDrawerPreferences = { export type TracePreferencesState = { autogroup: {parent: boolean; sibling: boolean}; + clock_drift_correction: boolean; compressed_timeline: boolean; drawer: TraceDrawerPreferences; layout: TraceLayoutPreferences; @@ -34,9 +36,19 @@ type StoredTracePreferences = { autogroup: TracePreferencesState['autogroup']; drawer_layout: TraceLayoutPreferences; missing_instrumentation: boolean; + clock_drift_correction?: boolean; compressed_timeline?: boolean; }; +/** + * The preferences that change the structure or timing of a trace tree. + */ +export type TraceTreePreferences = Pick< + TracePreferencesState, + 'autogroup' | 'missing_instrumentation' +> & + Partial>; + export const TRACE_DRAWER_DEFAULT_SIZES: TraceDrawerPreferences['sizes'] = { 'drawer left': 0.4, 'drawer right': 0.4, @@ -52,6 +64,7 @@ export const DEFAULT_TRACE_VIEW_PREFERENCES: TracePreferencesState = { autogroup: {parent: true, sibling: true}, missing_instrumentation: false, compressed_timeline: true, + clock_drift_correction: false, layout: 'drawer right', list: {width: 0.5}, }; @@ -65,6 +78,7 @@ export function storeTraceViewPreferences( missing_instrumentation: state.missing_instrumentation, autogroup: state.autogroup, compressed_timeline: state.compressed_timeline, + clock_drift_correction: state.clock_drift_correction, }; // Make sure we dont fire this during a render phase @@ -154,6 +168,8 @@ export function getInitialTracePreferences( preferences.autogroup = stored.autogroup; preferences.missing_instrumentation = stored.missing_instrumentation; preferences.layout = stored.drawer_layout; + preferences.clock_drift_correction = + stored.clock_drift_correction ?? default_state.clock_drift_correction; if (source === 'issues' || source === 'replay') { preferences.compressed_timeline = false; @@ -194,6 +210,8 @@ export function tracePreferencesReducer( return {...state, missing_instrumentation: action.payload}; case 'set compressed timeline': return {...state, compressed_timeline: action.payload}; + case 'set clock drift correction': + return {...state, clock_drift_correction: action.payload}; case 'set list width': return {...state, list: {width: clamp(action.payload, 0.1, 0.9)}}; default: diff --git a/static/app/views/performance/traceDetails/traceState/traceStateProvider.spec.tsx b/static/app/views/performance/traceDetails/traceState/traceStateProvider.spec.tsx index c2b601cb6041..ac0c1812d946 100644 --- a/static/app/views/performance/traceDetails/traceState/traceStateProvider.spec.tsx +++ b/static/app/views/performance/traceDetails/traceState/traceStateProvider.spec.tsx @@ -1,9 +1,16 @@ -import {render, screen} from 'sentry-test/reactTestingLibrary'; +import {OrganizationFixture} from 'sentry-fixture/organization'; + +import {render, screen, waitFor} from 'sentry-test/reactTestingLibrary'; import {setWindowLocation} from 'sentry-test/utils'; import {DEFAULT_TRACE_VIEW_PREFERENCES} from './tracePreferences'; import {TraceStateProvider, useTraceState} from './traceStateProvider'; +function ClockDriftCorrectionPreference() { + const {preferences} = useTraceState(); + return
{preferences.clock_drift_correction ? 'corrected' : 'not corrected'}
; +} + function SearchQuery() { const {search} = useTraceState(); return
{search.query ?? 'no search'}
; @@ -40,4 +47,28 @@ describe('TraceStateProvider', () => { expect(screen.getByText('no search')).toBeInTheDocument(); }); + + it('keeps the stored clock drift correction preference without the feature', async () => { + localStorage.clear(); + + render( + + + , + {organization: OrganizationFixture({features: []})} + ); + + expect(screen.getByText('not corrected')).toBeInTheDocument(); + await waitFor(() => { + expect(JSON.parse(localStorage.getItem('trace-preferences-test')!)).toMatchObject({ + clock_drift_correction: true, + }); + }); + }); }); diff --git a/static/app/views/performance/traceDetails/traceState/traceStateProvider.tsx b/static/app/views/performance/traceDetails/traceState/traceStateProvider.tsx index 2b33ceaf4c96..2a79648b54e2 100644 --- a/static/app/views/performance/traceDetails/traceState/traceStateProvider.tsx +++ b/static/app/views/performance/traceDetails/traceState/traceStateProvider.tsx @@ -6,6 +6,8 @@ import { useDispatchingReducer, type DispatchingReducerEmitter, } from 'sentry/utils/useDispatchingReducer'; +import {useOrganization} from 'sentry/utils/useOrganization'; +import {hasClockDriftCorrectionFeature} from 'sentry/views/performance/traceDetails/traceModels/clockDriftCorrection'; import {TraceReducer, type TraceReducerAction, type TraceReducerState} from './index'; import {storeTraceViewPreferences, type TracePreferencesState} from './tracePreferences'; @@ -63,6 +65,17 @@ interface TraceStateProviderProps { } export function TraceStateProvider(props: TraceStateProviderProps): React.ReactNode { + const organization = useOrganization({allowNull: true}); + const hasClockDriftCorrection = hasClockDriftCorrectionFeature(organization); + // Every trace tree reads its preferences from here, so turning the correction off here keeps it + // off everywhere, also if it was stored while the organization had the feature. + const initialPreferences = hasClockDriftCorrection + ? props.initialPreferences + : {...props.initialPreferences, clock_drift_correction: false}; + // The stored preference is shared with organizations that have the feature, so keep it as it + // was instead of storing the forced value. It can't be toggled without the feature. + const storedClockDriftCorrection = props.initialPreferences.clock_drift_correction; + // We only want to decode on load, hence the lazy initializer. const [initialQuery] = useState((): string | undefined => { if (props.disableUrlSync) { @@ -85,16 +98,29 @@ export function TraceStateProvider(props: TraceStateProviderProps): React.ReactN status: undefined, resultsLookup: new Map(), }, - preferences: props.initialPreferences, + preferences: initialPreferences, tabs: {tabs: [], current_tab: null, last_clicked_tab: null}, } ); useLayoutEffect(() => { if (props.preferencesStorageKey) { - storeTraceViewPreferences(props.preferencesStorageKey, traceState.preferences); + storeTraceViewPreferences( + props.preferencesStorageKey, + hasClockDriftCorrection + ? traceState.preferences + : { + ...traceState.preferences, + clock_drift_correction: storedClockDriftCorrection, + } + ); } - }, [traceState.preferences, props.preferencesStorageKey]); + }, [ + traceState.preferences, + props.preferencesStorageKey, + hasClockDriftCorrection, + storedClockDriftCorrection, + ]); return ( diff --git a/static/app/views/performance/traceDetails/traceWaterfall.tsx b/static/app/views/performance/traceDetails/traceWaterfall.tsx index 726ad71afb5f..17b7f5ec6ab8 100644 --- a/static/app/views/performance/traceDetails/traceWaterfall.tsx +++ b/static/app/views/performance/traceDetails/traceWaterfall.tsx @@ -19,7 +19,7 @@ import {Flex, Stack} from '@sentry/scraps/layout'; import {toast} from '@sentry/scraps/toast'; import {usePageFilters} from 'sentry/components/pageFilters/usePageFilters'; -import {t, tct} from 'sentry/locale'; +import {t, tct, tn} from 'sentry/locale'; import type {Organization} from 'sentry/types/organization'; import {trackAnalytics} from 'sentry/utils/analytics'; import {DemoTourElement, DemoTourStep} from 'sentry/utils/demoMode/demoTours'; @@ -756,6 +756,30 @@ export function TraceWaterfall(props: TraceWaterfallProps) { props.organization, ]); + const onClockDriftCorrectionChange = useCallback(() => { + const value = !traceState.preferences.clock_drift_correction; + const count = props.tree.setClockDriftCorrection(value, { + organization: props.organization, + preferences: traceState.preferences, + }); + + toast.success( + value + ? count > 0 + ? tn( + 'Clock drift correction enabled, adjusted %s span', + 'Clock drift correction enabled, adjusted %s spans', + count + ) + : t('Clock drift correction enabled') + : t('Clock drift correction disabled') + ); + + traceAnalytics.trackClockDriftCorrectionPreferenceChange(props.organization, value); + props.tree.rebuild(); + traceDispatch({type: 'set clock drift correction', payload: value}); + }, [traceDispatch, traceState.preferences, props.tree, props.organization]); + const onCompressedTimelineChange = useCallback(() => { const value = !traceState.preferences.compressed_timeline; @@ -813,8 +837,11 @@ export function TraceWaterfall(props: TraceWaterfallProps) { traceState.preferences.autogroup.sibling } compressedTimeline={traceState.preferences.compressed_timeline} + clockDriftCorrection={traceState.preferences.clock_drift_correction} + clockDriftCorrectionCount={props.tree.clock_drift_correction_count} missingInstrumentation={traceState.preferences.missing_instrumentation} onAutogroupChange={onAutogroupChange} + onClockDriftCorrectionChange={onClockDriftCorrectionChange} onCompressedTimelineChange={onCompressedTimelineChange} onMissingInstrumentationChange={onMissingInstrumentationChange} />