Skip to content

Commit

Permalink
Fix memory leak when tracing is enabled (#3432)
Browse files Browse the repository at this point in the history
  • Loading branch information
jamescrosswell authored Jun 18, 2024
1 parent e0f548b commit 7c2a91f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
- Fixed Monitor duration calculation ([#3420]https://github.com/getsentry/sentry-dotnet/pull/3420)
- Fixed null IServiceProvider in anonymous routes with OpenTelemetry ([#3401](https://github.com/getsentry/sentry-dotnet/pull/3401))
- Fixed Trim warnings in Sentry.DiagnosticSource and WinUIUnhandledException integrations ([#3410](https://github.com/getsentry/sentry-dotnet/pull/3410))
- Fix memory leak when tracing is enabled ([#3432](https://github.com/getsentry/sentry-dotnet/pull/3432))

### Dependencies

Expand Down
25 changes: 25 additions & 0 deletions src/Sentry/TransactionTracer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,11 @@ public IReadOnlyList<string> Fingerprint
/// <inheritdoc />
public IReadOnlyDictionary<string, string> Tags => _tags;

#if NETSTANDARD2_1_OR_GREATER
private readonly ConcurrentBag<ISpan> _spans = new();
#else
private ConcurrentBag<ISpan> _spans = new();
#endif

/// <inheritdoc />
public IReadOnlyCollection<ISpan> Spans => _spans;
Expand Down Expand Up @@ -337,6 +341,14 @@ public void Push(ISpan span)
return null;
}
}

public void Clear()
{
lock (_lock)
{
TrackedSpans.Clear();
}
}
}
private readonly LastActiveSpanTracker _activeSpanTracker = new LastActiveSpanTracker();

Expand Down Expand Up @@ -373,6 +385,9 @@ public void Finish()

// Client decides whether to discard this transaction based on sampling
_hub.CaptureTransaction(new SentryTransaction(this));

// Release tracked spans
ReleaseSpans();
}

/// <inheritdoc />
Expand All @@ -395,4 +410,14 @@ public void Finish(Exception exception) =>

/// <inheritdoc />
public SentryTraceHeader GetTraceHeader() => new(TraceId, SpanId, IsSampled);

private void ReleaseSpans()
{
#if NETSTANDARD2_1_OR_GREATER
_spans.Clear();
#else
_spans = new ConcurrentBag<ISpan>();
#endif
_activeSpanTracker.Clear();
}
}
3 changes: 2 additions & 1 deletion test/Sentry.Tests/Protocol/SentryTransactionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ public void Redact_Redacts_Urls()
child2.SetExtra("f222", "p111");
child2.Finish(SpanStatus.OutOfRange);

txTracer.Finish(SpanStatus.Aborted);
// Don't finish the tracer - that would cause the spans to be released
// txTracer.Finish(SpanStatus.Aborted);

// Act
var transaction = new SentryTransaction(txTracer);
Expand Down

0 comments on commit 7c2a91f

Please sign in to comment.