Title: Memory leak: SentryScheduleHook builds an unbounded Scopes chain for self-rescheduling tasks (reactor-netty pool eviction) · Issue #6248 · getsentry/sentry-java · GitHub
Open Graph Title: Memory leak: SentryScheduleHook builds an unbounded Scopes chain for self-rescheduling tasks (reactor-netty pool eviction) · Issue #6248 · getsentry/sentry-java
X Title: Memory leak: SentryScheduleHook builds an unbounded Scopes chain for self-rescheduling tasks (reactor-netty pool eviction) · Issue #6248 · getsentry/sentry-java
Description: Integration sentry-spring-boot-starter-jakarta Java Version 21 Other Error Monitoring Solution No Version 8.46.0 (also reproduced on main, fb3079b) Steps to Reproduce Same kind of leak as #5051, but from reactor-netty's connection pool e...
Open Graph Description: Integration sentry-spring-boot-starter-jakarta Java Version 21 Other Error Monitoring Solution No Version 8.46.0 (also reproduced on main, fb3079b) Steps to Reproduce Same kind of leak as #5051, bu...
X Description: Integration sentry-spring-boot-starter-jakarta Java Version 21 Other Error Monitoring Solution No Version 8.46.0 (also reproduced on main, fb3079b) Steps to Reproduce Same kind of leak as #5051, bu...
Opengraph URL: https://github.com/getsentry/sentry-java/issues/6248
X: @github
Domain: github.com
IPv4 address: 140.82.114.4
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Memory leak: SentryScheduleHook builds an unbounded Scopes chain for self-rescheduling tasks (reactor-netty pool eviction)","articleBody":"### Integration\n\nsentry-spring-boot-starter-jakarta\n\n### Java Version\n\n21\n\n### Other Error Monitoring Solution\n\nNo\n\n### Version\n\n8.46.0 (also reproduced on main, fb3079b)\n\n### Steps to Reproduce\n\nSame kind of leak as #5051, but from reactor-netty's connection pool eviction instead of reactor-kafka. Each eviction run forks `Scopes` from the previous run's fork, so every pool builds a parent chain that is never released. For us that was ~4 GB (97% of the live heap) after 12.8 days, independent of traffic.\n\nOur setup: Spring Boot 3.4.5 WebFlux app (Spring Cloud Gateway 4.2.1, reactor-netty 1.2.5), DSN set, no `io.micrometer:context-propagation` on the classpath, so the starter registers `Schedulers.onScheduleHook(\"sentry\", new SentryScheduleHook())`.\n\n1. Use a reactor-netty `ConnectionProvider` with `.evictInBackground(Duration.ofSeconds(29))`. Each remote address gets its own pool, and its eviction task re-schedules itself on `Schedulers.parallel()` at the end of every run (`SimpleDequePool.evictInBackground` -> `scheduleEviction()`).\n2. Call a few hosts and leave the app running.\n\nMinimal repro, a task that re-schedules itself from inside its own run. It drops into `sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/`:\n\n```kotlin\npackage io.sentry.spring.jakarta.webflux\n\nimport io.sentry.IScopes\nimport io.sentry.Sentry\nimport java.util.concurrent.CountDownLatch\nimport java.util.concurrent.TimeUnit\nimport kotlin.test.Test\nimport kotlin.test.assertTrue\nimport reactor.core.scheduler.Schedulers\n\nclass SentryScheduleHookChainTest {\n private fun depth(s: IScopes?) = generateSequence(s) { it.parentScopes }.count()\n\n @Test\n fun `self-rescheduling task keeps the scopes chain bounded`() {\n Sentry.init { it.dsn = \"https://key@localhost/proj\" }\n Schedulers.onScheduleHook(\"sentry\", SentryScheduleHook())\n val scheduler = Schedulers.newSingle(\"evictor\")\n val depths = mutableListOf\u003cInt>()\n val done = CountDownLatch(1)\n // same shape as reactor-pool's evictInBackground: do the work, then re-arm from inside the run\n lateinit var tick: Runnable\n tick = Runnable {\n depths += depth(Sentry.getCurrentScopes())\n if (depths.size \u003c 1000) scheduler.schedule(tick, 1, TimeUnit.MILLISECONDS)\n else done.countDown()\n }\n scheduler.schedule(tick, 1, TimeUnit.MILLISECONDS)\n try {\n assertTrue(done.await(30, TimeUnit.SECONDS))\n println(\"chain depth: run 1 = ${depths.first()}, run 1000 = ${depths.last()}\")\n assertTrue(depths.last() \u003c 10, \"chain depth grew to ${depths.last()}\")\n } finally {\n Schedulers.resetOnScheduleHook(\"sentry\")\n scheduler.dispose()\n Sentry.close()\n }\n }\n}\n```\n\nOn main (fb3079b, 8.60.0) it prints `chain depth: run 1 = 2, run 1000 = 1001` and fails.\n\n\u003cdetails>\n\u003csummary>Same thing with a real reactor-netty pool\u003c/summary>\n\n```kotlin\npackage io.sentry.spring.jakarta.webflux\n\nimport io.sentry.IScopes\nimport io.sentry.Sentry\nimport java.time.Duration\nimport java.util.concurrent.atomic.AtomicInteger\nimport kotlin.test.Test\nimport reactor.core.publisher.Mono\nimport reactor.core.scheduler.Schedulers\nimport reactor.netty.http.client.HttpClient\nimport reactor.netty.http.server.HttpServer\nimport reactor.netty.resources.ConnectionProvider\n\nclass SentryScheduleHookNettyPoolTest {\n private fun depth(s: IScopes?) = generateSequence(s) { it.parentScopes }.count()\n\n @Test\n fun `reactor-netty pool eviction grows the scopes chain`() {\n Sentry.init { it.dsn = \"https://key@localhost/proj\" }\n Schedulers.onScheduleHook(\"sentry\", SentryScheduleHook())\n val maxDepth = AtomicInteger() // depth of the current scopes whenever something is scheduled\n Schedulers.onScheduleHook(\"probe\") { r ->\n maxDepth.accumulateAndGet(depth(Sentry.getCurrentScopes()), ::maxOf)\n r\n }\n val server = HttpServer.create().port(0).handle { _, res -> res.sendString(Mono.just(\"ok\")) }.bindNow()\n val pool =\n ConnectionProvider.builder(\"repro\")\n .maxIdleTime(Duration.ofMillis(10))\n .evictInBackground(Duration.ofMillis(10)) // 29s in production\n .build()\n HttpClient.create(pool).get().uri(\"http://localhost:${server.port()}/\")\n .responseContent().aggregate().asString().block()\n Thread.sleep(3_000)\n println(\"max scopes chain depth after 3s: ${maxDepth.get()}\")\n Schedulers.resetOnScheduleHook(\"probe\")\n Schedulers.resetOnScheduleHook(\"sentry\")\n pool.dispose()\n server.disposeNow()\n Sentry.close()\n }\n}\n```\n\nOn main this prints a max depth of a few hundred after 3 s (222, 250 and 252 in three runs, reactor-netty 1.2.6 from the module's test classpath). In a local test in our app (8.46.0, reactor-netty 1.2.5) the same setup stays flat without the hook, without `evictInBackground`, or with an empty DSN.\n\n\u003c/details>\n\n### Expected Result\n\nA periodically re-armed task shouldn't keep the `Scopes` of all its previous runs alive. Chain depth and the number of live `Scopes` should stay bounded however long the app runs.\n\n### Actual Result\n\nThe re-arm happens inside the previous wrapped run, so `SentryScheduleHook.apply` forks from the previous run's fork. The pending task holds the newest fork and `parentScopes` is never cleared, so the whole chain stays reachable.\n\nHeap dump from production after 12.8 days of uptime (`-Xmx6g`):\n\n- 63 pools (one per upstream host) -> 63 chains, 2,229,249 links in total. The longest has 38,062 `spring.scheduleHook` forks (12.8 days / 29 s ≈ 38,130 eviction runs).\n- Eclipse MAT leak suspect: 63 `reactor.core.scheduler.SchedulerTask` instances retain ~4.05 GB, 97% of the live heap.\n- About 1.8 KB per link, and every link is empty (no tags, no breadcrumbs). Roughly 300 MB/day.\n\n\u003cdetails>\n\u003csummary>Retention path and per-link contents\u003c/summary>\n\n```\nparallel-N thread (GC root)\n -> ScheduledThreadPoolExecutor$DelayedWorkQueue\n -> ScheduledFutureTask.callable\n -> reactor.core.scheduler.SchedulerTask (also referenced by SimpleDequePool.evictionTask)\n -> SentryScheduleHook$$Lambda (arg$1 = newest Scopes, arg$2 = SimpleDequePool::evictInBackground)\n -> Scopes.parentScopes -> Scopes.parentScopes -> ... (38,062 x \"spring.scheduleHook\")\n -> Scopes \"request.webflux\" (the one current when the pool was created)\n -> Scopes \"Sentry.init\"\n```\n\nEach link is a `Scopes`, a cloned `Scope`, `CombinedScopeView`, an empty breadcrumb queue with its `Object[100]`, 4 empty `ConcurrentHashMap`s, ~13 locks, `PropagationContext`, `Contexts`, the logger/metrics/feedback API objects, etc. The top histogram entries (`Object[]`, `ConcurrentHashMap`, `ReentrantLock$NonfairSync`, `io.sentry.Scope`) all have counts that are multiples of the ~2.23M links.\n\n\u003c/details>\n\nAlso:\n\n- `SentryTaskDecorator` and `SentryWrapper.wrap*` fork the same way. On main, a `ThreadPoolTaskScheduler` with `SentryTaskDecorator` and a `Trigger` schedule went from depth 2 to 301 over 300 runs (`ReschedulingRunnable` re-schedules itself from inside its run; fixed-rate tasks stay at 2).\n- `Scopes.isAncestorOf` is recursive. Since #6004 (8.55.0), `Sentry.getCurrentScopes()` in globalHubMode calls `root.isAncestorOf(scopes)`, so a chain like this can also throw `StackOverflowError` there (20k links overflow a 256 KB stack). We don't use globalHubMode.\n\nWorkaround: `Schedulers.resetOnScheduleHook(\"sentry\")` on `ApplicationReadyEvent` (not in an `ApplicationRunner`, the starter's runner has no `@Order`). Existing chains become collectable after the next eviction run, but scopes are then no longer carried onto Reactor scheduler threads, so events captured after `publishOn`/`subscribeOn` lose the request's scope data. Adding `io.micrometer:context-propagation` also avoids the leak, but turns on `Hooks.enableAutomaticContextPropagation()` globally.\n\n#### Possible fix\n\nAdding the reactor-pool prefixes (`reactor.netty.internal.shaded.reactor.pool.`, `reactor.pool.`) to `EXCLUDED_RUNNABLE_PREFIXES` would fix our case, but not the next self-rescheduling runnable. #5080 did the same for `ConsumerEventLoop`, and a more generic fix was mentioned in #5051 with the downside that \"introducing some sort of scope cloning depth limit would silently break Sentry after a potentially long time of running the application\".\n\nWhat I tried instead: when a task fork (schedule hook, `SentryTaskDecorator`, `SentryWrapper`) is created inside another task fork, directly or under a scope forked within it such as `withScope`, it gets that task fork's parent instead of the current scopes. Scope data is still cloned from the current scopes, only the parent link changes.\n\n```\ntoday: R \u003c- f1 \u003c- f2 \u003c- f3 \u003c- ... (R = scopes current when the task was first scheduled)\nchange: R \u003c- f1, R \u003c- f2, R \u003c- f3, ...\n```\n\nUnlike a depth limit, nothing changes the longer the app runs: run 38,000 gets the same parent as run 1 and still clones its scope data from the run before it, as today, so propagation never stops. Old runs become collectable, and the request/root scopes stay an ancestor, so the #6004 check keeps working. No weak references or class-name list either. With it, both tests above stay at depth 2.\n\n\u003cdetails>\n\u003csummary>Implementation, behavior change, alternatives\u003c/summary>\n\nImplementation: two `@ApiStatus.Internal` default methods on `IScopes` (`forkedScopesForTask` / `forkedCurrentScopeForTask`, defaulting to the existing fork methods), one nullable field in `Scopes` that remembers the parent for task forks (regular forks inherit it), a one-line change at each call site in `SentryScheduleHook`, `SentryTaskDecorator` and `SentryWrapper`, plus delegating overrides in `ScopesAdapter` / `HubAdapter` / `HubScopesWrapper`. I have it on a branch with regression tests that fail on main and pass with the change; the existing `ScopesTest`, `SentryTest` (including the #6004 globalHubMode tests), spring hook/decorator tests and `apiCheck` pass.\n\nBehavior change: forks made from regular scopes are unchanged. For a task fork created inside another task fork, `getParentScopes()` returns the enclosing task's parent, so `intermediateTaskFork.isAncestorOf(laterTaskFork)` becomes false. Besides the #6004 check (unaffected, the root is still an ancestor), the only production caller is `SentryContextWrapper.forkCurrentScopeInternal` in the OTel module; in that case it would fork from the context's scopes instead of the span's, and the active span is still set.\n\nAlternatives I looked at:\n\n- Depth cap: see the #5051 comment above.\n- Weak reference to the parent: behavior depends on GC timing.\n- No parent for task forks: breaks the #6004 stale-scopes check.\n- Parent = root scopes: breaks first-hop ancestry for OTel.\n- Skip one level (parent = current's parent): still unbounded when the re-arm happens inside `withScope` or another nested fork.\n- Reuse the enclosing task fork instead of forking again: tasks scheduled from the same run would share one mutable `Scope`.\n- More exclusion prefixes: needs a new entry for every self-rescheduling runnable.\n\n\u003c/details>\n\nI can send the exclusion-prefix PR right away as a stopgap. Would you also take a PR for the change above (internal API only, against main), or would you rather go another way? Making `isAncestorOf` iterative is independent and could go in first as a small separate PR.\n","author":{"url":"https://github.com/hocaron","@type":"Person","name":"hocaron"},"datePublished":"2026-10-12T14:40:28Z","url":"https://github.com/getsentry/sentry-java/issues/6248"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:9c708eab-4e5c-6280-38af-d50f93879c6a |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | DD32:2F721B:C61E0:119233:6B0463C8 |
| html-safe-nonce | 4b2200308ddc7cc585edae771081d11fe7bb074349fea63c65b8a41897e322c0 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJERDMyOjJGNzIxQjpDNjFFMDoxMTkyMzM6NkIwNDYzQzgiLCJ2aXNpdG9yX2lkIjoiMTExMzM4MTA0NTMzNzg3NTQwMCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 3f4a5e88ea35821c6962e37a5679d3c0c0ef1701359d65b945e62b952b19abce |
| hovercard-subject-tag | issue:5815594559 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/getsentry/sentry-java/6248/issue_layout |
| twitter:image | https://opengraph.githubassets.com/6244c9d500bf402106ba98f7835e625cc230122c3e1a24bfc3499fc4bde5c7c1/getsentry/sentry-java/issues/6248 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/6244c9d500bf402106ba98f7835e625cc230122c3e1a24bfc3499fc4bde5c7c1/getsentry/sentry-java/issues/6248 |
| og:image:alt | Integration sentry-spring-boot-starter-jakarta Java Version 21 Other Error Monitoring Solution No Version 8.46.0 (also reproduced on main, fb3079b) Steps to Reproduce Same kind of leak as #5051, bu... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | hocaron |
| hostname | github.com |
| expected-hostname | github.com |
| None | 2d58451b4bcb73c33c67bfb6b28fb75fe6d5e279daf9b560fa4fd832f3d8c9a6 |
| turbo-cache-control | no-preview |
| go-import | github.com/getsentry/sentry-java git https://github.com/getsentry/sentry-java.git |
| octolytics-dimension-user_id | 1396951 |
| octolytics-dimension-user_login | getsentry |
| octolytics-dimension-repository_id | 3368190 |
| octolytics-dimension-repository_nwo | getsentry/sentry-java |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 3368190 |
| octolytics-dimension-repository_network_root_nwo | getsentry/sentry-java |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 03e114520787ad27289207f153520ef97461127c |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width