Repository navigation
feat(anr): [Non-Fatal ANR 5] Report non-fatal ANRs #6726
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
Changes from all commits
db300e8
9ef17ef
c34f212
f7e13d2
8f9c634
02485f7
c7764ba
392afad
549775a
e28fcf1
eb1e698
f44f040
82165ba
959280d
714a52e
c3a1a50
a5f4e61
eb16e57
ed8917b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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(); | ||
| } | ||
| } | ||
|
|
||
| @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); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Marker can outlive a later hangMedium Severity The skip marker is written only after async envelope flush, and a later hang deletes it only if Additional Locations (1)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; | ||
| } | ||
| } | ||
| } | ||


There was a problem hiding this comment.
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
markFlushedalso runs when the rate limiter drops the envelope, and that path still writeslast_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)
sentry-android-core/src/main/java/io/sentry/android/core/NonFatalAnrIntegration.java#L139-L149Reviewed by Cursor Bugbot for commit ed8917b. Configure here.