Skip to content

Commit e69948b

Browse files
committed
ref(core): Wrap scopes in WeakRef when storing scopes on spans
We often store scopes 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 scopes 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 162143f commit e69948b

File tree

2 files changed

+295
-6
lines changed

2 files changed

+295
-6
lines changed

packages/core/src/tracing/utils.ts

Lines changed: 46 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,69 @@
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 & {
9-
[SCOPE_ON_START_SPAN_FIELD]?: Scope;
10-
[ISOLATION_SCOPE_ON_START_SPAN_FIELD]?: Scope;
12+
[SCOPE_ON_START_SPAN_FIELD]?: ScopeWeakRef;
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);
17-
addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);
53+
addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, wrapScopeWithWeakRef(isolationScope));
54+
addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, wrapScopeWithWeakRef(scope));
1855
}
1956
}
2057

2158
/**
2259
* Grabs the scope and isolation scope off a span that were active when the span was started.
60+
* If WeakRef was used and scopes have been garbage collected, returns undefined for those scopes.
2361
*/
2462
export function getCapturedScopesOnSpan(span: Span): { scope?: Scope; isolationScope?: Scope } {
63+
const spanWithScopes = span as SpanWithScopes;
64+
2565
return {
26-
scope: (span as SpanWithScopes)[SCOPE_ON_START_SPAN_FIELD],
27-
isolationScope: (span as SpanWithScopes)[ISOLATION_SCOPE_ON_START_SPAN_FIELD],
66+
scope: unwrapScopeFromWeakRef(spanWithScopes[SCOPE_ON_START_SPAN_FIELD]),
67+
isolationScope: unwrapScopeFromWeakRef(spanWithScopes[ISOLATION_SCOPE_ON_START_SPAN_FIELD]),
2868
};
2969
}
Lines changed: 249 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,249 @@
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', () => {
48+
const span = createMockSpan();
49+
const scope = new Scope();
50+
const isolationScope = new Scope();
51+
52+
setCapturedScopesOnSpan(span, scope, isolationScope);
53+
54+
// Check that WeakRef instances were stored
55+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
56+
const spanWithScopes = span as any;
57+
expect(spanWithScopes._sentryScope).toBeInstanceOf(WeakRef);
58+
expect(spanWithScopes._sentryIsolationScope).toBeInstanceOf(WeakRef);
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 scopes were stored directly
80+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
81+
const spanWithScopes = span as any;
82+
expect(spanWithScopes._sentryScope).toBe(scope);
83+
expect(spanWithScopes._sentryIsolationScope).toBe(isolationScope);
84+
85+
// When WeakRef is available, check that stored values are not WeakRef instances
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 (simulating garbage collection)
110+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
111+
const spanWithScopes = span as any;
112+
const mockScopeWeakRef = {
113+
deref: vi.fn().mockReturnValue(undefined),
114+
};
115+
const mockIsolationScopeWeakRef = {
116+
deref: vi.fn().mockReturnValue(undefined),
117+
};
118+
119+
spanWithScopes._sentryScope = mockScopeWeakRef;
120+
spanWithScopes._sentryIsolationScope = mockIsolationScopeWeakRef;
121+
122+
const retrieved = getCapturedScopesOnSpan(span);
123+
expect(retrieved.scope).toBeUndefined();
124+
expect(retrieved.isolationScope).toBeUndefined();
125+
expect(mockScopeWeakRef.deref).toHaveBeenCalled();
126+
expect(mockIsolationScopeWeakRef.deref).toHaveBeenCalled();
127+
});
128+
129+
it('handles corrupted WeakRef objects gracefully', () => {
130+
const span = createMockSpan();
131+
132+
// Simulate corrupted WeakRef objects
133+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
134+
const spanWithScopes = span as any;
135+
spanWithScopes._sentryScope = {
136+
deref: vi.fn().mockImplementation(() => {
137+
throw new Error('WeakRef deref failed');
138+
}),
139+
};
140+
spanWithScopes._sentryIsolationScope = {
141+
deref: vi.fn().mockImplementation(() => {
142+
throw new Error('WeakRef deref failed');
143+
}),
144+
};
145+
146+
const retrieved = getCapturedScopesOnSpan(span);
147+
expect(retrieved.scope).toBeUndefined();
148+
expect(retrieved.isolationScope).toBeUndefined();
149+
});
150+
151+
it('preserves scope data when using WeakRef', () => {
152+
const span = createMockSpan();
153+
const scope = new Scope();
154+
const isolationScope = new Scope();
155+
156+
// Add various types of data to scopes
157+
scope.setTag('string-tag', 'value');
158+
scope.setTag('number-tag', 123);
159+
scope.setTag('boolean-tag', true);
160+
scope.setContext('test-context', { key: 'value' });
161+
scope.setUser({ id: 'test-user' });
162+
163+
isolationScope.setExtra('extra-data', { complex: { nested: 'object' } });
164+
isolationScope.setLevel('warning');
165+
166+
setCapturedScopesOnSpan(span, scope, isolationScope);
167+
const retrieved = getCapturedScopesOnSpan(span);
168+
169+
// Verify all data is preserved
170+
expect(retrieved.scope?.getScopeData().tags).toEqual({
171+
'string-tag': 'value',
172+
'number-tag': 123,
173+
'boolean-tag': true,
174+
});
175+
expect(retrieved.scope?.getScopeData().contexts).toEqual({
176+
'test-context': { key: 'value' },
177+
});
178+
expect(retrieved.scope?.getScopeData().user).toEqual({ id: 'test-user' });
179+
180+
expect(retrieved.isolationScope?.getScopeData().extra).toEqual({
181+
'extra-data': { complex: { nested: 'object' } },
182+
});
183+
expect(retrieved.isolationScope?.getScopeData().level).toBe('warning');
184+
});
185+
186+
it('handles multiple spans with different scopes', () => {
187+
const span1 = createMockSpan();
188+
const span2 = createMockSpan();
189+
190+
const scope1 = new Scope();
191+
const scope2 = new Scope();
192+
const isolationScope1 = new Scope();
193+
const isolationScope2 = new Scope();
194+
195+
scope1.setTag('span', '1');
196+
scope2.setTag('span', '2');
197+
isolationScope1.setTag('isolation', '1');
198+
isolationScope2.setTag('isolation', '2');
199+
200+
setCapturedScopesOnSpan(span1, scope1, isolationScope1);
201+
setCapturedScopesOnSpan(span2, scope2, isolationScope2);
202+
203+
const retrieved1 = getCapturedScopesOnSpan(span1);
204+
const retrieved2 = getCapturedScopesOnSpan(span2);
205+
206+
expect(retrieved1.scope?.getScopeData().tags).toEqual({ span: '1' });
207+
expect(retrieved1.isolationScope?.getScopeData().tags).toEqual({ isolation: '1' });
208+
209+
expect(retrieved2.scope?.getScopeData().tags).toEqual({ span: '2' });
210+
expect(retrieved2.isolationScope?.getScopeData().tags).toEqual({ isolation: '2' });
211+
212+
// Ensure they are different scope instances
213+
expect(retrieved1.scope).not.toBe(retrieved2.scope);
214+
expect(retrieved1.isolationScope).not.toBe(retrieved2.isolationScope);
215+
});
216+
217+
it('handles span reuse correctly', () => {
218+
const span = createMockSpan();
219+
220+
// First use
221+
const scope1 = new Scope();
222+
const isolationScope1 = new Scope();
223+
scope1.setTag('first', 'use');
224+
isolationScope1.setTag('first-isolation', 'use');
225+
226+
setCapturedScopesOnSpan(span, scope1, isolationScope1);
227+
const retrieved1 = getCapturedScopesOnSpan(span);
228+
229+
expect(retrieved1.scope?.getScopeData().tags).toEqual({ first: 'use' });
230+
expect(retrieved1.isolationScope?.getScopeData().tags).toEqual({ 'first-isolation': 'use' });
231+
232+
// Reuse with different scopes (overwrite)
233+
const scope2 = new Scope();
234+
const isolationScope2 = new Scope();
235+
scope2.setTag('second', 'use');
236+
isolationScope2.setTag('second-isolation', 'use');
237+
238+
setCapturedScopesOnSpan(span, scope2, isolationScope2);
239+
const retrieved2 = getCapturedScopesOnSpan(span);
240+
241+
expect(retrieved2.scope?.getScopeData().tags).toEqual({ second: 'use' });
242+
expect(retrieved2.isolationScope?.getScopeData().tags).toEqual({ 'second-isolation': 'use' });
243+
244+
// Should be the new scopes, not the old ones
245+
expect(retrieved2.scope).toBe(scope2);
246+
expect(retrieved2.isolationScope).toBe(isolationScope2);
247+
});
248+
});
249+
});

0 commit comments

Comments
 (0)