Repository navigation
Description
Package
Sentry.Profiling
.NET Flavor
.NET
.NET Version
8.0
OS
Linux
SDK Version
6.6.0 (Sentry.AspNetCore 6.6.0 + Sentry.Profiling 6.6.0)
Self-Hosted Sentry Version
No response (SaaS)
Steps to Reproduce
- ASP.NET Core service on Linux x64 (Rocky 9, kernel 5.14), 8 GB VM, systemd-hosted,
builder.WebHost.UseSentry(...)withoptions.AddProfilingIntegration(). TracesSampleRate: 0.1,ProfilesSampleRate: 0.1.- Run under real production traffic (an idle instance does not reproduce — sampled transactions drive it).
- Watch process RSS over days.
Expected Result
Profiling overhead reaches a bounded steady state.
Actual Result
RSS grows ~0.6 GB/day under steady traffic until kernel OOM-kill at ~6.1 GB anon RSS after ~8 days of uptime. Growth rate is traffic-proportional (~100 MiB/hr at evening peak, less overnight).
dotnet-gcdump on the live process (t+5.5 h after a restart, working set 1581 MiB and climbing) shows 478 MB live heap / 8.67 M objects, and the top retained large types are all Microsoft.Diagnostics.Tracing (TraceEvent) bookkeeping:
Object Bytes Count Type
35,087,256 1 CallStackInfo[] [Microsoft.Diagnostics.Tracing.TraceEvent.dll]
35,087,256 1 System.Collections.Generic.List<Microsoft.Diagnostics.Tracing.Etlx.CallStackIndex>[]
2,548,664 1 MethodInfo[] [Microsoft.Diagnostics.Tracing.TraceEvent.dll]
2,548,536 1 CodeAddressInfo[] [Microsoft.Diagnostics.Tracing.TraceEvent.dll]
2,172,576 1 Entry<System.Int64,TraceCodeAddresses+ILMapIndex>[]
1,810,368 1 Entry<System.UInt64,CodeAddressIndex>[]
1,048,600 1 MethodLoadUnloadVerboseTraceData[] [TraceEvent]
876,536 1 TraceMethod[] [TraceEvent]
849,528 1 ILToNativeMap[] [TraceEvent]
424,776 1 CodeAddressIndex[] [TraceEvent]
161,984 1 Entry<System.Int32,EventPipe.StackCache+StackMarker>[]
(These are the >100 KB single arrays; the remaining growth is millions of small entries in the same structures.)
A/B on the identical build: set ProfilesSampleRate: 0 and restart → t+10 h working set 477 MiB and falling; gcdump shows 31 MB live / 470 k objects with zero TraceEvent types. Leak fully cured by disabling profiling alone (tracing, logs, error reporting all left enabled).
Analysis
The continuous in-process EventPipe/TraceEvent session backing transaction profiling accumulates call-stack, code-address, and IL-map index tables (CallStackInfo, TraceCodeAddresses maps, ILToNativeMap, StackCache) for the life of the session, proportional to the diversity/volume of sampled stacks. They are never trimmed.
Related history — all distinct mechanisms, and all already present in 6.6.0:
- #3407 was closed by #3491 ("decrease runtime circular buffer for diagnostics client") — native EventPipe buffer sizing, not managed index growth.
- Sentry profiler seems to be leaking memory #5113 was closed by #5133 (shipped 6.4.0) — ConcurrentBag/ConcurrentQueue stranded per-thread nodes, not TraceEvent index tables.
- SamplingTransactionProfilerFactory.Dispose disposes the Task, not the SampleProfilerSession (resource leak) #5418 (open) — SampleProfilerSession not disposed on factory Dispose; a shutdown-path resource leak, distinct from this steady-state runtime growth (possibly compounding).
As far as I can tell this steady-state TraceEvent index accumulation has no existing open or closed issue.
Happy to attach both full gcdump type histograms (with-profiling vs without) if useful.
Metadata
Metadata
Assignees
Projects
- StatusShow more project fieldsNo status
Activity
linear-code commentedon Aug 5, 2026
NET-783
jamescrosswell commentedon Aug 6, 2026
Thanks @therickfactr ❤️
Claude reproduced this for me in a Linux container with a minimal harness (ASP.NET-free: a bare EventPipe + TraceLog session plus synthetic stack-shape churn), and confirms both the symptom and your analysis.
Root cause
Stems from
TraceCallStacks.InternCallStackIndexin TraceEvent'sTraceLog.cs. The call-stack table is an append-only trie: every distinct stack shape interns a newCallStackInfo, and each one also appends to the parallelcalleeslist.TraceLog's real-time mode does have trimming, but only for three
eventsToStacks,eventsToCodeAddressesandcswitchBlockingEventsToStacks— and on the EventPipe path those are already cleared after every event. The interning tables(
callStacks,callees,codeAddresses) have no eviction path at all.This is tracked upstream:
But the upstream was closed as not planned... so we need to either get a PR accepted upstream to fix or fork from upstream (yuck).
Two surprises
Growth tracks distinct stack shapes, not sample volume. With a single fixed stack shape, 11x more samples grew the table only 24%. This is why an idle instance doesn't reproduce and your traffic-proportional rate does — real traffic keeps minting new stack
shapes. It also means the leak rate depends on application shape (async state machines, generics, DI-heavy call paths) more than on request count.
It is independent of
ProfilesSampleRateabove 0. The accumulation happens inside TraceLog's event processing whether or not a profiler is attached to consume samples — the session is started once bySamplingTransactionProfilerFactoryand runs continuously.ProfilesSampleRate: 0cures it only because no factory (and therefore no session) is constructed at all. That matches your A/B exactly, and it means lowering the sample rate is not a mitigation — only disabling profiling outright is.Recycling the session does NOT work
The obvious remedy is to tear down and restart the EventPipe session once the call-stack table crosses a budget. It works on the managed side and fails on the whole-process side. Three 600s runs, identical workload:
The interning tables stay bounded and managed heap goes flat — but each recycle costs ~3.1-3.3 MiB of RSS that is never returned so RSS grew ~3x faster than the leak being fixed (the cure is worse than the disease). Disposing the old session before starting the replacement changes nothing (3.3 vs 3.1 MiB/recycle), so it isn't the two 16 MB EventPipe buffers briefly coexisting — it's a per-session cost. Scaled to the reporter's ~222 stacks/sec, even a 1M-stack budget would leave ~120 MiB permanently resident and still leak ~50 MiB/day.
Recommended direction / fix
A new EventPipe session is not needed - only a reset of the managed interning tables. The session is precisely what costs the
3 MiB.
So instead, add a reset to
TraceCallStacksin the getsentry/perfview fork (clearingcallStacks,callees,threads) and call it fromSamplingTransactionProfilerFactorybetween profiles.Nothing outside those tables retains a
CallStackIndexacross events.PastEventInfois a fixed 2048-entry ring, theeventsTo*Stacksarrays are cleared per-event on the EventPipe path, andSampleProfileBuilder's index maps are constructed fresh per profile.TraceCallStacks.SetSizeis existing precedent for shrinking the array, though it doesn't touchcallees/threads,which a correct reset would need to.
Not yet implemented or validated — this is just what came out of the initial analysis.
Repro environment
Linux container (
mcr.microsoft.com/dotnet/runtime:9.0, .NET 9.0.8, kernel 6.10) rather than .NET 8 / Rocky 9, so it's the same mechanism rather than a byte-for-byte match of your environment. RSS measured asVmRSSfrom/proc/self/status.jamescrosswell commentedon Aug 6, 2026
Planned sequencing for the fix
getsentry/perfviewmirror -getsentry/perfviewmainis 144 commits behindmicrosoft/perfviewmaingetsentry/perfview- are you able to do this?microsoft/perfviewrepo) - If Microsoft are willing to accept the PR, we can avoid having to fork from upstream (which I'd really really like to do).Notes on the bump (step 1)
FlushRealTimeEvents). Both are in code the profiler exercises continuously.therickfactr commentedon Aug 9, 2026
Following up on the upstream path: I've opened microsoft/perfview#2451 with the production evidence and the mechanism from @jamescrosswell's analysis above, framed as a question about whether an unbounded interning table is considered in-scope for the real-time/EventPipe path.
Rather than reopening microsoft/perfview#1199 — which was closed in 2022 because the original reporter stopped seeing it, not because it was resolved or ruled out — it's a fresh issue linking back to it, so it lands in the triage queue instead of a dormant thread.
It explicitly floats the bounded-reset direction (clearing
callStacks/callees/threadsbetween profiles without tearing down the session, withTraceCallStacks.SetSizeas precedent), so if Microsoft engage, step 4 of your plan may not need a fork. Happy to supply dumps or a repro harness if that helps.jamescrosswell commentedon Aug 12, 2026
Thanks @therickfactr - I'll reference the new issue you opened in any PR/fix for the issue 👍🏻
jamescrosswell commentedon Aug 12, 2026
Recording a timing hazard found while designing the SDK-side call site, because it is easy to
get wrong and produces silently corrupt profiles rather than an exception.
The reset itself now exists — getsentry/perfview#4 adds
TraceLog.ResetCallStacks()(opt in,real time only) with a regression test. Measured over 600s against the same workload: interned
call stacks bounded instead of reaching 1.23M and climbing, managed heap flat at ~7 MiB instead
of 119 MiB, RSS +15.8 MiB instead of +135.5 MiB, at ~0.012 MiB per reset. That lines up with what
@therickfactr floated in microsoft/perfview#2451, so if Microsoft engage there we have a concrete
implementation to offer.
Why
_inProgressis not a sufficient guardResetCallStacks()invalidates everyCallStackIndex, so it must only run when nothing is stillreading them. The obvious guard is
SamplingTransactionProfilerFactory._inProgress. It is notenough.
How the indexes are used.
SampleProfileBuilder.AddSampleresolves a sample synchronouslyinside the
ThreadSamplecallback — walksCallStacks.Caller(...)to the root, resolves throughCodeAddresses.MethodIndex(...)to a method name, and buildsSentryStackFrames. Nothing holds aCallStackIndexafter it returns. But it caches by index:_stackIndexesis aDictionary<int,int>keyed by(int)callStackIndex. After a reset TraceLog reissues indexes from0 for entirely different stacks, so a stale cache entry hands back a previously built stack for an
unrelated one. Wrong frames in the profile, no error.
The window.
SamplingTransactionProfiler.Stop()callsOnFinish?.Invoke(), which sets_inProgress = false— butOnThreadSamplestays subscribed. It keeps feedingAddSampleuntila sample arrives with
timestampMs > _endTimeMs, and only then unsubscribes and signals_completionSource. That drain is deliberate: TraceLog dispatches with roughly a 2 second delay,which is also why
CollectAsyncwaits up to a second for it.So there is a window, up to a couple of seconds wide, where
_inProgress == falsewhile theprevious profile is still actively reading the trie and filling its index-keyed caches. Resetting
in that window corrupts the profile that is mid-collection.
The safe signal
_inProgress == falseand the last profiler has finished draining (completion signalled /OnThreadSampleunsubscribed). The profiler has no way to tell the factory that today, so thisneeds a small amount of plumbing.
Where to call it
An always-on
ThreadSamplehandler on the factory. It runs on the event-processing thread, whichsatisfies
ResetCallStacks's threading contract with no locking, and it is the same thread anactive profiler's handler runs on, so the two cannot interleave.
It has to be always-on rather than fired at profile boundaries, because the interning tables grow
whether or not a profiler is attached — the EventPipe session samples continuously, so stacks
accumulate during idle periods between sampled transactions too. Resetting only when a profile ends
would leave the growth running whenever traffic is sparse. A
CallStacks.Count > budgetcheck persample costs a comparison and catches it.
What survives a reset
_frameIndexesByCodeAddressIndexand_frameIndexesByMethodIndexstay valid —ResetCallStacks()does not touch
codeAddressesorMethods, so those indexes are not recycled. And becauseSampleProfileBuilderis constructed fresh per profile, no cache spans a reset at all, providedresets only happen between profiles.
jamescrosswell commentedon Aug 13, 2026
I've submitted a PR to the
microsoft/perfviewrepo:That's half of the puzzle (assuming it gets accepted). The other half is to use this new method in Sentry.Profiling to clear the interning tables periodically.