Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 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
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
25 changes: 25 additions & 0 deletions sentry-android-core/api/sentry-android-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,19 @@ 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/NonFatalAnrHint : io/sentry/hints/DiskFlushNotification {
public fun <init> (Ljava/lang/Runnable;)V
public fun isFlushable (Lio/sentry/protocol/SentryId;)Z
public fun markFlushed ()V
public fun setFlushable (Lio/sentry/protocol/SentryId;)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 +462,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 +535,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 @@ -796,6 +813,14 @@ public final class io/sentry/android/core/anr/AnrStackTrace : java/lang/Comparab
public fun serialize (Ljava/io/DataOutputStream;)V
}

public final class io/sentry/android/core/anr/NonFatalAnrMarker {
public static final field FILE_NAME Ljava/lang/String;
public static fun delete (Lio/sentry/SentryOptions;)V
public fun matches (IJ)Z
public static fun read (Lio/sentry/SentryOptions;)Lio/sentry/android/core/anr/NonFatalAnrMarker;
public static fun write (Lio/sentry/SentryOptions;IJJ)V
}

public final class io/sentry/android/core/anr/StackTraceConverter {
public fun <init> ()V
public static fun convert (Lio/sentry/android/core/anr/AnrProfile;)Lio/sentry/protocol/profiling/SentryProfile;
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, and nothing reads the marker.
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,43 @@
package io.sentry.android.core;

import io.sentry.hints.DiskFlushNotification;
import io.sentry.protocol.SentryId;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
* Type-check hint of non-fatal ANR events. Of the {@code io.sentry.hints} interfaces it implements
* only {@link DiskFlushNotification}, so the session is not ended as abnormal for it.
*/
@ApiStatus.Internal
public final class NonFatalAnrHint implements DiskFlushNotification {

private final @Nullable Runnable onStoredOnDisk;
private final @NotNull AtomicBoolean flushed = new AtomicBoolean(false);

/**
* @param onStoredOnDisk runs once, on the transport thread, after the envelope of the event was
* stored on disk. The transport also calls it when a rate limit drops the event. Null if the
* event needs no action on disk.
*/
public NonFatalAnrHint(final @Nullable Runnable onStoredOnDisk) {
this.onStoredOnDisk = onStoredOnDisk;
}

@Override
public void markFlushed() {
if (onStoredOnDisk != null && flushed.compareAndSet(false, true)) {
onStoredOnDisk.run();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Rate limit still writes skip marker

Medium Severity

markFlushed also runs when the rate limiter drops the envelope, and that path still writes last_non_fatal_anr. The hang was never stored, so a later fatal ANR for the same hang can be skipped and never reported.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ed8917b. Configure here.

}

@Override
public boolean isFlushable(final @Nullable SentryId eventId) {
return true;
}

@Override
public void setFlushable(final @NotNull SentryId eventId) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
package io.sentry.android.core;

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

import android.os.Looper;
import android.os.Process;
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.anr.NonFatalAnrMarker;
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.HintUtils;
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.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
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 as non-fatal ANR events: hangs that recover, before or after Android
* shows the ANR dialog, and hangs that still block the main thread after 8 s, which are cut there.
*
* <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), where {@link AnrV2Integration}
* skips the fatal ANRs that this integration already reported.
*
* <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 {

/**
* Android reports an input ANR after 5 s at the earliest, so a shorter hang cannot be a fatal ANR
* and gets no marker.
*/
static final long MIN_FATAL_ANR_DURATION_MS = 5_000;

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;
private final @NotNull AtomicBoolean markerWritten = new AtomicBoolean(false);

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() {
// A fatal ANR of this hang must not match the marker of an earlier hang. A marker of the
// previous process stays, AnrV2Integration still needs it.
if (markerWritten.getAndSet(false)) {
deleteMarker();
}
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 startTimestampMs = record.getStartTimestampMs();
final long endTimestampMs = startTimestampMs + record.getDurationMs();

// Only once the transport has handled the event: a kill before that must not suppress the
// fatal ANR.
final @Nullable Runnable writeMarker;
if (record.hasEndedAtMaxRecordingTime()
|| record.getDurationMs() >= MIN_FATAL_ANR_DURATION_MS) {
final int pid = Process.myPid();
writeMarker =
() -> {
NonFatalAnrMarker.write(options, pid, startTimestampMs, endTimestampMs);
markerWritten.set(true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Marker can outlive a later hang

Medium Severity

The skip marker is written only after async envelope flush, and a later hang deletes it only if markerWritten is already true. A new hang can start in the window after capture and before flush, so the previous hang’s marker is written afterward and can still match. AnrV2Integration would then treat a later fatal ANR as already reported.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ed8917b. Configure here.

};
} else {
writeMarker = null;
}

final @NotNull SentryEvent event = buildEvent(record, endTimestampMs);
scopes.captureEvent(
event, HintUtils.createWithTypeCheckHint(new NonFatalAnrHint(writeMarker)));

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);
}

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);
}
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);

if (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"));
}
return event;
}

@SuppressWarnings("FutureReturnValueIgnored")
private void deleteMarker() {
try {
options.getExecutorService().submit(() -> NonFatalAnrMarker.delete(options));
} catch (RejectedExecutionException e) {
options
.getLogger()
.log(SentryLevel.WARNING, "Failed to delete the non-fatal ANR marker", e);
}
}

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());
}
return thread;
}
}
}
Loading
Loading