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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
integrations: [
Sentry.browserTracingIntegration({
enableReportPageLoaded: true,
// Otherwise, the navigation right after the pageload start counts as a redirect
detectRedirects: false,
}),
],
tracesSampleRate: 1,
});

const pageloadPropagationContext = Sentry.getCurrentScope().getPropagationContext();
window._pageloadSampleRand = pageloadPropagationContext.sampleRand;

// Record which trace the scope holds when the pageload span envelope is sent
Sentry.getClient().on('beforeEnvelope', envelope => {
const isSpanEnvelope = envelope[1].some(([itemHeader]) => itemHeader.type === 'span');
if (isSpanEnvelope && envelope[0].trace?.trace_id === pageloadPropagationContext.traceId) {
window._scopeTraceIdOnPageloadFlush = Sentry.getCurrentScope().getPropagationContext().traceId;
}
});

// End the pageload span and start a new trace in the same tick, so both happen before the pageload span is flushed
Sentry.reportPageLoaded();
window.history.pushState({}, '', '/sub-page');
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { NAVIGATION, PAGELOAD } from '@sentry/conventions/op';
import { SENTRY_IDLE_SPAN_FINISH_REASON } from '@sentry/conventions/attributes';
import { expect } from '@playwright/test';
import { sentryTest } from '../../../../utils/fixtures';
import { shouldSkipTracingTest } from '../../../../utils/helpers';
import { getSpanOp, waitForStreamedSpanAndTraceHeader } from '../../../../utils/spanUtils';

sentryTest(
"keeps the pageload's trace values in its trace envelope header when a new navigation trace starts before the pageload spans are flushed",
async ({ getLocalTestUrl, page }) => {
if (shouldSkipTracingTest()) {
sentryTest.skip();
}

const url = await getLocalTestUrl({ testDir: __dirname });

const pageloadPromise = waitForStreamedSpanAndTraceHeader(page, span => getSpanOp(span) === PAGELOAD);
const navigationPromise = waitForStreamedSpanAndTraceHeader(page, span => getSpanOp(span) === NAVIGATION);

await page.goto(url);

const [pageloadSpan, pageloadTraceHeader] = await pageloadPromise;
const [navigationSpan, navigationTraceHeader] = await navigationPromise;

const { pageloadSampleRand, scopeTraceIdOnPageloadFlush } = await page.evaluate(() => ({
pageloadSampleRand: (window as any)._pageloadSampleRand,
scopeTraceIdOnPageloadFlush: (window as any)._scopeTraceIdOnPageloadFlush,
}));

expect(pageloadSpan.trace_id).not.toEqual(navigationSpan.trace_id);
expect(pageloadSpan.attributes[SENTRY_IDLE_SPAN_FINISH_REASON]?.value).toBe('reportPageLoaded');

// The pageload span envelope was only sent after the navigation started its new trace on the scope
expect(scopeTraceIdOnPageloadFlush).toBe(navigationSpan.trace_id);

// The navigation resets the propagation context on the scope the pageload span captured.
// The pageload envelope is flushed after that, but must still carry the pageload's values.
expect(pageloadTraceHeader).toEqual({
environment: 'production',
public_key: 'public',
trace_id: pageloadSpan.trace_id,
sample_rate: '1',
sampled: 'true',
sample_rand: String(pageloadSampleRand),
});

expect(navigationTraceHeader).toMatchObject({
trace_id: navigationSpan.trace_id,
sampled: 'true',
});

expect(navigationTraceHeader?.sample_rand).not.toEqual(pageloadTraceHeader?.sample_rand);
},
);
5 changes: 5 additions & 0 deletions packages/core/src/tracing/spans/captureSpan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
spanToJSON,
streamedSpanJsonToSerializedSpan,
} from '../../utils/spanUtils';
import { freezeDscOnSpan, getDynamicSamplingContextFromSpan } from '../dynamicSamplingContext';
import { getCapturedScopesOnSpan } from '../utils';
import { applyBeforeSendSpanCallback, isStaticBeforeSendSpanCallback } from './beforeSendSpan';
import { spanJsonToSerializedStreamedSpan } from './spanJsonToStreamedSpan';
Expand Down Expand Up @@ -66,6 +67,10 @@ export function captureSpan(span: Span, client: Client): SerializedStreamedSpanW
client.emit('preprocessSpan', spanJSON);

if (spanJSON.is_segment) {
// The span buffer builds the envelope's `trace` header from the segment span when a bucket is flushed.
// This can happen after the captured scope moved on to another trace (e.g. a browser navigation).
// Freezing the DSC at segment end keeps the values of this segment's trace.
freezeDscOnSpan(segmentSpan, getDynamicSamplingContextFromSpan(segmentSpan));
applyScopeToSegmentSpan(spanJSON, finalScopeData);
applySdkMetadataToSegmentSpan(spanJSON, client);
// Allow hook subscribers to mutate the segment span JSON
Expand Down
5 changes: 4 additions & 1 deletion packages/core/src/tracing/spans/spanBuffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { SerializedStreamedSpan, Span } from '../../types/span';
import { debug } from '../../utils/debug-logger';
import { spanToJSON } from '../../utils/spanUtils';
import { safeUnref } from '../../utils/timer';
import { getDynamicSamplingContextFromSpan } from '../dynamicSamplingContext';
import { freezeDscOnSpan, getDynamicSamplingContextFromSpan } from '../dynamicSamplingContext';
import type { SerializedStreamedSpanWithSegmentSpan } from './captureSpan';
import { createStreamedSpanEnvelope } from './envelope';
import { estimateSerializedSpanSizeInBytes } from './estimateSize';
Expand Down Expand Up @@ -168,7 +168,10 @@ export class SpanBuffer {
return;
}

// Freeze the DSC so that all envelopes of this segment carry the same `trace` header, even if the segment
// span is still running and more spans of it get flushed later.
const dsc = getDynamicSamplingContextFromSpan(segmentSpan);
freezeDscOnSpan(segmentSpan, dsc);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Freezing here also freezes the transaction name. If the first flush happens before the name is parameterized, the DSC never gets the final name, where before the last envelope did. Is that an issue?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not sure if that would surface in e2e

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

that's intentional. I think diverging between trace boundaries (i.e. when we propagate via baggage) is one thing but diverging within the same service (for two or more envelopes) is something we should avoid.


const currentSegmentNames = new Map<Span, string>();
const getCurrentSegmentName = (span: Span): string => {
Expand Down
39 changes: 38 additions & 1 deletion packages/core/test/lib/tracing/spans/spanBuffer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import {
SpanBuffer,
startInactiveSpan,
startSpan,
withScope,
withStreamedSpan,
} from '../../../../src';
import type { SerializedStreamedSpanWithSegmentSpan } from '../../../../src/tracing/spans/captureSpan';
import { captureSpan } from '../../../../src/tracing/spans/captureSpan';
import { getDefaultTestClientOptions, TestClient } from '../../../mocks/client';
import { HTTP_METHOD, SENTRY_SEGMENT_NAME, URL_FULL } from '@sentry/conventions/attributes';
import { HTTP_METHOD, SENTRY_SEGMENT_NAME, SENTRY_SEGMENT_NAME_SOURCE, URL_FULL } from '@sentry/conventions/attributes';

describe('SpanBuffer', () => {
let client: TestClient;
Expand Down Expand Up @@ -379,6 +380,42 @@ describe('SpanBuffer', () => {
});
});

describe('trace envelope header', () => {
it('freezes the DSC on the first flush while the segment span is still running', () => {
const buffer = new SpanBuffer(client);

withScope(scope => {
const sampleRand = scope.getPropagationContext().sampleRand;
const root = startInactiveSpan({ name: 'GET /old', attributes: { [SENTRY_SEGMENT_NAME_SOURCE]: 'route' } });
const traceId = root.spanContext().traceId;

const child = startInactiveSpan({ name: 'child', parentSpan: root });
child.end();
buffer.add(captureSpan(child, client));
buffer.flush(traceId);

root.updateName('GET /new');
scope.setPropagationContext({ traceId: '0'.repeat(32), sampleRand: 0.99 });

root.end();
buffer.add(captureSpan(root, client));
buffer.flush(traceId);

expect(sentEnvelopes).toHaveLength(2);
expect(sentEnvelopes[0]?.[0].trace).toEqual({
environment: 'production',
public_key: 'username',
trace_id: traceId,
transaction: 'GET /old',
sample_rate: '1',
sampled: 'true',
sample_rand: String(sampleRand),
});
expect(sentEnvelopes[1]?.[0].trace).toStrictEqual(sentEnvelopes[0]?.[0].trace);
});
});
});

describe('segment name', () => {
function getSentSegmentNames(): Record<string, unknown> {
const items = sentEnvelopes[0]?.[1]?.[0]?.[1]?.items ?? [];
Expand Down
Loading