Skip to content

Memory leak with Sentry.Profiling 6.6.0 on Linux: TraceEvent call-stack/method index tables accumulate unboundedly under traffic (~0.6 GB/day to OOM) #5469

Closed

Description

@therickfactr

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

  1. ASP.NET Core service on Linux x64 (Rocky 9, kernel 5.14), 8 GB VM, systemd-hosted, builder.WebHost.UseSentry(...) with options.AddProfilingIntegration().
  2. TracesSampleRate: 0.1, ProfilesSampleRate: 0.1.
  3. Run under real production traffic (an idle instance does not reproduce — sampled transactions drive it).
  4. 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:

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.

Activity

  1. moved this to Waiting for: Product Owner in GitHub Issues with 👀 3on Aug 5, 2026
  2. linear-code commented on Aug 5, 2026

    @linear-code
  3. added
    Bug
    .NET
    on Aug 5, 2026
  4. jamescrosswell commented on Aug 6, 2026

    @jamescrosswell
    Collaborator

    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.InternCallStackIndex in TraceEvent's TraceLog.cs. The call-stack table is an append-only trie: every distinct stack shape interns a new CallStackInfo, and each one also appends to the parallel callees list.

    TraceLog's real-time mode does have trimming, but only for three eventsToStacks, eventsToCodeAddresses and cswitchBlockingEventsToStacks — 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 ProfilesSampleRate above 0. The accumulation happens inside TraceLog's event processing whether or not a profiler is attached to consume samples — the session is started once by SamplingTransactionProfilerFactory and runs continuously. ProfilesSampleRate: 0 cures 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:

    run call stacks (end) managed heap RSS start→end
    baseline 42,321, still climbing 3.8 → 6.6 MiB 70.6 → 79.3 MiB (+8.7)
    recycling (8 recycles) bounded ≤10.8k ~3.6 MiB flat 73.7 → 98.5 MiB (+24.8)
    recycling, no session overlap (6) bounded ≤10.3k ~3.8 MiB flat 71.2 → 90.8 MiB (+19.6)

    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 TraceCallStacks in the getsentry/perfview fork (clearing callStacks, callees, threads) and call it from SamplingTransactionProfilerFactory between profiles.

    Nothing outside those tables retains a CallStackIndex across events. PastEventInfo is a fixed 2048-entry ring, the
    eventsTo*Stacks arrays are cleared per-event on the EventPipe path, and SampleProfileBuilder's index maps are constructed fresh per profile. TraceCallStacks.SetSize is existing precedent for shrinking the array, though it doesn't touch callees/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 as VmRSS from /proc/self/status.

  5. moved this from Waiting for: Product Owner to No status in GitHub Issues with 👀 3on Aug 6, 2026
  6. jamescrosswell commented on Aug 6, 2026

    @jamescrosswell
    Collaborator

    Planned sequencing for the fix

    1. Fast-forward the getsentry/perfview mirror - getsentry/perfview main is 144 commits behind microsoft/perfview main
      • @vaind do you have push rights for getsentry/perfview - are you able to do this?
    2. Bump the submodule in sentry-dotnet to the new head - check nothing breaks
    3. Write a fix
    4. PR for the fix upstream (in the microsoft/perfview repo) - 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)

  7. therickfactr commented on Aug 9, 2026

    @therickfactr
    Author

    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/threads between profiles without tearing down the session, with TraceCallStacks.SetSize as 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.

  8. moved this to Waiting for: Product Owner in GitHub Issues with 👀 3on Aug 9, 2026
  9. jamescrosswell commented on Aug 12, 2026

    @jamescrosswell
    Collaborator

    Thanks @therickfactr - I'll reference the new issue you opened in any PR/fix for the issue 👍🏻

  10. moved this from Waiting for: Product Owner to No status in GitHub Issues with 👀 3on Aug 12, 2026
  11. jamescrosswell commented on Aug 12, 2026

    @jamescrosswell
    Collaborator

    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 _inProgress is not a sufficient guard

    ResetCallStacks() invalidates every CallStackIndex, so it must only run when nothing is still
    reading them. The obvious guard is SamplingTransactionProfilerFactory._inProgress. It is not
    enough.

    How the indexes are used. SampleProfileBuilder.AddSample resolves a sample synchronously
    inside the ThreadSample callback — walks CallStacks.Caller(...) to the root, resolves through
    CodeAddresses.MethodIndex(...) to a method name, and builds SentryStackFrames. Nothing holds a
    CallStackIndex after it returns. But it caches by index: _stackIndexes is a
    Dictionary<int,int> keyed by (int)callStackIndex. After a reset TraceLog reissues indexes from
    0 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() calls OnFinish?.Invoke(), which sets
    _inProgress = false — but OnThreadSample stays subscribed. It keeps feeding AddSample until
    a 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 CollectAsync waits up to a second for it.

    So there is a window, up to a couple of seconds wide, where _inProgress == false while the
    previous 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 == false and the last profiler has finished draining (completion signalled /
    OnThreadSample unsubscribed). The profiler has no way to tell the factory that today, so this
    needs a small amount of plumbing.

    Where to call it

    An always-on ThreadSample handler on the factory. It runs on the event-processing thread, which
    satisfies ResetCallStacks's threading contract with no locking, and it is the same thread an
    active 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 > budget check per
    sample costs a comparison and catches it.

    What survives a reset

    _frameIndexesByCodeAddressIndex and _frameIndexesByMethodIndex stay valid — ResetCallStacks()
    does not touch codeAddresses or Methods, so those indexes are not recycled. And because
    SampleProfileBuilder is constructed fresh per profile, no cache spans a reset at all, provided
    resets only happen between profiles.

  12. jamescrosswell commented on Aug 13, 2026

    @jamescrosswell
    Collaborator

    I've submitted a PR to the microsoft/perfview repo:

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

.NETBugProfiles

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions