Skip to content

Commit 1d66b8a

Browse files
authored
fix(core): Ensure standalone spans respect sampled flag (#12533)
`sendSpanEnvelope` immediately sends spans without checking for `this._sampled`, which means you can't use `tracesSampler` to filter them. This changes that! We also record client outcomes for `sample_rate` with spans.
1 parent e9e862f commit 1d66b8a

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

packages/core/src/tracing/sentrySpan.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,15 @@ export class SentrySpan implements Span {
261261

262262
// if this is a standalone span, we send it immediately
263263
if (this._isStandaloneSpan) {
264-
sendSpanEnvelope(createSpanEnvelope([this], client));
264+
if (this._sampled) {
265+
sendSpanEnvelope(createSpanEnvelope([this], client));
266+
} else {
267+
DEBUG_BUILD &&
268+
logger.log('[Tracing] Discarding standalone span because its trace was not chosen to be sampled.');
269+
if (client) {
270+
client.recordDroppedEvent('sample_rate', 'span');
271+
}
272+
}
265273
return;
266274
}
267275

packages/core/test/lib/tracing/sentrySpan.test.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,39 @@ describe('SentrySpan', () => {
9191
expect(spanToJSON(span).timestamp).toBeGreaterThan(1);
9292
});
9393

94+
test('uses sampled config for standalone span', () => {
95+
const client = new TestClient(
96+
getDefaultTestClientOptions({
97+
dsn: 'https://username@domain/123',
98+
enableSend: true,
99+
}),
100+
);
101+
setCurrentClient(client);
102+
103+
// @ts-expect-error Accessing private transport API
104+
const mockSend = jest.spyOn(client._transport, 'send');
105+
106+
const notSampledSpan = new SentrySpan({
107+
name: 'not-sampled',
108+
isStandalone: true,
109+
startTimestamp: 1,
110+
endTimestamp: 2,
111+
sampled: false,
112+
});
113+
notSampledSpan.end();
114+
expect(mockSend).not.toHaveBeenCalled();
115+
116+
const sampledSpan = new SentrySpan({
117+
name: 'is-sampled',
118+
isStandalone: true,
119+
startTimestamp: 1,
120+
endTimestamp: 2,
121+
sampled: true,
122+
});
123+
sampledSpan.end();
124+
expect(mockSend).toHaveBeenCalledTimes(1);
125+
});
126+
94127
test('sends the span if `beforeSendSpan` does not modify the span ', () => {
95128
const beforeSendSpan = jest.fn(span => span);
96129
const client = new TestClient(

0 commit comments

Comments
 (0)