From 402042ce0b34709ba8899b15f8d06de367db8752 Mon Sep 17 00:00:00 2001 From: Alexander Dinauer Date: Tue, 17 Nov 2026 11:20:57 +0100 Subject: [PATCH 1/2] fix(core): Release intermediate parent scopes Hold immediate scope parents weakly while retaining the SDK initialization root. This prevents escaping asynchronous tasks from retaining an unbounded chain of historical Scopes instances. Fixes #6248 Co-Authored-By: Claude --- .../opentelemetry/SentryContextWrapperTest.kt | 47 ++++++++++++++++++ .../sentry/spring7/SentryTaskDecoratorTest.kt | 26 ++++++++++ .../spring7/webflux/SentryScheduleHookTest.kt | 25 ++++++++++ .../spring/jakarta/SentryTaskDecoratorTest.kt | 26 ++++++++++ .../jakarta/webflux/SentryScheduleHookTest.kt | 25 ++++++++++ .../sentry/spring/SentryTaskDecoratorTest.kt | 26 ++++++++++ .../spring/webflux/SentryScheduleHookTest.kt | 25 ++++++++++ sentry/src/main/java/io/sentry/IScopes.java | 6 +-- sentry/src/main/java/io/sentry/Scopes.java | 28 +++++------ .../main/java/io/sentry/util/ScopesUtil.java | 26 +++++----- sentry/src/test/java/io/sentry/ScopesTest.kt | 49 +++++++++++++++++++ sentry/src/test/java/io/sentry/SentryTest.kt | 23 +++++++++ .../test/java/io/sentry/SentryWrapperTest.kt | 24 +++++++++ 13 files changed, 327 insertions(+), 29 deletions(-) diff --git a/sentry-opentelemetry/sentry-opentelemetry-bootstrap/src/test/kotlin/io/sentry/opentelemetry/SentryContextWrapperTest.kt b/sentry-opentelemetry/sentry-opentelemetry-bootstrap/src/test/kotlin/io/sentry/opentelemetry/SentryContextWrapperTest.kt index c0647cd9c01..538532eb111 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-bootstrap/src/test/kotlin/io/sentry/opentelemetry/SentryContextWrapperTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-bootstrap/src/test/kotlin/io/sentry/opentelemetry/SentryContextWrapperTest.kt @@ -1,14 +1,31 @@ package io.sentry.opentelemetry +import com.google.common.truth.Truth.assertThat +import io.opentelemetry.api.trace.Span +import io.opentelemetry.api.trace.SpanContext +import io.opentelemetry.api.trace.TraceFlags +import io.opentelemetry.api.trace.TraceState import io.opentelemetry.context.Context +import io.sentry.Scope +import io.sentry.Scopes import io.sentry.Sentry +import io.sentry.SentryOptions import io.sentry.opentelemetry.SentryOtelKeys.SENTRY_SCOPES_KEY import junit.framework.TestCase.assertNull import junit.framework.TestCase.assertTrue +import kotlin.test.AfterTest import kotlin.test.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever class SentryContextWrapperTest { + @AfterTest + fun tearDown() { + SentryWeakSpanStorage.getInstance().clear() + Sentry.close() + } + @Test fun `ensure noop scopes are not stored on Context`() { val context = Context.root() @@ -17,4 +34,34 @@ class SentryContextWrapperTest { val wrappedContext = SentryContextWrapper.wrap(context) assertNull(wrappedContext.get(SENTRY_SCOPES_KEY)) } + + @Test + fun `uses span scopes when context scopes are the live weak parent`() { + val options = SentryOptions().apply { dsn = "https://key@sentry.io/proj" } + val rootScopes = Scopes(Scope(options), Scope(options), Scope(options), "root") + val contextScopes = rootScopes.forkedCurrentScope("context") + contextScopes.scope.setTag("source", "context") + val spanScopes = contextScopes.forkedCurrentScope("span") + spanScopes.scope.setTag("source", "span") + + val spanContext = + SpanContext.create( + "f9118105af4a2d42b4124532cd1065ff", + "424cffc8f94feeee", + TraceFlags.getSampled(), + TraceState.getDefault(), + ) + val span = Span.wrap(spanContext) + val sentrySpan = mock() + whenever(sentrySpan.scopes).thenReturn(spanScopes) + SentryWeakSpanStorage.getInstance().storeSentrySpan(spanContext, sentrySpan) + val context = Context.root().with(SENTRY_SCOPES_KEY, contextScopes).with(span) + + System.gc() + val wrappedContext = SentryContextWrapper.wrap(context) + val selectedScopes = wrappedContext.get(SENTRY_SCOPES_KEY) + + assertThat(selectedScopes).isNotNull() + assertThat(selectedScopes!!.scope.tags["source"]).isEqualTo("span") + } } diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryTaskDecoratorTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryTaskDecoratorTest.kt index d589537d59c..619092c3419 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryTaskDecoratorTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryTaskDecoratorTest.kt @@ -1,19 +1,31 @@ package io.sentry.spring7 +import io.sentry.IScopes import io.sentry.Sentry import io.sentry.test.initForTest +import java.lang.ref.WeakReference import java.util.concurrent.ExecutorService import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import org.awaitility.kotlin.await class SentryTaskDecoratorTest { private val dsn = "http://key@localhost/proj" private lateinit var executor: ExecutorService + private fun decorateFromChildScopes(): Pair> { + val childScopes = Sentry.getCurrentScopes().forkedCurrentScope("child") + val decoratedRunnable = + childScopes.makeCurrent().use { SentryTaskDecorator().decorate(Runnable {}) } + return decoratedRunnable to WeakReference(childScopes) + } + @BeforeTest fun beforeTest() { executor = Executors.newSingleThreadExecutor() @@ -25,6 +37,20 @@ class SentryTaskDecoratorTest { executor.shutdown() } + @Test + fun `decorated task does not strongly retain scheduling scopes`() { + initForTest { it.dsn = dsn } + val (decoratedRunnable, childReference) = decorateFromChildScopes() + + await.atMost(5, TimeUnit.SECONDS).untilAsserted { + System.gc() + System.runFinalization() + assertNull(childReference.get()) + } + + decoratedRunnable.run() + } + @Test fun `scopes is reset to its state within the thread after decoration is done`() { initForTest { it.dsn = dsn } diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryScheduleHookTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryScheduleHookTest.kt index 189acf89d52..9b2fc44f065 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryScheduleHookTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryScheduleHookTest.kt @@ -1,21 +1,32 @@ package io.sentry.spring7.webflux +import io.sentry.IScopes import io.sentry.Sentry import io.sentry.test.initForTest +import java.lang.ref.WeakReference import java.util.concurrent.ExecutorService import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotEquals +import kotlin.test.assertNull import kotlin.test.assertTrue +import org.awaitility.kotlin.await class SentryScheduleHookTest { private val dsn = "http://key@localhost/proj" private lateinit var executor: ExecutorService + private fun applyHookFromChildScopes(): Pair> { + val childScopes = Sentry.getCurrentScopes().forkedCurrentScope("child") + val wrappedRunnable = childScopes.makeCurrent().use { SentryScheduleHook().apply(Runnable {}) } + return wrappedRunnable to WeakReference(childScopes) + } + @BeforeTest fun beforeTest() { executor = Executors.newSingleThreadExecutor() @@ -58,6 +69,20 @@ class SentryScheduleHookTest { .get() } + @Test + fun `wrapped task does not strongly retain scheduling scopes`() { + initForTest { it.dsn = dsn } + val (wrappedRunnable, childReference) = applyHookFromChildScopes() + + await.atMost(5, TimeUnit.SECONDS).untilAsserted { + System.gc() + System.runFinalization() + assertNull(childReference.get()) + } + + wrappedRunnable.run() + } + @Test fun `known maintenance runnable class names are excluded`() { val classNames = diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryTaskDecoratorTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryTaskDecoratorTest.kt index 1f0f74d25cf..bea22857f48 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryTaskDecoratorTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryTaskDecoratorTest.kt @@ -1,19 +1,31 @@ package io.sentry.spring.jakarta +import io.sentry.IScopes import io.sentry.Sentry import io.sentry.test.initForTest +import java.lang.ref.WeakReference import java.util.concurrent.ExecutorService import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import org.awaitility.kotlin.await class SentryTaskDecoratorTest { private val dsn = "http://key@localhost/proj" private lateinit var executor: ExecutorService + private fun decorateFromChildScopes(): Pair> { + val childScopes = Sentry.getCurrentScopes().forkedCurrentScope("child") + val decoratedRunnable = + childScopes.makeCurrent().use { SentryTaskDecorator().decorate(Runnable {}) } + return decoratedRunnable to WeakReference(childScopes) + } + @BeforeTest fun beforeTest() { executor = Executors.newSingleThreadExecutor() @@ -25,6 +37,20 @@ class SentryTaskDecoratorTest { executor.shutdown() } + @Test + fun `decorated task does not strongly retain scheduling scopes`() { + initForTest { it.dsn = dsn } + val (decoratedRunnable, childReference) = decorateFromChildScopes() + + await.atMost(5, TimeUnit.SECONDS).untilAsserted { + System.gc() + System.runFinalization() + assertNull(childReference.get()) + } + + decoratedRunnable.run() + } + @Test fun `scopes is reset to its state within the thread after decoration is done`() { initForTest { it.dsn = dsn } diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryScheduleHookTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryScheduleHookTest.kt index 07249866a7e..52f67f2354c 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryScheduleHookTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryScheduleHookTest.kt @@ -1,21 +1,32 @@ package io.sentry.spring.jakarta.webflux +import io.sentry.IScopes import io.sentry.Sentry import io.sentry.test.initForTest +import java.lang.ref.WeakReference import java.util.concurrent.ExecutorService import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotEquals +import kotlin.test.assertNull import kotlin.test.assertTrue +import org.awaitility.kotlin.await class SentryScheduleHookTest { private val dsn = "http://key@localhost/proj" private lateinit var executor: ExecutorService + private fun applyHookFromChildScopes(): Pair> { + val childScopes = Sentry.getCurrentScopes().forkedCurrentScope("child") + val wrappedRunnable = childScopes.makeCurrent().use { SentryScheduleHook().apply(Runnable {}) } + return wrappedRunnable to WeakReference(childScopes) + } + @BeforeTest fun beforeTest() { executor = Executors.newSingleThreadExecutor() @@ -58,6 +69,20 @@ class SentryScheduleHookTest { .get() } + @Test + fun `wrapped task does not strongly retain scheduling scopes`() { + initForTest { it.dsn = dsn } + val (wrappedRunnable, childReference) = applyHookFromChildScopes() + + await.atMost(5, TimeUnit.SECONDS).untilAsserted { + System.gc() + System.runFinalization() + assertNull(childReference.get()) + } + + wrappedRunnable.run() + } + @Test fun `known maintenance runnable class names are excluded`() { val classNames = diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/SentryTaskDecoratorTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/SentryTaskDecoratorTest.kt index 5fc955d0031..7ed8cbb8edd 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/SentryTaskDecoratorTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/SentryTaskDecoratorTest.kt @@ -1,19 +1,31 @@ package io.sentry.spring +import io.sentry.IScopes import io.sentry.Sentry import io.sentry.test.initForTest +import java.lang.ref.WeakReference import java.util.concurrent.ExecutorService import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import org.awaitility.kotlin.await class SentryTaskDecoratorTest { private val dsn = "http://key@localhost/proj" private lateinit var executor: ExecutorService + private fun decorateFromChildScopes(): Pair> { + val childScopes = Sentry.getCurrentScopes().forkedCurrentScope("child") + val decoratedRunnable = + childScopes.makeCurrent().use { SentryTaskDecorator().decorate(Runnable {}) } + return decoratedRunnable to WeakReference(childScopes) + } + @BeforeTest fun beforeTest() { executor = Executors.newSingleThreadExecutor() @@ -25,6 +37,20 @@ class SentryTaskDecoratorTest { executor.shutdown() } + @Test + fun `decorated task does not strongly retain scheduling scopes`() { + initForTest { it.dsn = dsn } + val (decoratedRunnable, childReference) = decorateFromChildScopes() + + await.atMost(5, TimeUnit.SECONDS).untilAsserted { + System.gc() + System.runFinalization() + assertNull(childReference.get()) + } + + decoratedRunnable.run() + } + @Test fun `scopes is reset to its state within the thread after decoration is done`() { initForTest { it.dsn = dsn } diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryScheduleHookTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryScheduleHookTest.kt index 2c45bf1daa8..98ce91b73fd 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryScheduleHookTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryScheduleHookTest.kt @@ -1,21 +1,32 @@ package io.sentry.spring.webflux +import io.sentry.IScopes import io.sentry.Sentry import io.sentry.test.initForTest +import java.lang.ref.WeakReference import java.util.concurrent.ExecutorService import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotEquals +import kotlin.test.assertNull import kotlin.test.assertTrue +import org.awaitility.kotlin.await class SentryScheduleHookTest { private val dsn = "http://key@localhost/proj" private lateinit var executor: ExecutorService + private fun applyHookFromChildScopes(): Pair> { + val childScopes = Sentry.getCurrentScopes().forkedCurrentScope("child") + val wrappedRunnable = childScopes.makeCurrent().use { SentryScheduleHook().apply(Runnable {}) } + return wrappedRunnable to WeakReference(childScopes) + } + @BeforeTest fun beforeTest() { executor = Executors.newSingleThreadExecutor() @@ -58,6 +69,20 @@ class SentryScheduleHookTest { .get() } + @Test + fun `wrapped task does not strongly retain scheduling scopes`() { + initForTest { it.dsn = dsn } + val (wrappedRunnable, childReference) = applyHookFromChildScopes() + + await.atMost(5, TimeUnit.SECONDS).untilAsserted { + System.gc() + System.runFinalization() + assertNull(childReference.get()) + } + + wrappedRunnable.run() + } + @Test fun `known maintenance runnable class names are excluded`() { val classNames = diff --git a/sentry/src/main/java/io/sentry/IScopes.java b/sentry/src/main/java/io/sentry/IScopes.java index acf5485ec16..84622f15b67 100644 --- a/sentry/src/main/java/io/sentry/IScopes.java +++ b/sentry/src/main/java/io/sentry/IScopes.java @@ -468,10 +468,10 @@ default void configureScope(@NotNull ScopeCallback callback) { IScope getGlobalScope(); /** - * Returns the parent of this Scopes instance or null, if it does not have a parent. The parent is - * the Scopes instance this instance was forked from. + * Returns the parent of this Scopes instance. If the immediate parent has been garbage collected, + * returns the root Scopes from the same SDK initialization. Returns null for root Scopes. * - * @return parent Scopes or null + * @return parent or SDK initialization root Scopes, or null for root Scopes */ @ApiStatus.Internal @Nullable diff --git a/sentry/src/main/java/io/sentry/Scopes.java b/sentry/src/main/java/io/sentry/Scopes.java index ba3f83d347b..4d790f52221 100644 --- a/sentry/src/main/java/io/sentry/Scopes.java +++ b/sentry/src/main/java/io/sentry/Scopes.java @@ -14,6 +14,7 @@ import io.sentry.util.SpanUtils; import io.sentry.util.TracingUtils; import java.io.Closeable; +import java.lang.ref.WeakReference; import java.util.List; import java.util.concurrent.RejectedExecutionException; import org.jetbrains.annotations.ApiStatus; @@ -26,7 +27,7 @@ public final class Scopes implements IScopes { private final @NotNull IScope isolationScope; private final @NotNull IScope globalScope; - private final @Nullable Scopes parentScopes; + private final @Nullable WeakReference parentScopes; private final @NotNull Scopes sdkInitializationRoot; private final @NotNull String creator; @@ -56,7 +57,7 @@ private Scopes( this.scope = scope; this.isolationScope = isolationScope; this.globalScope = globalScope; - this.parentScopes = parentScopes; + this.parentScopes = parentScopes == null ? null : new WeakReference<>(parentScopes); this.sdkInitializationRoot = sdkInitializationRoot == null ? this : sdkInitializationRoot; this.creator = creator; @@ -93,24 +94,23 @@ private Scopes( @Override @ApiStatus.Internal public @Nullable IScopes getParentScopes() { - return parentScopes; + if (parentScopes == null) { + return null; + } + final @Nullable Scopes parent = parentScopes.get(); + return parent == null ? sdkInitializationRoot : parent; } @Override @ApiStatus.Internal public boolean isAncestorOf(final @Nullable IScopes otherScopes) { - if (otherScopes == null) { - return false; - } - - if (this == otherScopes) { - return true; - } - - if (otherScopes.getParentScopes() != null) { - return isAncestorOf(otherScopes.getParentScopes()); + @Nullable IScopes current = otherScopes; + while (current != null) { + if (this == current) { + return true; + } + current = current.getParentScopes(); } - return false; } diff --git a/sentry/src/main/java/io/sentry/util/ScopesUtil.java b/sentry/src/main/java/io/sentry/util/ScopesUtil.java index 2d1034cee01..f8dcf957901 100644 --- a/sentry/src/main/java/io/sentry/util/ScopesUtil.java +++ b/sentry/src/main/java/io/sentry/util/ScopesUtil.java @@ -11,8 +11,9 @@ * A util for printing the scopes chain from passed in scopes all the way up to its initial * ancestor. * - *

It walks up the parents of each scopes instance until it reaches a parent of null. The scopes - * without a parent are the ones created in Sentry.init. + *

It walks up the parents of each scopes instance until it reaches a parent of null. Parent + * references are weak, so collected intermediate parents are skipped and traversal continues from + * the root Scopes created in Sentry.init. */ @ApiStatus.Internal public final class ScopesUtil { @@ -31,10 +32,11 @@ public static void printScopesChain(final @Nullable IScopes scopes) { @SuppressWarnings("ObjectToString") private static void printScopesChainInternal(final @Nullable IScopes someScopes) { - if (someScopes != null) { - if (someScopes instanceof Scopes) { - Scopes scopes = (Scopes) someScopes; - String info = + @Nullable IScopes current = someScopes; + while (current != null) { + if (current instanceof Scopes) { + final Scopes scopes = (Scopes) current; + final String info = String.format( "%-25s {g=%-25s, i=%-25s, c=%-25s} [%s]", scopes, @@ -43,14 +45,14 @@ private static void printScopesChainInternal(final @Nullable IScopes someScopes) scopes.getScope(), scopes.getCreator()); System.out.println(info); - printScopesChainInternal(someScopes.getParentScopes()); - } else if (someScopes instanceof ScopesAdapter) { - printScopesChainInternal(Sentry.getCurrentScopes()); + current = current.getParentScopes(); + } else if (current instanceof ScopesAdapter) { + current = Sentry.getCurrentScopes(); } else { - System.out.println("Hit unhandled Scopes class" + someScopes.getClass()); + System.out.println("Hit unhandled Scopes class" + current.getClass()); + return; } - } else { - System.out.println("-"); } + System.out.println("-"); } } diff --git a/sentry/src/test/java/io/sentry/ScopesTest.kt b/sentry/src/test/java/io/sentry/ScopesTest.kt index c319b25a57a..cc0adc78bef 100644 --- a/sentry/src/test/java/io/sentry/ScopesTest.kt +++ b/sentry/src/test/java/io/sentry/ScopesTest.kt @@ -23,9 +23,11 @@ import io.sentry.test.initForTest import io.sentry.util.HintUtils import io.sentry.util.StringUtils import java.io.File +import java.lang.ref.WeakReference import java.nio.file.Files import java.util.Queue import java.util.UUID +import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference import junit.framework.TestCase.assertSame import kotlin.test.AfterTest @@ -39,6 +41,7 @@ import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.test.fail +import org.awaitility.kotlin.await import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argWhere @@ -82,6 +85,23 @@ class ScopesTest { return createTestScopes(options).also { it.bindClient(SentryClient(options)) } } + private fun createForkWithWeakParent( + options: SentryOptions + ): Triple, WeakReference> { + val rootScopes = createScopes(options) + val parentScopes = rootScopes.forkedCurrentScope("parent") + val childScopes = parentScopes.forkedCurrentScope("child") + return Triple(childScopes, WeakReference(parentScopes), WeakReference(rootScopes)) + } + + private fun assertEventuallyCollected(reference: WeakReference<*>) { + await.atMost(5, TimeUnit.SECONDS).untilAsserted { + System.gc() + System.runFinalization() + assertThat(reference.get()).isNull() + } + } + @Test fun `when no dsn available, ctor throws illegal arg`() { val ex = @@ -112,6 +132,35 @@ class ScopesTest { assertFalse(firstRoot.isFromSameSdkInitialization(secondRoot)) } + @Test + fun `fork retains initialization root instead of immediate parent`() { + val options = SentryOptions() + options.dsn = "https://key@sentry.io/proj" + options.setSerializer(mock()) + val (childScopes, parentReference, rootReference) = createForkWithWeakParent(options) + + assertSame(parentReference.get(), childScopes.parentScopes) + assertEventuallyCollected(parentReference) + + val rootScopes = rootReference.get() + assertNotNull(rootScopes) + assertSame(rootScopes, childScopes.parentScopes) + assertTrue(rootScopes.isAncestorOf(childScopes)) + assertTrue(rootScopes.isFromSameSdkInitialization(childScopes)) + } + + @Test + fun `ancestor traversal does not overflow for a deep chain`() { + val options = SentryOptions() + options.dsn = "https://key@sentry.io/proj" + options.setSerializer(mock()) + val rootScopes = createScopes(options) + val descendants = mutableListOf(rootScopes) + repeat(5_000) { descendants += descendants.last().forkedCurrentScope("child") } + + assertTrue(rootScopes.isAncestorOf(descendants.last())) + } + @Test fun `when isolation scope is forked, integrations are not registered`() { val integrationMock = mock() diff --git a/sentry/src/test/java/io/sentry/SentryTest.kt b/sentry/src/test/java/io/sentry/SentryTest.kt index b65dda88c46..a295a067006 100644 --- a/sentry/src/test/java/io/sentry/SentryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTest.kt @@ -30,6 +30,7 @@ import io.sentry.util.thread.ThreadChecker import java.io.Closeable import java.io.File import java.io.FileReader +import java.lang.ref.WeakReference import java.nio.file.Files import java.util.Properties import java.util.concurrent.CompletableFuture @@ -69,6 +70,11 @@ class SentryTest { @get:Rule val tmpDir = TemporaryFolder() + private fun createScopesWithWeakParent(): Pair> { + val parentScopes = Sentry.getCurrentScopes().forkedCurrentScope("parent") + return parentScopes.forkedCurrentScope("child") to WeakReference(parentScopes) + } + @BeforeTest @AfterTest fun beforeTest() { @@ -1538,6 +1544,23 @@ class SentryTest { assertSame(Sentry.getCurrentScopes(), fromOtherThread) } + @Test + fun `in globalHubMode forked scopes remain valid after their weak parent is collected`() { + initForTest({ o -> o.dsn = dsn }, true) + val rootScopes = Sentry.getCurrentScopes() + val (childScopes, parentReference) = createScopesWithWeakParent() + Sentry.setCurrentScopes(childScopes) + + await.untilAsserted { + System.gc() + System.runFinalization() + assertNull(parentReference.get()) + } + + assertTrue(rootScopes.isAncestorOf(childScopes)) + assertSame(childScopes, Sentry.getCurrentScopes()) + } + @Test fun `in globalHubMode scopes left over from a closed SDK are ignored`() { initForTest({ o -> o.dsn = dsn }, true) diff --git a/sentry/src/test/java/io/sentry/SentryWrapperTest.kt b/sentry/src/test/java/io/sentry/SentryWrapperTest.kt index 0ed46d8fa38..a6751a195bd 100644 --- a/sentry/src/test/java/io/sentry/SentryWrapperTest.kt +++ b/sentry/src/test/java/io/sentry/SentryWrapperTest.kt @@ -1,19 +1,29 @@ package io.sentry import io.sentry.test.initForTest +import java.lang.ref.WeakReference import java.util.concurrent.CompletableFuture import java.util.concurrent.ExecutorService import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import org.awaitility.kotlin.await class SentryWrapperTest { private val dsn = "http://key@localhost/proj" private lateinit var executor: ExecutorService + private fun wrapRunnableFromChildScopes(): Pair> { + val childScopes = Sentry.getCurrentScopes().forkedCurrentScope("child") + val wrappedRunnable = childScopes.makeCurrent().use { SentryWrapper.wrapRunnable {} } + return wrappedRunnable to WeakReference(childScopes) + } + @BeforeTest fun beforeTest() { executor = Executors.newSingleThreadExecutor() @@ -244,6 +254,20 @@ class SentryWrapperTest { assertEquals(2, clonedEvent2?.breadcrumbs?.size) } + @Test + fun `wrapped runnable does not strongly retain scheduling scopes`() { + initForTest { it.dsn = dsn } + val (wrappedRunnable, childReference) = wrapRunnableFromChildScopes() + + await.atMost(5, TimeUnit.SECONDS).untilAsserted { + System.gc() + System.runFinalization() + assertNull(childReference.get()) + } + + wrappedRunnable.run() + } + @Test fun `scopes is reset to state within the thread after isolated runnable is done`() { initForTest { it.dsn = dsn } From 4e4a0b68bf13db4f7a641f9d292986eb6794a2ef Mon Sep 17 00:00:00 2001 From: Alexander Dinauer Date: Tue, 17 Nov 2026 11:21:36 +0100 Subject: [PATCH 2/2] changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cdc4d0f5eb9..546c4566874 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -85,6 +85,7 @@ ### Fixes +- Prevent asynchronous scope propagation from retaining unbounded chains of historical scopes ([#6637](https://github.com/getsentry/sentry-java/pull/6637)) - Add opt-in support for matching GraphQL ignored error types against classification specifications via `sentry.graphql.enable-specification-error-type-filtering` ([#6092](https://github.com/getsentry/sentry-java/pull/6092)) - Session Replay: Fix `SentryOkHttpInterceptor` hanging forever on responses whose body has no known length, such as Server-Sent Events or a gzipped response, when network details are enabled for the URL ([#6231](https://github.com/getsentry/sentry-java/pull/6231)) - Session Replay: `SentryOkHttpInterceptor` now captures network request and response details only while Session Replay is recording or buffering ([#6486](https://github.com/getsentry/sentry-java/pull/6486))