fix(opentelemetry): Use WeakRef for context stored on scope to prevent memory leak#20328
fix(opentelemetry): Use WeakRef for context stored on scope to prevent memory leak#20328
Conversation
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 1142bec. Configure here.
| expect(storedRef).toBeDefined(); | ||
| expect(typeof (storedRef as { deref?: unknown }).deref).toBe('function'); | ||
| } | ||
| }); |
There was a problem hiding this comment.
Test conditional makes assertions silently skippable
Low Severity
The test "uses WeakRef when available" wraps all its expect assertions inside if (typeof WeakRef !== 'undefined'). If WeakRef were ever unavailable in the test environment, the test would pass silently without asserting anything. Per the project review rules, conditionals in a single test are discouraged — this could be split into two separate tests (one for when WeakRef is available, one for when it isn't) to ensure assertions always run.
Triggered by project rule: PR Review Guidelines for Cursor Bot
Reviewed by Cursor Bugbot for commit 1142bec. Configure here.
size-limit report 📦
|
…t memory leak When using pooled connections (e.g., pg) with OTel instrumentation, patched callbacks can retain references to contexts. Previously, contexts held strong references to scopes, and scopes held strong references back to contexts, creating a circular reference that prevented garbage collection. This change: - Adds a shared WeakRef utility (makeWeakRef/derefWeakRef) in @sentry/core - Uses WeakRef for the context stored on scope, breaking the circular reference - Refactors tracing/utils.ts to use the shared utility - Adds comprehensive unit tests for the WeakRef utility Fixes #20174 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Tests for getScopesFromContext, setScopesOnContext, setContextOnScope, and getContextFromScope including WeakRef behavior verification. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1142bec to
e4c6473
Compare


closes #20174
closes JS-2106
When using pooled connections (e.g., pg) with OTel instrumentation, patched callbacks can retain references to contexts. Previously, contexts held strong references to scopes, and scopes held strong references back to contexts, creating a circular reference that prevented garbage collection.
This change:
Load tests with Artillery ran against the reproduction s1gr1d/sentry-js-20174-fastify-memory before and after the fix. With reusing the
makeWeakRefandderefWeakRefthe memory leak is gone. If it makes more sense to split this up into two PRs (1. exportingmakeWeakRefandderefWeakRefand 2. the actual fix, I'm happy to do it)