Skip to content

Commit 686e75b

Browse files
authored
fix(browser): Skip profiling for unsampled active root spans (#25498)
- [x] If you've added code that should be tested, please add tests. - [x] Ensure your code lints and the test suite passes (`yarn lint`) & (`yarn test`). - [x] Link an issue if there is one related to your pull request. If no issue is linked, one will be auto-generated and linked. Closes #25497 With the `trace` profile lifecycle in `@sentry/browser`, `notifyRootSpanActive()` started the profiler for a root span that was already active at setup. It did not check whether that span was sampled. As a result, an unsampled pageload span started UI profiling and sent a `profile_chunk`, even with `tracesSampleRate: 0`. This change returns early in `notifyRootSpanActive()` when the root span is not recording. This matches the check in the `spanStart` listener. Two tests were added: - A regression test for an unsampled pageload span with the `trace` profile lifecycle. - A test for a sampled root span that is already active when the integration is added. Here only `notifyRootSpanActive()` can start the profiler, so the test covers that path directly. It also checks that the second notification from the timeout does not start another profiler. Validation (in `packages/browser`): - `yarn test`: 763 tests passed, including the two new tests - `yarn lint`: no errors; `oxfmt --check` passed on the changed files - The regression test fails without the fix - The new active-root-span test fails if `notifyRootSpanActive()` is disabled - Browser integration tests (Playwright) were not run
1 parent 777b3b2 commit 686e75b

2 files changed

Lines changed: 111 additions & 1 deletion

File tree

‎packages/browser/src/profiling/UIProfiler.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,8 @@ export class UIProfiler implements ContinuousProfiler<Client> {
135135

136136
/** Handle an already-active root span at integration setup time (used only in trace mode). */
137137
public notifyRootSpanActive(rootSpan: Span): void {
138-
if (this._lifecycleMode !== 'trace' || !this._sessionSampled) {
138+
// Only count sampled root spans, same as the `spanStart` listener
139+
if (this._lifecycleMode !== 'trace' || !this._sessionSampled || !rootSpan.isRecording()) {
139140
return;
140141
}
141142

‎packages/browser/test/profiling/integration.test.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
*/
44

55
import {
6+
addIntegration,
67
init,
78
getClient,
89
spanToStaticSpanJSON,
@@ -92,6 +93,114 @@ describe('BrowserProfilingIntegration', () => {
9293
expect(profileChunk.profile.samples[0].timestamp).toBeGreaterThanOrEqual(transaction.start_timestamp);
9394
});
9495

96+
it('does not profile an already active pageload span that is not sampled in trace lifecycle mode', async () => {
97+
const mockProfiler = vi.fn().mockImplementation(function () {
98+
return {
99+
stop: vi.fn().mockResolvedValue({
100+
frames: [{ name: 'pageload_fn', line: 1, column: 1 }],
101+
stacks: [{ frameId: 0 }],
102+
samples: [
103+
{ stackId: 0, timestamp: 0 },
104+
{ stackId: 0, timestamp: 100 },
105+
],
106+
resources: [],
107+
}),
108+
addEventListener: vi.fn(),
109+
};
110+
});
111+
112+
// @ts-expect-error this is a mock constructor
113+
window.Profiler = mockProfiler;
114+
115+
const send = vi.fn().mockResolvedValue(undefined);
116+
const client = init({
117+
tracesSampleRate: 0,
118+
traceLifecycle: 'static',
119+
profileSessionSampleRate: 1,
120+
profileLifecycle: 'trace',
121+
dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
122+
transport: () => ({
123+
flush: vi.fn().mockResolvedValue(true),
124+
send,
125+
}),
126+
integrations: [browserTracingIntegration(), browserProfilingIntegration()],
127+
});
128+
129+
const pageloadSpan = getActiveSpan();
130+
expect(pageloadSpan).toBeDefined();
131+
expect(spanToStaticSpanJSON(pageloadSpan!).op).toBe('pageload');
132+
expect(pageloadSpan!.isRecording()).toBe(false);
133+
134+
// The integration re-checks the active root span in a timeout after setup.
135+
await new Promise(resolve => setTimeout(resolve, 0));
136+
137+
pageloadSpan?.end();
138+
await Promise.resolve();
139+
await client?.flush(1000);
140+
141+
expect(mockProfiler).not.toHaveBeenCalled();
142+
const profileChunkEnvelope = send.mock.calls.find(call => call[0][1][0][0].type === 'profile_chunk');
143+
expect(profileChunkEnvelope).toBeUndefined();
144+
});
145+
146+
it('profiles a sampled root span that is already active when the integration is added', async () => {
147+
const stopProfile = vi.fn().mockResolvedValue({
148+
frames: [{ name: 'pageload_fn', line: 1, column: 1 }],
149+
stacks: [{ frameId: 0 }],
150+
samples: [
151+
{ stackId: 0, timestamp: 0 },
152+
{ stackId: 0, timestamp: 100 },
153+
],
154+
resources: [],
155+
});
156+
157+
const mockProfiler = vi.fn().mockImplementation(function () {
158+
return {
159+
stop: stopProfile,
160+
addEventListener: vi.fn(),
161+
};
162+
});
163+
164+
// @ts-expect-error this is a mock constructor
165+
window.Profiler = mockProfiler;
166+
167+
const send = vi.fn().mockResolvedValue(undefined);
168+
const client = init({
169+
tracesSampleRate: 1,
170+
traceLifecycle: 'static',
171+
profileSessionSampleRate: 1,
172+
profileLifecycle: 'trace',
173+
dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
174+
transport: () => ({
175+
flush: vi.fn().mockResolvedValue(true),
176+
send,
177+
}),
178+
integrations: [browserTracingIntegration()],
179+
});
180+
181+
const pageloadSpan = getActiveSpan();
182+
expect(pageloadSpan!.isRecording()).toBe(true);
183+
184+
// The pageload span started before the profiler listens to `spanStart`,
185+
// so only the integration setup can start the profiler for it.
186+
addIntegration(browserProfilingIntegration());
187+
const profilerCallsAfterSetup = mockProfiler.mock.calls.length;
188+
189+
// The re-check in a timeout notifies the same root span again, which must not start another profiler.
190+
await new Promise(resolve => setTimeout(resolve, 0));
191+
const profilerCallsAfterRecheck = mockProfiler.mock.calls.length;
192+
193+
pageloadSpan?.end();
194+
await Promise.resolve();
195+
await client?.flush(1000);
196+
197+
expect(profilerCallsAfterSetup).toBe(1);
198+
expect(profilerCallsAfterRecheck).toBe(1);
199+
expect(stopProfile).toHaveBeenCalledTimes(1);
200+
const profileChunkEnvelope = send.mock.calls.find(call => call[0][1][0][0].type === 'profile_chunk');
201+
expect(profileChunkEnvelope).toBeDefined();
202+
});
203+
95204
it("warns when profileLifecycle is 'trace' but tracing is disabled", async () => {
96205
const warnSpy = vi.spyOn(debug, 'warn').mockImplementation(() => {});
97206

0 commit comments

Comments
 (0)