Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
7005e48
feat(anr): Collect runtime stats during hangs
markushi Nov 20, 2026
3aa42a1
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 23, 2026
ab4d915
ref(anr): Make RuntimeStatsCollector a pure reader
markushi Nov 23, 2026
1c49cb4
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 23, 2026
579df22
ref(anr): Aggregate runtime stats in NonFatalAnrIntegration
markushi Nov 23, 2026
86b3f49
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 23, 2026
efaf127
ref(anr): Adapt runtime stats to the pending HangRecord
markushi Nov 23, 2026
9c0d78d
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
1cb88a4
docs(anr): Remove the caller note from RuntimeStatsSource
markushi Nov 24, 2026
4fb6b04
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
82852c0
ref(anr): Adapt to the renamed hang types
markushi Nov 24, 2026
588c07e
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
0bfaaa1
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
356d905
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
aa2464d
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
53a9d7a
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
510f0d4
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
9dbd58d
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
d9487e2
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
a9fd9bf
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
35f4fed
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
markushi Nov 24, 2026
ef4925f
chore(anr): Merge non-fatal-anr-7 into non-fatal-anr-8
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
31 changes: 31 additions & 0 deletions sentry-android-core/api/sentry-android-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ public final class io/sentry/android/core/AndroidProfiler$ProfileStartData {
public fun <init> (JJLjava/util/Date;)V
}

public final class io/sentry/android/core/AndroidRuntimeStatsSource : io/sentry/android/core/hang/RuntimeStatsSource {
public fun <init> (Lio/sentry/ILogger;)V
public fun read ()Lio/sentry/android/core/hang/RuntimeStatsSnapshot;
}

public final class io/sentry/android/core/AndroidSocketTagger : io/sentry/ISocketTagger {
public static fun getInstance ()Lio/sentry/android/core/AndroidSocketTagger;
public fun tagSockets ()V
Expand Down Expand Up @@ -886,13 +891,15 @@ public abstract interface class io/sentry/android/core/hang/HangManager$SignalFa

public final class io/sentry/android/core/hang/HangRecord {
public fun getDurationMs ()J
public fun getRuntimeStats ()Ljava/util/List;
public fun getStackTraces ()Ljava/util/List;
public fun getStartTimestampMs ()J
public fun hasEndedAtMaxRecordingTime ()Z
}

public final class io/sentry/android/core/hang/HangRecord$Builder {
public fun <init> ()V
public fun addRuntimeStats (Lio/sentry/android/core/hang/RuntimeStatsSnapshot;)Lio/sentry/android/core/hang/HangRecord$Builder;
public fun addStackTrace (Lio/sentry/android/core/anr/AnrStackTrace;)Lio/sentry/android/core/hang/HangRecord$Builder;
public fun build ()Lio/sentry/android/core/hang/HangRecord;
public fun setDurationMs (J)Lio/sentry/android/core/hang/HangRecord$Builder;
Expand Down Expand Up @@ -948,6 +955,30 @@ public abstract interface class io/sentry/android/core/hang/Metronome$TickListen
public abstract fun onMetronomeTick (J)V
}

public final class io/sentry/android/core/hang/RuntimeStatsCollector : io/sentry/android/core/hang/HangDataCollector {
public fun <init> (Lio/sentry/android/core/hang/RuntimeStatsSource;)V
public fun sample ()Lio/sentry/android/core/hang/RuntimeStatsSnapshot;
public synthetic fun sample ()Ljava/lang/Object;
}

public final class io/sentry/android/core/hang/RuntimeStatsSnapshot {
public field blockingGcCount Ljava/lang/Long;
public field blockingGcTimeMs Ljava/lang/Double;
public field freeMemory Ljava/lang/Long;
public field freeMemoryUntilOome Ljava/lang/Long;
public field gcCount Ljava/lang/Long;
public field gcTimeMs Ljava/lang/Double;
public field gcWaitingTimeMs Ljava/lang/Double;
public field maxMemory Ljava/lang/Long;
public field preOomeGcCount Ljava/lang/Long;
public field totalMemory Ljava/lang/Long;
public fun <init> ()V
}

public abstract interface class io/sentry/android/core/hang/RuntimeStatsSource {
public abstract fun read ()Lio/sentry/android/core/hang/RuntimeStatsSnapshot;
}

public final class io/sentry/android/core/hang/ThreadHangSignal : io/sentry/android/core/hang/HangSignal, io/sentry/android/core/hang/Metronome$TickListener {
public fun <init> (Lio/sentry/android/core/hang/Metronome;Lio/sentry/IDebugManager;Lio/sentry/android/core/hang/ThreadPoster;J)V
public fun close ()V
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
import io.sentry.android.core.hang.HandlerThreadPoster;
import io.sentry.android.core.hang.HangCollectorSetup;
import io.sentry.android.core.hang.HangManager;
import io.sentry.android.core.hang.RuntimeStatsCollector;
import io.sentry.android.core.hang.RuntimeStatsSource;
import io.sentry.android.core.hang.ThreadHangSignal;
import io.sentry.android.core.hang.ThreadPoster;
import io.sentry.android.core.hang.ThreadSampleCollector;
Expand Down Expand Up @@ -278,7 +280,7 @@ static void initializeIntegrationsAndProcessors(
debugManager = new AndroidDebugManager();
options.setDebugManager(debugManager);
}
setupHangManager(options, debugManager);
setupHangManager(options, debugManager, buildInfoProvider);
if (options.getSocketTagger() instanceof NoOpSocketTagger) {
options.setSocketTagger(AndroidSocketTagger.getInstance());
}
Expand Down Expand Up @@ -539,7 +541,9 @@ static void installDefaultIntegrations(
}

private static void setupHangManager(
final @NotNull SentryAndroidOptions options, final @NotNull IDebugManager debugManager) {
final @NotNull SentryAndroidOptions options,
final @NotNull IDebugManager debugManager,
final @NotNull BuildInfoProvider buildInfoProvider) {
if (options.getCacheDirPath() == null || options.getHangManager() != null) {
return;
}
Expand All @@ -548,6 +552,21 @@ private static void setupHangManager(
// options.getMonotonicTicker() counts device sleep, which would read as a hang.
final @NotNull MonotonicTicker ticker = JavaMonotonicTicker.getInstance();
final @NotNull EpochClock epochClock = options.getEpochClock();
final @NotNull List<HangCollectorSetup<?>> collectors = new ArrayList<>();
collectors.add(
new HangCollectorSetup<>(
new ThreadSampleCollector(epochClock, mainLooper.getThread()),
(stackTrace, record) -> record.addStackTrace(stackTrace),
new AnrProfileStore(options)));
final @Nullable RuntimeStatsSource runtimeStatsSource =
createRuntimeStatsSource(buildInfoProvider, options.getLogger());
if (runtimeStatsSource != null) {
collectors.add(
new HangCollectorSetup<>(
new RuntimeStatsCollector(runtimeStatsSource),
(sample, record) -> record.addRuntimeStats(sample),
null));
}
final @NotNull HangManager manager =
new HangManager(
options,
Expand All @@ -565,14 +584,17 @@ private static void setupHangManager(
debugManager,
mainThreadPoster,
HangManager.DEFAULT_SUSPICIOUS_THRESHOLD_MS)),
Collections.singletonList(
new HangCollectorSetup<>(
new ThreadSampleCollector(epochClock, mainLooper.getThread()),
(stackTrace, record) -> record.addStackTrace(stackTrace),
new AnrProfileStore(options))));
collectors);
options.setHangManager(manager);
}

static @Nullable RuntimeStatsSource createRuntimeStatsSource(
final @NotNull BuildInfoProvider buildInfoProvider, final @NotNull ILogger logger) {
return buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.M
? new AndroidRuntimeStatsSource(logger)
: null;
}

/**
* Reads and sets default option values that are Android specific like release and inApp
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package io.sentry.android.core;

import android.os.Build;
import android.os.Debug;
import androidx.annotation.RequiresApi;
import io.sentry.ILogger;
import io.sentry.SentryLevel;
import io.sentry.android.core.hang.RuntimeStatsSnapshot;
import io.sentry.android.core.hang.RuntimeStatsSource;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
* Reads the ART counters with {@link Debug#getRuntimeStat(String)} per key, which costs about 0.4
* us. {@link Debug#getRuntimeStats()} is not used because its map has no value for some keys, and
* {@link Debug#getMemoryInfo(Debug.MemoryInfo)} takes milliseconds.
*/
@ApiStatus.Internal
@RequiresApi(api = Build.VERSION_CODES.M)
public final class AndroidRuntimeStatsSource implements RuntimeStatsSource {

static final @NotNull String GC_COUNT = "art.gc.gc-count";
static final @NotNull String GC_TIME = "art.gc.gc-time";
static final @NotNull String BLOCKING_GC_COUNT = "art.gc.blocking-gc-count";
static final @NotNull String BLOCKING_GC_TIME = "art.gc.blocking-gc-time";
static final @NotNull String PRE_OOME_GC_COUNT = "art.gc.pre-oome-gc-count";
static final @NotNull String GC_WAITING_TIME = "art.gc.total-time-waiting-for-gc";

private static final double NANOS_PER_MILLI = 1_000_000.0;

interface StatReader {
@Nullable
String read(@NotNull String key);
}

private final @NotNull ILogger logger;
private final @NotNull StatReader statReader;

public AndroidRuntimeStatsSource(final @NotNull ILogger logger) {
this(logger, Debug::getRuntimeStat);
}

AndroidRuntimeStatsSource(final @NotNull ILogger logger, final @NotNull StatReader statReader) {
this.logger = logger;
this.statReader = statReader;
}

@Override
public @NotNull RuntimeStatsSnapshot read() {
final @NotNull RuntimeStatsSnapshot snapshot = new RuntimeStatsSnapshot();
snapshot.gcCount = readLong(GC_COUNT);
snapshot.gcTimeMs = readDouble(GC_TIME);
snapshot.blockingGcCount = readLong(BLOCKING_GC_COUNT);
snapshot.blockingGcTimeMs = readDouble(BLOCKING_GC_TIME);
snapshot.preOomeGcCount = readLong(PRE_OOME_GC_COUNT);

// Undocumented unit; the values match nanoseconds.
final @Nullable Double waitingNanos = readDouble(GC_WAITING_TIME);
snapshot.gcWaitingTimeMs = waitingNanos == null ? null : waitingNanos / NANOS_PER_MILLI;

final @NotNull Runtime runtime = Runtime.getRuntime();
final long total = runtime.totalMemory();
final long free = runtime.freeMemory();
final long max = runtime.maxMemory();
snapshot.freeMemory = free;
snapshot.totalMemory = total;
snapshot.maxMemory = max;
// ART has no counter for this, the heap headroom is the closest value.
snapshot.freeMemoryUntilOome = max - (total - free);
return snapshot;
}

private @Nullable Long readLong(final @NotNull String key) {
final @Nullable String value = statReader.read(key);
if (value == null) {
return null;
}
try {
return Long.parseLong(value.trim());
} catch (NumberFormatException e) {
logUnparsable(key, value, e);
return null;
}
}

private @Nullable Double readDouble(final @NotNull String key) {
final @Nullable String value = statReader.read(key);
if (value == null) {
return null;
}
try {
return Double.parseDouble(value.trim());
} catch (NumberFormatException e) {
logUnparsable(key, value, e);
return null;
}
}

private void logUnparsable(
final @NotNull String key, final @NotNull String value, final @NotNull Throwable e) {
logger.log(SentryLevel.WARNING, e, "Could not parse the runtime stat %s: %s", key, value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
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.hang.RuntimeStatsSnapshot;
import io.sentry.android.core.internal.util.AndroidThreadChecker;
import io.sentry.protocol.ArtContext;
import io.sentry.protocol.Mechanism;
import io.sentry.protocol.SentryException;
import io.sentry.protocol.SentryThread;
Expand Down Expand Up @@ -199,6 +201,17 @@ public void onHangRecorded(final @NotNull HangRecord record) {
final @NotNull Map<String, Object> context = new HashMap<>();
context.put("duration_ms", record.getDurationMs());
context.put("sample_count", samples.size());
final @NotNull List<RuntimeStatsSnapshot> runtimeStats = record.getRuntimeStats();
if (!runtimeStats.isEmpty()) {
final @NotNull RuntimeStatsSnapshot first = runtimeStats.get(0);
final @NotNull RuntimeStatsSnapshot last = runtimeStats.get(runtimeStats.size() - 1);
putDelta(context, "gc_count_delta", first.gcCount, last.gcCount);
putDelta(context, "gc_time_ms_delta", first.gcTimeMs, last.gcTimeMs);
putDelta(context, "blocking_gc_count_delta", first.blockingGcCount, last.blockingGcCount);
putDelta(
context, "blocking_gc_time_ms_delta", first.blockingGcTimeMs, last.blockingGcTimeMs);
event.getContexts().setArt(toArtContext(last));
}
event.getContexts().put("non_fatal_anr", context);

if (options.isEnableAnrFingerprinting()
Expand All @@ -210,6 +223,41 @@ public void onHangRecorded(final @NotNull HangRecord record) {
return event;
}

private static void putDelta(
final @NotNull Map<String, Object> context,
final @NotNull String key,
final @Nullable Long first,
final @Nullable Long last) {
if (first != null && last != null) {
context.put(key, last - first);
}
}

private static void putDelta(
final @NotNull Map<String, Object> context,
final @NotNull String key,
final @Nullable Double first,
final @Nullable Double last) {
if (first != null && last != null) {
context.put(key, last - first);
}
}

private static @NotNull ArtContext toArtContext(final @NotNull RuntimeStatsSnapshot stats) {
final @NotNull ArtContext art = new ArtContext();
art.setGcTotalCount(stats.gcCount);
art.setGcTotalTime(stats.gcTimeMs);
art.setGcBlockingCount(stats.blockingGcCount);
art.setGcBlockingTime(stats.blockingGcTimeMs);
art.setGcPreOomeCount(stats.preOomeGcCount);
art.setGcWaitingTime(stats.gcWaitingTimeMs);
art.setFreeMemory(stats.freeMemory);
art.setFreeMemoryUntilOome(stats.freeMemoryUntilOome);
art.setTotalMemory(stats.totalMemory);
art.setMaxMemory(stats.maxMemory);
return art;
}

@SuppressWarnings("FutureReturnValueIgnored")
private void deleteMarker() {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ public final class HangRecord {
private final long durationMs;
private final long startTimestampMs;
private final @NotNull List<AnrStackTrace> stackTraces;
private final @NotNull List<RuntimeStatsSnapshot> runtimeStats;
private final boolean endedAtMaxRecordingTime;

private HangRecord(final @NotNull Builder builder) {
this.durationMs = builder.durationMs;
this.startTimestampMs = builder.startTimestampMs;
this.stackTraces = Collections.unmodifiableList(new ArrayList<>(builder.stackTraces));
this.runtimeStats = Collections.unmodifiableList(new ArrayList<>(builder.runtimeStats));
this.endedAtMaxRecordingTime = builder.endedAtMaxRecordingTime;
}

Expand All @@ -37,6 +39,11 @@ public long getStartTimestampMs() {
return stackTraces;
}

/** The runtime counters, in the order they were read. Empty if no collector read them. */
public @NotNull List<RuntimeStatsSnapshot> getRuntimeStats() {
return runtimeStats;
}

/**
* Whether the hang was cut at the maximum recording time. The watched thread is then still
* blocked when the record is given to the listeners.
Expand All @@ -50,6 +57,7 @@ public static final class Builder {
private long durationMs;
private long startTimestampMs;
private final @NotNull List<AnrStackTrace> stackTraces = new ArrayList<>();
private final @NotNull List<RuntimeStatsSnapshot> runtimeStats = new ArrayList<>();
private boolean endedAtMaxRecordingTime;

public @NotNull Builder setDurationMs(final long durationMs) {
Expand All @@ -68,6 +76,11 @@ public static final class Builder {
return this;
}

public @NotNull Builder addRuntimeStats(final @NotNull RuntimeStatsSnapshot runtimeStats) {
this.runtimeStats.add(runtimeStats);
return this;
}

public @NotNull Builder setEndedAtMaxRecordingTime(final boolean endedAtMaxRecordingTime) {
this.endedAtMaxRecordingTime = endedAtMaxRecordingTime;
return this;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package io.sentry.android.core.hang;

import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;

/** Reads the runtime counters on each sampling tick of a recorded hang. */
@ApiStatus.Internal
public final class RuntimeStatsCollector implements HangDataCollector<RuntimeStatsSnapshot> {

private final @NotNull RuntimeStatsSource source;

public RuntimeStatsCollector(final @NotNull RuntimeStatsSource source) {
this.source = source;
}

@Override
public @NotNull RuntimeStatsSnapshot sample() {
return source.read();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package io.sentry.android.core.hang;

import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;

/**
* The runtime counters at one point in time. GC counters are cumulative for the process, times are
* in milliseconds and memory is in bytes. A value the runtime does not provide is {@code null}.
*/
@ApiStatus.Internal
public final class RuntimeStatsSnapshot {

public @Nullable Long gcCount;
public @Nullable Double gcTimeMs;
public @Nullable Long blockingGcCount;
public @Nullable Double blockingGcTimeMs;
public @Nullable Long preOomeGcCount;
public @Nullable Double gcWaitingTimeMs;
public @Nullable Long freeMemory;
public @Nullable Long freeMemoryUntilOome;
public @Nullable Long totalMemory;
public @Nullable Long maxMemory;
}
Loading
Loading