Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
db300e8
feat(anr): Report non-fatal ANRs
markushi Nov 20, 2026
9ef17ef
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 23, 2026
c34f212
ref(anr): Adapt NonFatalAnrIntegration to HangRecordingRequest
markushi Nov 23, 2026
f7e13d2
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 23, 2026
8f9c634
ref(anr): Read stack traces from the HangRecord
markushi Nov 23, 2026
02485f7
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 23, 2026
c7764ba
feat(anr): Draw the non-fatal ANR sample rate for each hang
markushi Nov 23, 2026
392afad
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 24, 2026
549775a
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 24, 2026
e28fcf1
ref(anr): Adapt to the renamed hang types
markushi Nov 24, 2026
eb1e698
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 24, 2026
f44f040
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 24, 2026
82165ba
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 24, 2026
959280d
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 24, 2026
714a52e
fix(anr): Delete the non-fatal ANR marker at the next hang
markushi Nov 24, 2026
c3a1a50
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 24, 2026
a5f4e61
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 24, 2026
eb16e57
ref(anr): Do not report a thread state for non-fatal ANRs
markushi Nov 24, 2026
ed8917b
ref(anr): Remove the main thread blocked flag from NonFatalAnrHint
markushi Nov 24, 2026
595c97a
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 25, 2026
23aca71
ref(anr): Report only recovered hangs and remove the non-fatal ANR ma…
markushi Nov 25, 2026
4cb594b
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 25, 2026
f49eae1
feat(anr): Report the thread state of the non-fatal ANR culprit
markushi Nov 25, 2026
c6a34a1
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 27, 2026
4b50e60
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 27, 2026
cabe2f1
fix(anr): Use the default fingerprint for a non-fatal ANR without a s…
markushi Nov 27, 2026
a66ae84
chore(anr): Merge non-fatal-anr-4 into non-fatal-anr-5
markushi Nov 27, 2026
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
13 changes: 12 additions & 1 deletion sentry-android-core/api/sentry-android-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,12 @@ public final class io/sentry/android/core/NetworkBreadcrumbsIntegration : io/sen
public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V
}

public final class io/sentry/android/core/NonFatalAnrIntegration : io/sentry/Integration, java/io/Closeable {
public fun <init> ()V
public fun close ()V
public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V
}

public final class io/sentry/android/core/PerfettoContinuousProfiler : io/sentry/IContinuousProfiler, io/sentry/transport/RateLimiter$IRateLimitObserver {
public fun <init> (Lio/sentry/ILogger;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;Lio/sentry/util/LazyEvaluator$Evaluator;Ljava/util/function/Supplier;)V
public fun close (Z)V
Expand Down Expand Up @@ -449,6 +455,8 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr
public fun getNativeSdkName ()Ljava/lang/String;
public fun getNdkAppHangTimeoutIntervalMillis ()J
public fun getNdkHandlerStrategy ()I
public fun getNonFatalAnrSampleRate ()Ljava/lang/Double;
public fun getNonFatalAnrThresholdMs ()J
public fun getScreenshot ()Lio/sentry/android/core/SentryScreenshotOptions;
public fun getStartupCrashDurationThresholdMillis ()J
public fun getTombstoneMergeTimeThresholdMillis ()J
Expand Down Expand Up @@ -520,6 +528,8 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr
public fun setNativeHandlerStrategy (Lio/sentry/android/core/NdkHandlerStrategy;)V
public fun setNativeSdkName (Ljava/lang/String;)V
public fun setNdkAppHangTimeoutIntervalMillis (J)V
public fun setNonFatalAnrSampleRate (Ljava/lang/Double;)V
public fun setNonFatalAnrThresholdMs (J)V
public fun setReportHistoricalAnrs (Z)V
public fun setReportHistoricalMemoryLimiterExits (Z)V
public fun setReportHistoricalTombstones (Z)V
Expand Down Expand Up @@ -723,9 +733,10 @@ public final class io/sentry/android/core/ViewHierarchyEventProcessor : io/sentr
}

public final class io/sentry/android/core/anr/AggregatedStackTrace {
public fun <init> ([Ljava/lang/StackTraceElement;IIJF)V
public fun <init> ([Ljava/lang/StackTraceElement;IIJFLjava/lang/Thread$State;)V
public fun addOccurrence (J)V
public fun getStack ()[Ljava/lang/StackTraceElement;
public fun getState ()Ljava/lang/Thread$State;
}

public final class io/sentry/android/core/anr/AnrCulpritEventHelper {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,10 @@ static void installDefaultIntegrations(
options.addIntegration(AnrIntegrationFactory.create(context, buildInfoProvider));

options.addIntegration(new AnrProfilingIntegration());
// Below API 30, AnrIntegration reports the same hangs.
if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.R) {
options.addIntegration(new NonFatalAnrIntegration());
}

// registerActivityLifecycleCallbacks is only available if Context is an AppContext
if (context instanceof Application) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ final class ManifestMetadataReader {
static final String SCREENSHOT_MASK_ALL_IMAGES = "io.sentry.screenshot.mask-all-images";

static final String ANR_PROFILING_SAMPLE_RATE = "io.sentry.anr.profiling.sample-rate";
static final String NON_FATAL_ANR_SAMPLE_RATE = "io.sentry.anr.non-fatal.sample-rate";
static final String NON_FATAL_ANR_THRESHOLD_MS = "io.sentry.anr.non-fatal.threshold-ms";

static final String ENABLE_ANR_FINGERPRINTING = "io.sentry.anr.enable-fingerprinting";

Expand Down Expand Up @@ -825,6 +827,20 @@ static void applyMetadata(
}
}

if (options.getNonFatalAnrSampleRate() == null) {
final double nonFatalAnrSampleRate =
readDouble(metadata, logger, NON_FATAL_ANR_SAMPLE_RATE);
if (nonFatalAnrSampleRate != -1) {
options.setNonFatalAnrSampleRate(nonFatalAnrSampleRate);
}
}

final long nonFatalAnrThresholdMs =
readLong(metadata, logger, NON_FATAL_ANR_THRESHOLD_MS, -1);
if (nonFatalAnrThresholdMs != -1) {
options.setNonFatalAnrThresholdMs(nonFatalAnrThresholdMs);
}

options.setEnableAnrFingerprinting(
readBool(
metadata, logger, ENABLE_ANR_FINGERPRINTING, options.isEnableAnrFingerprinting()));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
package io.sentry.android.core;

import static io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion;

import android.os.Looper;
import io.sentry.Breadcrumb;
import io.sentry.DateUtils;
import io.sentry.ILogger;
import io.sentry.IScopes;
import io.sentry.Integration;
import io.sentry.SentryEvent;
import io.sentry.SentryExceptionFactory;
import io.sentry.SentryLevel;
import io.sentry.SentryOptions;
import io.sentry.SentryStackTraceFactory;
import io.sentry.android.core.anr.AggregatedStackTrace;
import io.sentry.android.core.anr.AnrCulpritEventHelper;
import io.sentry.android.core.anr.AnrCulpritIdentifier;
import io.sentry.android.core.anr.AnrStackTrace;
import io.sentry.android.core.hang.HangManager;
import io.sentry.android.core.hang.HangRecord;
import io.sentry.android.core.hang.HangRecordingListener;
import io.sentry.android.core.hang.HangRecordingRequest;
import io.sentry.android.core.internal.util.AndroidThreadChecker;
import io.sentry.protocol.Mechanism;
import io.sentry.protocol.SentryException;
import io.sentry.protocol.SentryThread;
import io.sentry.util.Objects;
import io.sentry.util.SentryRandom;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
* Reports main-thread hangs that recover as non-fatal ANR events: the main thread runs again, or
* the app goes to the background. A hang that does not recover, for example because the process is
* killed, is left to the fatal ANR path.
*
* <p>Subscribes to the {@link HangManager} of the options for the SDK lifetime, and draws the
* sample rate at each hang. Installed from Android 11 (API 30); below that, {@link AnrIntegration}
* reports the same hangs.
*
* <p>Enable via {@link SentryAndroidOptions#setNonFatalAnrSampleRate(Double)} or the {@code
* io.sentry.anr.non-fatal.sample-rate} manifest metadata.
*/
@ApiStatus.Internal
public final class NonFatalAnrIntegration implements Integration, Closeable {

private final @NotNull AtomicReference<HangManager> subscribedManager = new AtomicReference<>();
private final @NotNull AtomicReference<HangRecordingListener> subscription =
new AtomicReference<>();

@Override
public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions options) {
final @NotNull SentryAndroidOptions androidOptions =
Objects.requireNonNull(
(options instanceof SentryAndroidOptions) ? (SentryAndroidOptions) options : null,
"SentryAndroidOptions is required");
if (!androidOptions.isAnrEnabled() || !androidOptions.isNonFatalAnrEnabled()) {
return;
}
final @NotNull ILogger logger = options.getLogger();
final @Nullable HangManager manager = androidOptions.getHangManager();
if (manager == null) {
logger.log(SentryLevel.WARNING, "Non-fatal ANR is enabled but there is no hang manager");
return;
}
if (!subscribedManager.compareAndSet(null, manager)) {
return;
}
final @NotNull HangRecordingListener listener = new Reporter(scopes, androidOptions);
subscription.set(listener);
manager.subscribe(listener);
addIntegrationToSdkVersion("NonFatalAnr");
}

@Override
public void close() throws IOException {
final @Nullable HangManager manager = subscribedManager.getAndSet(null);
final @Nullable HangRecordingListener listener = subscription.getAndSet(null);
if (manager != null && listener != null) {
manager.unsubscribe(listener);
}
}

private static final class Reporter implements HangRecordingListener {

private final @NotNull IScopes scopes;
private final @NotNull SentryAndroidOptions options;
private final @NotNull AnrCulpritEventHelper culpritEventHelper;

Reporter(final @NotNull IScopes scopes, final @NotNull SentryAndroidOptions options) {
this.scopes = scopes;
this.options = options;
this.culpritEventHelper =
new AnrCulpritEventHelper(
new SentryExceptionFactory(new SentryStackTraceFactory(options)));
}

@Override
public @Nullable HangRecordingRequest onHangStarted() {
final @Nullable Double sampleRate = options.getNonFatalAnrSampleRate();
if (sampleRate != null && SentryRandom.current().nextDouble() < sampleRate) {
return new HangRecordingRequest(true, false);
}
return null;
}

@Override
public void onHangRecorded(final @NotNull HangRecord record) {
if (record.getDurationMs() < options.getNonFatalAnrThresholdMs()) {
return;
}
final long endTimestampMs = record.getStartTimestampMs() + record.getDurationMs();
scopes.captureEvent(buildEvent(record, endTimestampMs));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Missing non-fatal ANR marker

Medium Severity

The integration reports a recovered hang and never writes the last_non_fatal_anr marker. A hang that is long enough for Android to still kill the process (for example after backgrounding) can then also be sent as a fatal ANR on the next launch, duplicating the same incident.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit a66ae84. Configure here.


final @NotNull Breadcrumb breadcrumb = new Breadcrumb();
breadcrumb.setCategory("anr");
breadcrumb.setType("error");
breadcrumb.setLevel(SentryLevel.WARNING);
breadcrumb.setMessage("Non-fatal ANR");
breadcrumb.setData("duration_ms", record.getDurationMs());
scopes.addBreadcrumb(breadcrumb);
}
Comment thread
markushi marked this conversation as resolved.
Resolved

private @NotNull SentryEvent buildEvent(
final @NotNull HangRecord record, final long endTimestampMs) {
final @NotNull List<AnrStackTrace> samples = record.getStackTraces();
final @Nullable AggregatedStackTrace culprit =
samples.isEmpty() ? null : AnrCulpritIdentifier.identify(samples);

final @NotNull Mechanism mechanism = new Mechanism();
mechanism.setType("NonFatalANR");
mechanism.setHandled(true);

@Nullable
List<SentryException> exceptions =
culprit == null ? null : culpritEventHelper.toSentryExceptions(culprit, mechanism);
if (exceptions == null) {
final @NotNull SentryException exception = new SentryException();
exception.setType(ApplicationNotResponding.class.getName());
exception.setValue("Non-fatal ANR");
exception.setMechanism(mechanism);
exceptions = Arrays.asList(exception);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Fallback ANR type uses FQCN

Medium Severity

When a hang has no usable stack samples, the fallback exception sets type to ApplicationNotResponding.class.getName() (the FQCN) and leaves module unset. Culprit events built through AnrCulpritEventHelper instead use simple name plus package. Those two shapes group as different issues, so recovered hangs without samples split from the rest.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit a66ae84. Configure here.

}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Wrong fallback exception type

Low Severity

When there is no culprit stack, the fallback exception sets type to ApplicationNotResponding.class.getName(), the FQCN. AnrCulpritEventHelper instead sets type to ApplicationNotResponding and module to io.sentry.android.core. Hangs without a usable stack therefore show a different exception type and can group apart from sampled non-fatal ANRs even with the same fingerprints.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit cabe2f1. Configure here.

final long mainThreadId =
AndroidThreadChecker.getThreadId(Looper.getMainLooper().getThread());
for (final @NotNull SentryException exception : exceptions) {
exception.setThreadId(mainThreadId);
}

final @NotNull SentryEvent event = new SentryEvent(DateUtils.getDateTime(endTimestampMs));
event.setLevel(SentryLevel.ERROR);
event.setExceptions(exceptions);
event.setThreads(Arrays.asList(mainThread(mainThreadId, culprit, exceptions)));

final @NotNull Map<String, Object> context = new HashMap<>();
context.put("duration_ms", record.getDurationMs());
context.put("sample_count", samples.size());
event.getContexts().put("non_fatal_anr", context);

// An exception without a stack has no frames either, but it is not a system-only stack.
if (culprit != null
&& options.isEnableAnrFingerprinting()
&& AnrCulpritEventHelper.hasOnlySystemFrames(exceptions)) {
event.setFingerprints(Arrays.asList("system-frames-only-anr", "non-fatal-anr"));
} else {
event.setFingerprints(Arrays.asList("{{ default }}", "non-fatal-anr"));
}
Comment thread
markushi marked this conversation as resolved.
Resolved
return event;
}

private static @NotNull SentryThread mainThread(
final long mainThreadId,
final @Nullable AggregatedStackTrace culprit,
final @NotNull List<SentryException> exceptions) {
final @NotNull SentryThread thread = new SentryThread();
thread.setId(mainThreadId);
thread.setName("main");
thread.setCurrent(true);
thread.setMain(true);
if (culprit != null) {
thread.setStacktrace(exceptions.get(0).getStacktrace());
final @Nullable Thread.State state = culprit.getState();
if (state != null) {
thread.setState(state.name());
}
}
return thread;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,10 @@ public interface BeforeCaptureCallback {
*/
private @Nullable Double anrProfilingSampleRate;

private @Nullable Double nonFatalAnrSampleRate;

private long nonFatalAnrThresholdMs = 700;

private boolean enableAnrFingerprinting = true;

private volatile @Nullable HangManager hangManager;
Expand Down Expand Up @@ -401,7 +405,11 @@ public boolean isAnrReportInDebug() {
}

/**
* Sets ANR (Application Not Responding) to enabled or disabled on Debug mode Default is disabled
* Sets whether {@link AnrIntegration} (ANR v1, below Android 11) reports ANRs while a debugger is
* connected. Default is disabled.
*
* <p>Only ANR v1 uses this flag. Non-fatal ANR reporting and ANR profiling always ignore hangs
* while a debugger is connected.
*
* @param anrReportInDebug true for enabled and false for disabled
*/
Expand Down Expand Up @@ -1009,6 +1017,66 @@ public boolean isAnrProfilingEnabled() {
return anrProfilingSampleRate != null && anrProfilingSampleRate > 0;
}

/**
* Returns the sample rate for reporting non-fatal ANRs: main-thread hangs that recover. A hang
* that does not recover is reported only as a fatal ANR.
*
* @return the non-fatal ANR sample rate, or {@code null} when reporting is disabled (default)
*/
public @Nullable Double getNonFatalAnrSampleRate() {
return nonFatalAnrSampleRate;
}

/**
* Sets the sample rate for reporting non-fatal ANRs. The sampling decision is made for each hang.
*
* <p>Use {@code null} to disable (default). Values must be between {@code 0.0} and {@code 1.0}.
*
* @param nonFatalAnrSampleRate the sample rate, or {@code null} to disable
*/
public void setNonFatalAnrSampleRate(final @Nullable Double nonFatalAnrSampleRate) {
if (!SampleRateUtils.isValidSampleRate(nonFatalAnrSampleRate)) {
throw new IllegalArgumentException(
"The value "
+ nonFatalAnrSampleRate
+ " is not valid. Use null to disable or values >= 0.0 and <= 1.0.");
}
this.nonFatalAnrSampleRate = nonFatalAnrSampleRate;
}

/**
* Returns the minimum duration in milliseconds a main-thread hang needs to be reported as a
* non-fatal ANR. Defaults to 700.
*/
public long getNonFatalAnrThresholdMs() {
return nonFatalAnrThresholdMs;
}

/**
* Sets the minimum duration in milliseconds a main-thread hang needs to be reported as a
* non-fatal ANR. Defaults to 700. Only used if {@link #getNonFatalAnrSampleRate()} is set.
*
* <p>Detection starts after 300 ms, so a lower value behaves like 300 ms. A negative value is
* ignored.
*
* @param nonFatalAnrThresholdMs the threshold in milliseconds
*/
public void setNonFatalAnrThresholdMs(final long nonFatalAnrThresholdMs) {
if (nonFatalAnrThresholdMs < 0) {
getLogger()
.log(
SentryLevel.WARNING,
"The non-fatal ANR threshold %d ms is negative and is ignored.",
nonFatalAnrThresholdMs);
return;
}
this.nonFatalAnrThresholdMs = nonFatalAnrThresholdMs;
}

boolean isNonFatalAnrEnabled() {
return nonFatalAnrSampleRate != null && nonFatalAnrSampleRate > 0;
}

/**
* The hang manager that the ANR integrations share. Null if {@link #getCacheDirPath()} was null
* at init.
Expand Down
Loading
Loading