Skip to content

Commit

Permalink
fix(core): Ensure standalone spans respect sampled flag (#12533)
Browse files Browse the repository at this point in the history
`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.
  • Loading branch information
AbhiPrasad authored Jun 19, 2024
1 parent e9e862f commit 1d66b8a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
10 changes: 9 additions & 1 deletion packages/core/src/tracing/sentrySpan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,15 @@ export class SentrySpan implements Span {

// if this is a standalone span, we send it immediately
if (this._isStandaloneSpan) {
sendSpanEnvelope(createSpanEnvelope([this], client));
if (this._sampled) {
sendSpanEnvelope(createSpanEnvelope([this], client));
} else {
DEBUG_BUILD &&
logger.log('[Tracing] Discarding standalone span because its trace was not chosen to be sampled.');
if (client) {
client.recordDroppedEvent('sample_rate', 'span');
}
}
return;
}

Expand Down
33 changes: 33 additions & 0 deletions packages/core/test/lib/tracing/sentrySpan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,39 @@ describe('SentrySpan', () => {
expect(spanToJSON(span).timestamp).toBeGreaterThan(1);
});

test('uses sampled config for standalone span', () => {
const client = new TestClient(
getDefaultTestClientOptions({
dsn: 'https://username@domain/123',
enableSend: true,
}),
);
setCurrentClient(client);

// @ts-expect-error Accessing private transport API
const mockSend = jest.spyOn(client._transport, 'send');

const notSampledSpan = new SentrySpan({
name: 'not-sampled',
isStandalone: true,
startTimestamp: 1,
endTimestamp: 2,
sampled: false,
});
notSampledSpan.end();
expect(mockSend).not.toHaveBeenCalled();

const sampledSpan = new SentrySpan({
name: 'is-sampled',
isStandalone: true,
startTimestamp: 1,
endTimestamp: 2,
sampled: true,
});
sampledSpan.end();
expect(mockSend).toHaveBeenCalledTimes(1);
});

test('sends the span if `beforeSendSpan` does not modify the span ', () => {
const beforeSendSpan = jest.fn(span => span);
const client = new TestClient(
Expand Down

0 comments on commit 1d66b8a

Please sign in to comment.