Skip to content

Commit b685be6

Browse files
authored
ref(core): Wrap isolationscope in WeakRef when storing it on spans (#17712)
We often store isolationscopes on spans via `setCapturedScopesOnSpan` and retrieve them via `getCapturedScopesOnSpan`. This change wraps the scopes in `WeakRef` to attempt fixing a potential memory leak when spans hold on to scopes indefinitely. The downside is spans might end up with undefined scopes on them if the scope was garbage collected, we'll have to see if that's an issue or not.
1 parent 34f3479 commit b685be6

File tree

2 files changed

+290
-4
lines changed

2 files changed

+290
-4
lines changed

packages/core/src/tracing/utils.ts

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,71 @@
11
import type { Scope } from '../scope';
22
import type { Span } from '../types-hoist/span';
33
import { addNonEnumerableProperty } from '../utils/object';
4+
import { GLOBAL_OBJ } from '../utils/worldwide';
45

56
const SCOPE_ON_START_SPAN_FIELD = '_sentryScope';
67
const ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';
78

9+
type ScopeWeakRef = { deref(): Scope | undefined } | Scope;
10+
811
type SpanWithScopes = Span & {
912
[SCOPE_ON_START_SPAN_FIELD]?: Scope;
10-
[ISOLATION_SCOPE_ON_START_SPAN_FIELD]?: Scope;
13+
[ISOLATION_SCOPE_ON_START_SPAN_FIELD]?: ScopeWeakRef;
1114
};
1215

16+
/** Wrap a scope with a WeakRef if available, falling back to a direct scope. */
17+
function wrapScopeWithWeakRef(scope: Scope): ScopeWeakRef {
18+
try {
19+
// @ts-expect-error - WeakRef is not available in all environments
20+
const WeakRefClass = GLOBAL_OBJ.WeakRef;
21+
if (typeof WeakRefClass === 'function') {
22+
return new WeakRefClass(scope);
23+
}
24+
} catch {
25+
// WeakRef not available or failed to create
26+
// We'll fall back to a direct scope
27+
}
28+
29+
return scope;
30+
}
31+
32+
/** Try to unwrap a scope from a potential WeakRef wrapper. */
33+
function unwrapScopeFromWeakRef(scopeRef: ScopeWeakRef | undefined): Scope | undefined {
34+
if (!scopeRef) {
35+
return undefined;
36+
}
37+
38+
if (typeof scopeRef === 'object' && 'deref' in scopeRef && typeof scopeRef.deref === 'function') {
39+
try {
40+
return scopeRef.deref();
41+
} catch {
42+
return undefined;
43+
}
44+
}
45+
46+
// Fallback to a direct scope
47+
return scopeRef as Scope;
48+
}
49+
1350
/** Store the scope & isolation scope for a span, which can the be used when it is finished. */
1451
export function setCapturedScopesOnSpan(span: Span | undefined, scope: Scope, isolationScope: Scope): void {
1552
if (span) {
16-
addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope);
53+
addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, wrapScopeWithWeakRef(isolationScope));
54+
// We don't wrap the scope with a WeakRef here because webkit aggressively garbage collects
55+
// and scopes are not held in memory for long periods of time.
1756
addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);
1857
}
1958
}
2059

2160
/**
2261
* Grabs the scope and isolation scope off a span that were active when the span was started.
62+
* If WeakRef was used and scopes have been garbage collected, returns undefined for those scopes.
2363
*/
2464
export function getCapturedScopesOnSpan(span: Span): { scope?: Scope; isolationScope?: Scope } {
65+
const spanWithScopes = span as SpanWithScopes;
66+
2567
return {
26-
scope: (span as SpanWithScopes)[SCOPE_ON_START_SPAN_FIELD],
27-
isolationScope: (span as SpanWithScopes)[ISOLATION_SCOPE_ON_START_SPAN_FIELD],
68+
scope: spanWithScopes[SCOPE_ON_START_SPAN_FIELD],
69+
isolationScope: unwrapScopeFromWeakRef(spanWithScopes[ISOLATION_SCOPE_ON_START_SPAN_FIELD]),
2870
};
2971
}
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
import { describe, expect, it, vi } from 'vitest';
2+
import { Scope } from '../../../src/scope';
3+
import { getCapturedScopesOnSpan, setCapturedScopesOnSpan } from '../../../src/tracing/utils';
4+
import type { Span } from '../../../src/types-hoist/span';
5+
6+
// Mock span object that implements the minimum needed interface
7+
function createMockSpan(): Span {
8+
return {} as Span;
9+
}
10+
11+
describe('tracing utils', () => {
12+
describe('setCapturedScopesOnSpan / getCapturedScopesOnSpan', () => {
13+
it('stores and retrieves scopes correctly', () => {
14+
const span = createMockSpan();
15+
const scope = new Scope();
16+
const isolationScope = new Scope();
17+
18+
scope.setTag('test-scope', 'value1');
19+
isolationScope.setTag('test-isolation-scope', 'value2');
20+
21+
setCapturedScopesOnSpan(span, scope, isolationScope);
22+
const retrieved = getCapturedScopesOnSpan(span);
23+
24+
expect(retrieved.scope).toBe(scope);
25+
expect(retrieved.isolationScope).toBe(isolationScope);
26+
expect(retrieved.scope?.getScopeData().tags).toEqual({ 'test-scope': 'value1' });
27+
expect(retrieved.isolationScope?.getScopeData().tags).toEqual({ 'test-isolation-scope': 'value2' });
28+
});
29+
30+
it('handles undefined span gracefully in setCapturedScopesOnSpan', () => {
31+
const scope = new Scope();
32+
const isolationScope = new Scope();
33+
34+
expect(() => {
35+
setCapturedScopesOnSpan(undefined, scope, isolationScope);
36+
}).not.toThrow();
37+
});
38+
39+
it('returns undefined scopes when span has no captured scopes', () => {
40+
const span = createMockSpan();
41+
const retrieved = getCapturedScopesOnSpan(span);
42+
43+
expect(retrieved.scope).toBeUndefined();
44+
expect(retrieved.isolationScope).toBeUndefined();
45+
});
46+
47+
it('uses WeakRef only for isolation scopes', () => {
48+
const span = createMockSpan();
49+
const scope = new Scope();
50+
const isolationScope = new Scope();
51+
52+
setCapturedScopesOnSpan(span, scope, isolationScope);
53+
54+
// Check that only isolation scope is wrapped with WeakRef
55+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
56+
const spanWithScopes = span as any;
57+
expect(spanWithScopes._sentryScope).toBe(scope); // Regular scope stored directly
58+
expect(spanWithScopes._sentryIsolationScope).toBeInstanceOf(WeakRef); // Isolation scope wrapped
59+
60+
// Verify we can still retrieve the scopes
61+
const retrieved = getCapturedScopesOnSpan(span);
62+
expect(retrieved.scope).toBe(scope);
63+
expect(retrieved.isolationScope).toBe(isolationScope);
64+
});
65+
66+
it('falls back to direct storage when WeakRef is not available', () => {
67+
// Temporarily disable WeakRef
68+
const originalWeakRef = globalThis.WeakRef;
69+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
70+
(globalThis as any).WeakRef = undefined;
71+
72+
try {
73+
const span = createMockSpan();
74+
const scope = new Scope();
75+
const isolationScope = new Scope();
76+
77+
setCapturedScopesOnSpan(span, scope, isolationScope);
78+
79+
// Check that both scopes are stored directly when WeakRef is not available
80+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
81+
const spanWithScopes = span as any;
82+
expect(spanWithScopes._sentryScope).toBe(scope); // Regular scope always stored directly
83+
expect(spanWithScopes._sentryIsolationScope).toBe(isolationScope); // Isolation scope falls back to direct storage
84+
85+
// When WeakRef is available, ensure regular scope is not wrapped but isolation scope would be
86+
if (originalWeakRef) {
87+
expect(spanWithScopes._sentryScope).not.toBeInstanceOf(originalWeakRef);
88+
expect(spanWithScopes._sentryIsolationScope).not.toBeInstanceOf(originalWeakRef);
89+
}
90+
91+
// Verify we can still retrieve the scopes
92+
const retrieved = getCapturedScopesOnSpan(span);
93+
expect(retrieved.scope).toBe(scope);
94+
expect(retrieved.isolationScope).toBe(isolationScope);
95+
} finally {
96+
// Restore WeakRef
97+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
98+
(globalThis as any).WeakRef = originalWeakRef;
99+
}
100+
});
101+
102+
it('handles WeakRef deref returning undefined gracefully', () => {
103+
const span = createMockSpan();
104+
const scope = new Scope();
105+
const isolationScope = new Scope();
106+
107+
setCapturedScopesOnSpan(span, scope, isolationScope);
108+
109+
// Mock WeakRef.deref to return undefined for isolation scope (simulating garbage collection)
110+
// Regular scope is stored directly, so it should always be available
111+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
112+
const spanWithScopes = span as any;
113+
const mockIsolationScopeWeakRef = {
114+
deref: vi.fn().mockReturnValue(undefined),
115+
};
116+
117+
// Keep the regular scope as is (stored directly)
118+
// Only replace the isolation scope with a mock WeakRef
119+
spanWithScopes._sentryIsolationScope = mockIsolationScopeWeakRef;
120+
121+
const retrieved = getCapturedScopesOnSpan(span);
122+
expect(retrieved.scope).toBe(scope); // Regular scope should still be available
123+
expect(retrieved.isolationScope).toBeUndefined(); // Isolation scope should be undefined due to GC
124+
expect(mockIsolationScopeWeakRef.deref).toHaveBeenCalled();
125+
});
126+
127+
it('handles corrupted WeakRef objects gracefully', () => {
128+
const span = createMockSpan();
129+
const scope = new Scope();
130+
131+
// Set up a regular scope (stored directly) and a corrupted isolation scope WeakRef
132+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
133+
const spanWithScopes = span as any;
134+
spanWithScopes._sentryScope = scope; // Regular scope stored directly
135+
spanWithScopes._sentryIsolationScope = {
136+
deref: vi.fn().mockImplementation(() => {
137+
throw new Error('WeakRef deref failed');
138+
}),
139+
};
140+
141+
const retrieved = getCapturedScopesOnSpan(span);
142+
expect(retrieved.scope).toBe(scope); // Regular scope should still be available
143+
expect(retrieved.isolationScope).toBeUndefined(); // Isolation scope should be undefined due to error
144+
});
145+
146+
it('preserves scope data when using WeakRef', () => {
147+
const span = createMockSpan();
148+
const scope = new Scope();
149+
const isolationScope = new Scope();
150+
151+
// Add various types of data to scopes
152+
scope.setTag('string-tag', 'value');
153+
scope.setTag('number-tag', 123);
154+
scope.setTag('boolean-tag', true);
155+
scope.setContext('test-context', { key: 'value' });
156+
scope.setUser({ id: 'test-user' });
157+
158+
isolationScope.setExtra('extra-data', { complex: { nested: 'object' } });
159+
isolationScope.setLevel('warning');
160+
161+
setCapturedScopesOnSpan(span, scope, isolationScope);
162+
const retrieved = getCapturedScopesOnSpan(span);
163+
164+
// Verify all data is preserved
165+
expect(retrieved.scope?.getScopeData().tags).toEqual({
166+
'string-tag': 'value',
167+
'number-tag': 123,
168+
'boolean-tag': true,
169+
});
170+
expect(retrieved.scope?.getScopeData().contexts).toEqual({
171+
'test-context': { key: 'value' },
172+
});
173+
expect(retrieved.scope?.getScopeData().user).toEqual({ id: 'test-user' });
174+
175+
expect(retrieved.isolationScope?.getScopeData().extra).toEqual({
176+
'extra-data': { complex: { nested: 'object' } },
177+
});
178+
expect(retrieved.isolationScope?.getScopeData().level).toBe('warning');
179+
});
180+
181+
it('handles multiple spans with different scopes', () => {
182+
const span1 = createMockSpan();
183+
const span2 = createMockSpan();
184+
185+
const scope1 = new Scope();
186+
const scope2 = new Scope();
187+
const isolationScope1 = new Scope();
188+
const isolationScope2 = new Scope();
189+
190+
scope1.setTag('span', '1');
191+
scope2.setTag('span', '2');
192+
isolationScope1.setTag('isolation', '1');
193+
isolationScope2.setTag('isolation', '2');
194+
195+
setCapturedScopesOnSpan(span1, scope1, isolationScope1);
196+
setCapturedScopesOnSpan(span2, scope2, isolationScope2);
197+
198+
const retrieved1 = getCapturedScopesOnSpan(span1);
199+
const retrieved2 = getCapturedScopesOnSpan(span2);
200+
201+
expect(retrieved1.scope?.getScopeData().tags).toEqual({ span: '1' });
202+
expect(retrieved1.isolationScope?.getScopeData().tags).toEqual({ isolation: '1' });
203+
204+
expect(retrieved2.scope?.getScopeData().tags).toEqual({ span: '2' });
205+
expect(retrieved2.isolationScope?.getScopeData().tags).toEqual({ isolation: '2' });
206+
207+
// Ensure they are different scope instances
208+
expect(retrieved1.scope).not.toBe(retrieved2.scope);
209+
expect(retrieved1.isolationScope).not.toBe(retrieved2.isolationScope);
210+
});
211+
212+
it('handles span reuse correctly', () => {
213+
const span = createMockSpan();
214+
215+
// First use
216+
const scope1 = new Scope();
217+
const isolationScope1 = new Scope();
218+
scope1.setTag('first', 'use');
219+
isolationScope1.setTag('first-isolation', 'use');
220+
221+
setCapturedScopesOnSpan(span, scope1, isolationScope1);
222+
const retrieved1 = getCapturedScopesOnSpan(span);
223+
224+
expect(retrieved1.scope?.getScopeData().tags).toEqual({ first: 'use' });
225+
expect(retrieved1.isolationScope?.getScopeData().tags).toEqual({ 'first-isolation': 'use' });
226+
227+
// Reuse with different scopes (overwrite)
228+
const scope2 = new Scope();
229+
const isolationScope2 = new Scope();
230+
scope2.setTag('second', 'use');
231+
isolationScope2.setTag('second-isolation', 'use');
232+
233+
setCapturedScopesOnSpan(span, scope2, isolationScope2);
234+
const retrieved2 = getCapturedScopesOnSpan(span);
235+
236+
expect(retrieved2.scope?.getScopeData().tags).toEqual({ second: 'use' });
237+
expect(retrieved2.isolationScope?.getScopeData().tags).toEqual({ 'second-isolation': 'use' });
238+
239+
// Should be the new scopes, not the old ones
240+
expect(retrieved2.scope).toBe(scope2);
241+
expect(retrieved2.isolationScope).toBe(isolationScope2);
242+
});
243+
});
244+
});

0 commit comments

Comments
 (0)