Skip to content

fix: remove blocking detection for background worker #4288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions src/Sentry.Profiling/SamplingTransactionProfilerFactory.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Sentry.Ben.BlockingDetector;
using Sentry.Extensibility;
using Sentry.Internal;

Expand Down Expand Up @@ -27,16 +28,19 @@ public SamplingTransactionProfilerFactory(SentryOptions options, TimeSpan startu
{
_options = options;

_sessionTask = Task.Run(async () =>
using (new SuppressBlockingDetection())
{
// This can block up to 30 seconds. The timeout is out of our hands.
var session = SampleProfilerSession.StartNew(options.DiagnosticLogger);
_sessionTask = Task.Run(async () =>
{
// This can block up to 30 seconds. The timeout is out of our hands.
var session = SampleProfilerSession.StartNew(options.DiagnosticLogger);

// This can block indefinitely.
await session.WaitForFirstEventAsync().ConfigureAwait(false);
// This can block indefinitely.
await session.WaitForFirstEventAsync().ConfigureAwait(false);

return session;
});
return session;
});
}

Debug.Assert(TimeSpan.FromSeconds(0) == TimeSpan.Zero);
if (startupTimeout != TimeSpan.Zero && !_sessionTask.Wait(startupTimeout))
Expand Down
6 changes: 5 additions & 1 deletion src/Sentry/Internal/BackgroundWorker.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Sentry.Ben.BlockingDetector;
using Sentry.Extensibility;
using Sentry.Internal.Extensions;
using Sentry.Internal.Http;
Expand Down Expand Up @@ -37,7 +38,10 @@ public BackgroundWorker(
_queuedEnvelopeSemaphore = new SemaphoreSlim(0, _maxItems);

options.LogDebug("Starting BackgroundWorker.");
WorkerTask = Task.Run(DoWorkAsync);
using (new SuppressBlockingDetection())
{
WorkerTask = Task.Run(DoWorkAsync);
}
}

/// <inheritdoc />
Expand Down
10 changes: 8 additions & 2 deletions src/Sentry/Internal/GarbageCollectionMonitor.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Sentry.Ben.BlockingDetector;
using Sentry.Extensibility;

namespace Sentry.Internal;
Expand All @@ -10,8 +11,13 @@ internal sealed class GarbageCollectionMonitor
private const int MaxGenerationThreshold = 10;
private const int LargeObjectHeapThreshold = 10;

public static Task Start(Action onGarbageCollected, CancellationToken cancellationToken, IGCImplementation? gc = null) =>
Task.Run(() => MonitorGarbageCollection(onGarbageCollected, cancellationToken, gc), cancellationToken);
public static Task Start(Action onGarbageCollected, CancellationToken cancellationToken, IGCImplementation? gc = null)
{
using (new SuppressBlockingDetection())
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jamescrosswell this is the blocking detector itself right? we shouldn't add this then?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah don't do that...

{
return Task.Run(() => MonitorGarbageCollection(onGarbageCollected, cancellationToken, gc), cancellationToken);
}
}

private static void MonitorGarbageCollection(Action onGarbageCollected, CancellationToken cancellationToken, IGCImplementation? gc = null)
{
Expand Down
7 changes: 6 additions & 1 deletion src/Sentry/Internal/Http/CachingTransport.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Text.Json;
using Sentry.Ben.BlockingDetector;
using Sentry.Extensibility;
using Sentry.Internal.Extensions;
using Sentry.Protocol.Envelopes;
Expand Down Expand Up @@ -98,7 +100,10 @@ private void Initialize(bool startWorker)
if (startWorker)
{
_options.LogDebug("Starting CachingTransport worker.");
_worker = Task.Run(CachedTransportBackgroundTaskAsync);
using (new SuppressBlockingDetection())
{
_worker = Task.Run(CachedTransportBackgroundTaskAsync);
}
}
else
{
Expand Down
28 changes: 16 additions & 12 deletions src/Sentry/Internal/ProcessInfo.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Sentry.Ben.BlockingDetector;
using Sentry.Extensibility;

namespace Sentry.Internal;
Expand Down Expand Up @@ -95,20 +96,23 @@ internal ProcessInfo(
// This method will give a better precision to the StartupTime at a cost
// of calling Process.GetCurrentProcess, on a thread pool thread.
var preciseStartupTimeFunc = findPreciseStartupTime ?? GetStartupTime;
PreciseAppStartupTask = Task.Run(() =>
using (new SuppressBlockingDetection())
{
try
PreciseAppStartupTask = Task.Run(() =>
{
StartupTime = preciseStartupTimeFunc();
}
catch (Exception e)
{
options.LogError(e, "Failure getting precise App startup time.");
//Ignore any exception and stay with the less-precise DateTime.UtcNow value.
}
}).ContinueWith(_ =>
// Let the actual task get collected
PreciseAppStartupTask = Task.CompletedTask);
try
{
StartupTime = preciseStartupTimeFunc();
}
catch (Exception e)
{
options.LogError(e, "Failure getting precise App startup time.");
//Ignore any exception and stay with the less-precise DateTime.UtcNow value.
}
}).ContinueWith(_ =>
// Let the actual task get collected
PreciseAppStartupTask = Task.CompletedTask);
}
#endif
}
}
Expand Down
35 changes: 35 additions & 0 deletions test/Sentry.Tests/Internals/BackgroundWorkerTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.IO.Abstractions.TestingHelpers;
using Sentry.Ben.BlockingDetector;
using Sentry.Internal.Http;
using BackgroundWorker = Sentry.Internal.BackgroundWorker;

Expand Down Expand Up @@ -521,4 +522,38 @@ public async Task FlushAsync_Calls_CachingTransport_FlushAsync()
_fixture.Logger.Received(1)
.Log(SentryLevel.Debug, "CachingTransport received request to flush the cache.");
}

[Fact]
public void Ctor_SuppressesBlockingDetection_WhenCreatingTask()
{
// Arrange
var listenerState = Substitute.For<ITaskBlockingListenerState>();
var monitor = Substitute.For<IBlockingMonitor>();
var context = new DetectBlockingSynchronizationContext(monitor);

// Mock the current sync context to our test context
SynchronizationContext.SetSynchronizationContext(context);

// Mock the TaskBlockingListener to return our test state
var originalDefaultState = TaskBlockingListener.DefaultState;
TaskBlockingListener.DefaultState = listenerState;

try
{
// Act
using var sut = _fixture.GetSut();

// Assert
// Verify that suppression was called when creating the task
listenerState.Received(1).Suppress();
// Verify that restoration was called when exiting the using block
listenerState.Received(1).Restore();
}
finally
{
// Cleanup
TaskBlockingListener.DefaultState = originalDefaultState;
SynchronizationContext.SetSynchronizationContext(null);
}
}
}
Loading